Debian Codegraph @

src/transform/castleboxes.pas

raw
1 {
2 Copyright 2003-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 { Axis-aligned 3D boxes (TBox3D). }
17 unit CastleBoxes;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Generics.Collections,
24 CastleVectors, CastleUtils, CastleTriangles, CastleRectangles;
25
26 type
27 EBox3DEmpty = class(Exception);
28
29 TGetIndexFromIndexNumFunc = function (indexNum: integer): integer of object;
30
31 { State of collision between a plane and some other object.
32
33 pcNone occurs only when the "other object" is empty
34 (TBox3D.IsEmpty, in case of box).
35 Other values mean that the other object is not empty.
36
37 pcOutside means that the whole object is on the side of the plane pointed
38 by plane direction (normal) vector. More formally, every point P
39 inserted into the plane equation will yield (P*PlaneNormal + PlaneD) > 0.
40
41 pcInside is the reverse of pcOutside:
42 the other object is on the side of plane
43 pointed by inverted plane normal. Every point inserted into plane
44 equation will yield < 0.
45
46 pcIntersecting is, well, the remaining case. It means that there's
47 for sure some point P of other object that, when inserted into
48 plane equation, will yield = 0. }
49 TPlaneCollision = (pcIntersecting, pcOutside, pcInside, pcNone);
50
51 TBoxCorners = array [0..7] of TVector3;
52
53 { Axis-aligned box. Rectangular prism with all sides parallel to basic planes
54 X = 0, Y = 0 and Z = 0. This is sometimes called AABB, "axis-aligned bounding
55 box". Many geometric operations are fast and easy on this type.
56
57 The actual box dimensions are stored inside the @link(Data) field, as two 3D points.
58 First point has always all the smaller coords, second point has all
59 the larger coords. I.e. always
60
61 @preformatted(
62 Data[0].X <= Data[1].X and
63 Data[0].Y <= Data[1].Y and
64 Data[0].Z <= Data[1].Z
65 )
66
67 The only exception is the special value TBox3D.Empty.
68
69 Note that the box may still have all sizes equal 0. Consider a 3D model with
70 only a single 3D point --- it's not empty, but all the sizes must be 0. }
71 TBox3D = record
72 strict private
73 function GetMin: TVector3;
74 procedure SetMin(const Value: TVector3);
75 function GetMax: TVector3;
76 procedure SetMax(const Value: TVector3);
77 public
78 Data: array [0..1] of TVector3;
79
80 { Special TBox3D value meaning "bounding box is empty".
81 This is different than just bounding box with zero sizes,
82 as bounding box with zero sizes still has some position.
83 Empty bounding box doesn't contain any portion of 3D space. }
84 class function Empty: TBox3D; static;
85
86 { Check is box empty.
87 You can think of this function as "compare Box with TBox3D.Empty".
88
89 But actually it works a little faster, by utilizing the assumption
90 that TBox3D.Empty is the only allowed value that breaks
91 @code(Data[0].X <= Data[1].X) rule. }
92 function IsEmpty: boolean;
93
94 { The minimum 3D position within this box. Use only if not @link(IsEmpty),
95 in which case this is just a shortcut for @code(Data[0]). }
96 property Min: TVector3 read GetMin write SetMin;
97
98 { The maximum 3D position within this box. Use only if not @link(IsEmpty),
99 in which case this is just a shortcut for @code(Data[1]). }
100 property Max: TVector3 read GetMax write SetMax;
101
102 { Check is box empty or has all the sizes equal 0. }
103 function IsEmptyOrZero: boolean;
104
105 procedure CheckNonEmpty;
106
107 { Center of the box.
108 @raises(EBox3DEmpty If the Box is empty.) }
109 function Middle: TVector3; deprecated 'use Center';
110
111 { Center of the box.
112 @raises(EBox3DEmpty If the Box is empty.) }
113 function Center: TVector3;
114
115 { Average size of the box.
116 @raises(EBox3DEmpty If the Box is empty.) }
117 function AverageSize: Single; overload;
118
119 { Largest size of the box.
120 @raises(EBox3DEmpty If the Box is empty.) }
121 function MaxSize: Single; overload;
122
123 { Smallest size of the box.
124 @raises(EBox3DEmpty If the Box is empty.) }
125 function MinSize: Single; overload;
126
127 { Size in X (width) of the box.
128 @raises(EBox3DEmpty If the Box is empty.) }
129 function SizeX: Single;
130
131 { Size in Y (height) of the box.
132 @raises(EBox3DEmpty If the Box is empty.) }
133 function SizeY: Single;
134
135 { Size in Z (depth) of the box.
136 @raises(EBox3DEmpty If the Box is empty.) }
137 function SizeZ: Single;
138
139 { Average size of TBox3D, or EmptyBoxSize if box is empty.
140 @param(AllowZero Decides what to do when box is not empty but the result
141 would be zero, which means that the box is infinitely thin in all axes.
142 If @true, then result is just 0, otherwise it's EmptyBoxSize.) }
143 function AverageSize(const AllowZero: boolean;
144 const EmptyBoxSize: Single): Single; overload;
145
146 { Average size of TBox3D, or EmptyBoxSize if box is empty.
147 2D box projection is obtained by rejecting the IgnoreIndex coordinate
148 (must be 0, 1 or 2).
149
150 @param(AllowZero Decides what to do when box is not empty but the result
151 would be zero, which means that the box is infinitely thin in all axes.
152 If @true, then result is just 0, otherwise it's EmptyBoxSize.) }
153 function AverageSize2D(const AllowZero: boolean;
154 const EmptyBoxSize: Single; const IgnoreIndex: T3DAxis): Single; overload;
155
156 { Largest size of TBox3D, or EmptyBoxSize if box is empty.
157 @param(AllowZero Decides what to do when box is not empty but the result
158 would be zero, which means that the box is infinitely thin in all axes.
159 If @true, then result is just 0, otherwise it's EmptyBoxSize.) }
160 function MaxSize(const AllowZero: boolean;
161 const EmptyBoxSize: Single): Single; overload;
162
163 { Area of the six TBox3D sides, EmptyBoxArea if box is empty.
164 @param(AllowZero Decides what to do when box is not empty but the result
165 would be zero, which means that the box is infinitely thin in all axes.
166 If @true, then result is just 0, otherwise it's EmptyBoxSize.) }
167 function Area(const AllowZero: boolean;
168 const EmptyBoxArea: Single): Single;
169
170 { Decrease "minimum corner" by (AExpand, AExpand, AExpand) vector,
171 and increase "maximum corner" by the same vector.
172 So you get Box with all sizes increased by 2 * AExpand.
173
174 Box must not be empty.
175 Note that AExpand may be negative, but then you must be sure
176 that it doesn't make Box empty. }
177 procedure ExpandMe(const AExpand: Single); overload;
178
179 { Decrease "minimum corner" by AExpand vector,
180 and increase "maximum corner" by the same vector.
181 So you get Box with all sizes increased by 2 * AExpand.
182
183 Box must not be empty.
184 Note that AExpand may be negative, but then you must be sure
185 that it doesn't make Box empty. }
186 procedure ExpandMe(const AExpand: TVector3); overload;
187
188 function Grow(const AExpand: Single): TBox3D; overload;
189 function Grow(const AExpand: TVector3): TBox3D; overload;
190
191 function Expand(const AExpand: Single): TBox3D; overload; deprecated 'use Grow, consistent with TRectangle.Grow';
192 function Expand(const AExpand: TVector3): TBox3D; overload; deprecated 'use Grow, consistent with TRectangle.Grow';
193
194 { Check is the point inside the box.
195 Always false if Box is empty (obviously, no point is inside an empty box).
196
197 @groupBegin }
198 function Contains(const Point: TVector3): boolean; overload;
199
200 { Causes FPC errors about "duplicate ASM label",
201 see https://bugs.freepascal.org/view.php?id=32188 .
202 Also, it's not really very useful. }
203 //function Contains(const Point: TVector3Double): boolean; overload;
204
205 { }
206 function PointInside(const Point: TVector3): boolean; overload; deprecated 'use Contains method, which is consistent with TRectangle';
207
208 { Causes FPC errors about "duplicate ASM label",
209 see https://bugs.freepascal.org/view.php?id=32188 .
210 Also, it's not really very useful. }
211 //function PointInside(const Point: TVector3Double): boolean; overload; deprecated 'use Contains method, which is consistent with TRectangle';
212 { @groupEnd }
213
214 { Is the 2D point inside the 2D projection of the box, ignores the Z coord of box. }
215 function Contains2D(const Point: TVector2): boolean; overload;
216 function PointInside2D(const Point: TVector2): boolean; overload; deprecated 'use Contains2d method';
217
218 { Is the 2D point inside the 2D projection of the box.
219 2D projection (of point and box) is obtained by rejecting
220 the IgnoreIndex coordinate (must be 0, 1 or 2). }
221 function Contains2D(const Point: TVector3; const IgnoreIndex: T3DAxis): boolean; overload;
222 function PointInside2D(const Point: TVector3; const IgnoreIndex: T3DAxis): boolean; overload; deprecated 'use Contains2D method';
223
224 { Add another box to our box.
225 This calculates the smallest box that encloses both the current box,
226 and Box2. Doing @code(MyBox.Include(AnotherBox)) is equivalent to doing
227 @code(MyBox := MyBox + AnotherBox). }
228 procedure Include(const box2: TBox3D); overload;
229
230 { Make box larger, if necessary, to contain given Point. }
231 procedure Include(const Point: TVector3); overload;
232 procedure Include(const Points: TVector3List); overload;
233
234 { Make a box that contains given points. }
235 class function FromPoints(const Points: TVector3List): TBox3D; static;
236
237 { Three box sizes. }
238 function Sizes: TVector3; deprecated 'use Size';
239
240 { Three box sizes. Name consistent with TBoxNode.Size.
241 @raises(EBox3DEmpty If the Box is empty.) }
242 function Size: TVector3;
243
244 { Calculate eight corners of the box.}
245 procedure Corners(out AllPoints: TBoxCorners);
246 procedure GetAllPoints(AllPoints: PVector3Array); deprecated 'use Corners';
247
248 { Transform the Box by given matrix.
249 Since this is still an axis-aligned box, rotating etc. of the box
250 usually makes larger box.
251
252 Note that this is very optimized for Matrix with no projection
253 (where last row of the last matrix = [0, 0, 0, 1]). It still works
254 for all matrices (eventually fallbacks to simple "transform 8 corners and get
255 box enclosing them" method).
256
257 @raises(ETransformedResultInvalid When the Matrix will
258 transform some point to a direction (vector with 4th component
259 equal zero). In this case we just cannot interpret the result as a 3D point,
260 so we also cannot interpret the final result as a box.) }
261 function Transform(const Matrix: TMatrix4): TBox3D;
262
263 { Move Box. Does nothing if Box is empty. }
264 function Translate(const Translation: TVector3): TBox3D;
265
266 { Move Box, by -Translation. Does nothing if Box is empty. }
267 function AntiTranslate(const Translation: TVector3): TBox3D;
268
269 function ToNiceStr: string; deprecated 'use ToString';
270 function ToRawStr: string; deprecated 'use ToRawString';
271
272 function ToString: string;
273 function ToRawString: string;
274
275 procedure ClampVar(var point: TVector3); overload;
276
277 { Causes FPC errors about "duplicate ASM label",
278 see https://bugs.freepascal.org/view.php?id=32188 .
279 Also, it's not really very useful. }
280 // procedure ClampVar(var point: TVector3Double); overload;
281
282 { TryBoxRayClosestIntersection calculates intersection between the
283 ray (returns closest intersection to RayOrigin) and the box.
284
285 The box is treated just like a set of 6 rectangles in 3D.
286 This means that the intersection will always be placed on one of the
287 box sides, even if RayOrigin starts inside the box.
288 See TryBoxRayEntrance for the other version.
289
290 Returns also IntersectionDistance, which is the distance to the Intersection
291 relative to RayDirection (i.e. Intersection is always = RayOrigin +
292 IntersectionDistance * RayDirection).
293
294 @groupBegin }
295 function TryRayClosestIntersection(
296 out Intersection: TVector3;
297 out IntersectionDistance: Single;
298 const RayOrigin, RayDirection: TVector3): boolean; overload;
299 function TryRayClosestIntersection(
300 out Intersection: TVector3;
301 const RayOrigin, RayDirection: TVector3): boolean; overload;
302 function TryRayClosestIntersection(
303 out IntersectionDistance: Single;
304 const RayOrigin, RayDirection: TVector3): boolean; overload;
305 { @groupEnd }
306
307 { Intersection between the ray (returns closest intersection to RayOrigin)
308 and the box, treating the box as a filled volume.
309
310 If RayOrigin is inside the box, TryBoxRayEntrance simply returns
311 RayOrigin. If RayOrigin is outside of the box, the answer is the same
312 as with TryBoxRayClosestIntersection.
313
314 @groupBegin }
315 function TryRayEntrance(
316 out Entrance: TVector3; out EntranceDistance: Single;
317 const RayOrigin, RayDirection: TVector3): boolean; overload;
318 function TryRayEntrance(
319 out Entrance: TVector3;
320 const RayOrigin, RayDirection: TVector3): boolean; overload;
321 { @groupEnd }
322
323 function SegmentCollision(
324 const Segment1, Segment2: TVector3): boolean;
325
326 { Deprecated name for SegmentCollision. @deprecated @exclude }
327 function IsSegmentCollision(
328 const Segment1, Segment2: TVector3): boolean; deprecated;
329
330 { Collision between axis-aligned box (TBox3D) and 3D plane.
331 Returns detailed result as TPlaneCollision. }
332 function PlaneCollision(const Plane: TVector4): TPlaneCollision;
333
334 { Check is axis-aligned box (TBox3D) fully inside/outside the plane.
335
336 Inside/outside are defined as for TPlaneCollision:
337 Outside is where plane direction (normal) points.
338 Inside is where the @italic(inverted) plane direction (normal) points.
339
340 They work exactly like Box3DPlaneCollision, except they returns @true
341 when box is inside/outside (when Box3DPlaneCollision returned pcInside/pcOutside),
342 and @false otherwise.
343
344 For example Box3DPlaneCollisionInside doesn't differentiate between case
345 when box is empty, of partially intersects the plane, and is on the outside.
346 But it works (very slightly) faster.
347
348 @groupBegin }
349 function PlaneCollisionInside(const Plane: TVector4): boolean;
350 function PlaneCollisionOutside(const Plane: TVector4): boolean;
351 { @groupEnd }
352
353 function IsTriangleCollision(
354 const Triangle: TTriangle3): boolean;
355
356 { Smallest possible sphere completely enclosing the current box.
357 When this is empty (@link(IsEmpty)) we return
358 SphereRadiusSqr = 0 and an undefined SphereCenter.
359
360 @param(SphereCenter The calculated sphere center.)
361 @param(SphereRadiusSqr The calculated sphere radius, squared.
362
363 Use @code(Sqrt) to get the actual value.
364 Often the square of the radius is enough, and this way you can avoid
365 calculating expensive @code(Sqrt), and thus gain some speed.
366
367 But please remember the general guideline: "do not optimize when there's no need".
368 Sometimes it is simpler to just use @code(Sqrt) to get the actual radius,
369 and there's no measurable difference in performance.
370 So don't worry and do @code(SphereRadius := Sqrt(SphereRadiusSqr)).)
371 }
372 procedure BoundingSphere(
373 var SphereCenter: TVector3; var SphereRadiusSqr: Single);
374
375 { Does it have any common part with another box.
376 Better use @link(Collides),
377 which has a name consistent with @link(TFloatRectangle.Collides),
378 this method will be deprecated some day and later removed. }
379 function Collision(const Box2: TBox3D): boolean;
380
381 { Does it have any common part with another box. }
382 function Collides(const Box2: TBox3D): boolean;
383
384 { Radius of the minimal sphere that contains this box.
385 Sphere center is assumed to be in (0, 0, 0).
386 0 if box is empty. }
387 function Radius: Single;
388
389 { Radius of the minimal circle that contains the 2D projection of this box.
390 2D box projection is obtained by rejecting the IgnoreIndex coordinate
391 (must be 0, 1 or 2).
392 Circle center is assumed to be in (0, 0).
393 0 if box is empty. }
394 function Radius2D(const IgnoreIndex: T3DAxis): Single;
395
396 { Check for collision between box and sphere, fast @italic(but not
397 entirely correct).
398
399 This considers a Box enlarged by SphereRadius in each direction.
400 Then checks whether SphereCenter is inside such enlarged Box.
401 So this check will incorrectly report collision while in fact
402 there's no collision in the case when the sphere center is near
403 the corner of the Box.
404
405 So this check is not 100% correct. But often this is good enough
406 --- in games, if you know that the SphereRadius is going to be
407 relatively small compared to the Box, this may be perfectly
408 acceptable. And it's fast. }
409 function SphereSimpleCollision(
410 const SphereCenter: TVector3; const SphereRadius: Single): boolean;
411
412 { Check box vs sphere collision. }
413 function SphereCollision(
414 const SphereCenter: TVector3; const SphereRadius: Single): boolean;
415
416 { Check box vs sphere collision in 2D (ignores Z coordinates of box). }
417 function SphereCollision2D(
418 const SphereCenter: TVector2; const SphereRadius: Single): boolean;
419
420 { Calculate a plane in 3D space with direction = given Direction, moved
421 maximally in Direction and still intersecting the given Box.
422
423 For example, if Direction = -Z = (0, 0, -1), then this will return
424 the bottom plane of this box. For Direction = (1, 1, 1), this will return
425 a plane intersecting the Data[1] (maximum) point, with slope = (1, 1, 1).
426 The resulting plane always intersects at least one of the 8 corners of the box.
427
428 @raises(EBox3DEmpty If the Box is empty.) }
429 function MaximumPlane(const Direction: TVector3): TVector4;
430
431 { Calculate a plane in 3D space with direction = given Direction, moved
432 such that it touches the Box but takes minimum volume of this box.
433
434 For example, if Direction = +Z = (0, 0, 1), then this will return
435 the bottom plane of this box. For Direction = (1, 1, 1), this will return
436 a plane intersecting the Data[0] (minimum) point, with slope = (1, 1, 1).
437 The resulting plane always intersects at least one of the 8 corners of the box.
438
439 @raises(EBox3DEmpty If the Box is empty.) }
440 function MinimumPlane(const Direction: TVector3): TVector4;
441
442 { Farthest corner of the box in the given Direction.
443 @raises(EBox3DEmpty If the Box is empty.) }
444 function MaximumCorner(const Direction: TVector3): TVector3;
445
446 { Corner of the box such that the rest of the box lies in the given
447 Direction from this corner.
448 @raises(EBox3DEmpty If the Box is empty.) }
449 function MinimumCorner(const Direction: TVector3): TVector3;
450
451 { Calculate the distances between a given 3D point and a box.
452 MinDistance is the distance to the closest point of the box,
453 MaxDistance is the distance to the farthest point of the box.
454
455 Note that always MinDistance <= MaxDistance.
456 Note that both distances are always >= 0.
457
458 When the point is inside the box, it works correct too: minimum distance
459 is zero in this case.
460
461 @raises EBox3DEmpty When used with an empty box.
462
463 TODO: calculation of MinDistance is not perfect now. We assume that
464 the closest/farthest point of the box is one of the 8 box corners.
465 Which may not be true in case of the closest point, because it may
466 lie in the middle of some box face (imagine a sphere with increasing
467 radius reaching from a point to a box). So our minimum may be a *little*
468 too large. }
469 procedure PointDistances(const P: TVector3;
470 out MinDistance, MaxDistance: Single);
471
472 { Calculate the distances along a direction to a box.
473 The idea is that you have a 3D plane orthogonal to direction Dir
474 and passing through Point. You can move this plane,
475 but you have to keep it's direction constant.
476 MinDistance is the minimal distance along the Dir that you can
477 move this plane, such that it touches the box.
478 MaxDistance is the maximum such distance.
479
480 Note that always MinDistance <= MaxDistance.
481 Note that one distance (MinDistance) or both distances may be negative.
482
483 As a practical example: imagine a DirectionalLight (light rays are
484 parallel) that has a location. Now MinDistance and MaxDistance give
485 ranges of depth where the Box is, as seen from the light source.
486
487 @raises EBox3DEmpty When used with an empty box. }
488 procedure DirectionDistances(
489 const Point, Dir: TVector3;
490 out MinDistance, MaxDistance: Single);
491
492 (* MaxDistanceAlongDirection not used, so not defined for now.
493 { Maximum distance from Point to one of box corners, along the given direction.
494
495 Like DirectionDistances, but only returns MaxDistance,
496 and is faster. }
497 function MaxDistanceAlongDirection(const Point, Dir: TVector3): Single;
498 *)
499
500 { Shortest distance between the box and a point.
501 Always zero when the point is inside the box.
502
503 @raises EBox3DEmpty When used with an empty box. }
504 function PointDistance(const Point: TVector3): Single;
505
506 { Shortest distance between the box and a point, squared.
507 Always zero when the point is inside the box.
508
509 @raises EBox3DEmpty When used with an empty box. }
510 function PointDistanceSqr(const Point: TVector3): Single;
511
512 (*
513 { Maximum distance between the box and a point.
514 Returns EmptyBoxDistance when box is empty. }
515 function PointMaxDistance(const Point: TVector3;
516 const EmptyBoxDistance: Single): Single;
517
518 { Maximum distance between the box and a point, squared.
519 Returns EmptyBoxDistance when box is empty. }
520 function PointMaxDistanceSqr(const Point: TVector3;
521 const EmptyBoxDistance: Single): Single;
522 *)
523
524 function Equal(const Box2: TBox3D): boolean; overload;
525 function Equal(const Box2: TBox3D; const Epsilon: Single): boolean; overload;
526
527 { Diagonal of the box, zero if empty. }
528 function Diagonal: Single;
529
530 function RectangleXY: TFloatRectangle;
531 function RectangleXZ: TFloatRectangle;
532
533 { Project box along a given direction to a 2D rectangle.
534 @bold(Assumes that Dir, Side and Up vectors are already
535 orthogonal and normalized.) }
536 function OrthoProject(const Pos, Dir, Side, Up: TVector3): TFloatRectangle;
537
538 { Compare two bounding boxes based
539 on their Z coordinates, suitable for depth sorting in 2D.
540 Follows the algorithm documented at @link(sort2D).
541 Returns -1 if A < B, 1 if A > B, 0 if A = B.
542
543 Using this with a typical sorting function will result
544 in boxes back-to-front ordering, which means that the farthest
545 box will be first. }
546 class function CompareBackToFront2D(
547 const A, B: TBox3D): Integer; static;
548 deprecated 'rely on TCastleViewport.BlendingSort to sort shapes';
549
550 class operator {$ifdef FPC}+{$else}Add{$endif} (const Box1, Box2: TBox3D): TBox3D;
551 class operator {$ifdef FPC}+{$else}Add{$endif} (const B: TBox3D; const V: TVector3): TBox3D; deprecated 'use TBox3D.Translate. Operator is ambiguous (do we add a point, or translate?)';
552 class operator {$ifdef FPC}+{$else}Add{$endif} (const V: TVector3; const B: TBox3D): TBox3D; deprecated 'use TBox3D.Translate. Operator is ambiguous (do we add a point, or translate?)';
553
554 { Convert from center and size vector. Empty box has size (-1,-1,-1). }
555 class function FromCenterSize(const ACenter, ASize: TVector3): TBox3D; static;
556 { Convert to center and size vector. Empty box has size (-1,-1,-1). }
557 procedure ToCenterSize(out ACenter, ASize: TVector3);
558 end;
559
560 TBox3DBool = array [boolean] of TVector3;
561 PBox3D = ^TBox3D;
562
563 const
564 { Special TBox3D value meaning "bounding box is empty".
565 This is different than just bounding box with zero sizes,
566 as bounding box with zero sizes still has some position.
567 Empty bounding box doesn't contain any portion of 3D space. }
568 EmptyBox3D: TBox3D = (Data: ((X: 0; Y: 0; Z: 0), (X: -1; Y: -1; Z: -1))) deprecated 'use TBox3D.Empty';
569
570 type
571 TBox3DList = {$ifdef FPC}specialize{$endif} TStructList<TBox3D>;
572
573 { Construct TBox3D value from a minimum and maximum 3D point. }
574 function Box3D(const p0, p1: TVector3): TBox3D;
575
576 { Construct TBox3D value from a center and size.
577 When any Size component is < 0, we return an empty box (@link(TBox3D.Empty)).
578 This is consistent with X3D bboxCenter/Size definition e.g. at X3D Group node,
579 see http://www.web3d.org/documents/specifications/19775-1/V3.2/Part01/components/group.html#Group
580 @groupBegin }
581 function Box3DAroundPoint(const Pt: TVector3; Size: Single): TBox3D; overload;
582 function Box3DAroundPoint(const Pt: TVector3; Size: TVector3): TBox3D; overload;
583 { @groupEnd }
584
585 { Calculate bounding box of a set of 3D points.
586 This calculates the smallest possible box enclosing all given points.
587 For VertsCount = 0 this returns TBox3D.Empty.
588
589 Overloaded version with Transform parameter transforms each point
590 by given matrix.
591
592 Overloaded version with GetVertex as a function uses GetVertex to query
593 for indexes from [0 .. VertsCount - 1] range.
594
595 As usual, VertsStride = 0 means VertsStride = SizeOf(TVector3).
596
597 @groupBegin }
598 function CalculateBoundingBox(
599 Verts: PVector3; VertsCount: Cardinal; VertsStride: Cardinal): TBox3D; overload;
600 function CalculateBoundingBox(
601 Verts: PVector3; VertsCount: Cardinal; VertsStride: Cardinal;
602 const Transform: TMatrix4): TBox3D; overload;
603 function CalculateBoundingBox(Verts: TVector3List): TBox3D; overload;
604 function CalculateBoundingBox(Verts: TVector3List;
605 const Transform: TMatrix4): TBox3D; overload;
606 function CalculateBoundingBox(
607 GetVertex: TGetVertexFromIndexFunc;
608 VertsCount: integer): TBox3D; overload;
609 { @groupEnd }
610
611 { Calculate bounding box of a set of indexed 3D points.
612
613 This is much like CalculateBoundingBox, except there are two functions:
614 For each number in [0 .. VertsIndicesCount - 1] range, GetVertIndex
615 returns an index. If this index is >= 0 then it's used to query
616 GetVertex function to get actual vertex position.
617
618 Indexes < 0 are ignored, this is sometimes comfortable. E.g. for X3D models,
619 you often have a list of indexes with -1 in between marking end of faces.
620
621 Returns smallest box enclosing all vertexes.
622
623 Overloaded version with Transform parameter transforms each point
624 by given matrix.
625
626 @groupBegin }
627 function CalculateBoundingBoxFromIndices(
628 const GetVertIndex: TGetIndexFromIndexNumFunc;
629 const VertsIndicesCount: integer;
630 const GetVertex: TGetVertexFromIndexFunc): TBox3D; overload;
631 function CalculateBoundingBoxFromIndices(
632 const GetVertIndex: TGetIndexFromIndexNumFunc;
633 const VertsIndicesCount: integer;
634 const GetVertex: TGetVertexFromIndexFunc;
635 const Transform: TMatrix4): TBox3D; overload;
636 { @groupEnd }
637
638 function TriangleBoundingBox(const T: TTriangle3): TBox3D;
639
640 { Tests for collision between box3d centered around (0, 0, 0)
641 and a plane.
642
643 Note that you can't express empty box3d here: all BoxHalfSize items
644 must be >= 0. The case when size = 0 is considered like infintely small
645 box in some dimension (e.g. if all three sizes are = 0 then the box
646 becomes a point). }
647 function IsCenteredBox3DPlaneCollision(
648 const BoxHalfSize: TVector3;
649 const Plane: TVector4): boolean;
650
651 { Smallest possible box enclosing a sphere with Center, Radius. }
652 function BoundingBox3DFromSphere(const Center: TVector3;
653 const Radius: Single): TBox3D;
654
655 type
656 TBox3DEvent = function: TBox3D of object;
657
658 implementation
659
660 uses Math;
661
662 // Internal IsCenteredBox3DPlaneCollision alternative with Double-precision.
663 function IsCenteredBox3DPlaneCollisionDouble(
664 const BoxHalfSize: TVector3Double;
665 const Plane: TVector4Double): boolean; forward;
666
667 { Special procedures for raising errors, to make GetMin and friends ultra-fast,
668 so that they don't need an implicit try-finally section because they have a string. }
669
670 procedure RaiseGetMin;
671 begin
672 raise EBox3DEmpty.Create('Empty box 3D (Box.IsEmpty), cannot get minimum point');
673 end;
674
675 procedure RaiseSetMin;
676 begin
677 raise EBox3DEmpty.Create('Empty box 3D (Box.IsEmpty), cannot set minimum point. Set the whole box to non-empty using the global Box3D() function');
678 end;
679
680 procedure RaiseGetMax;
681 begin
682 raise EBox3DEmpty.Create('Empty box 3D (Box.IsEmpty), cannot get maximum point');
683 end;
684
685 procedure RaiseSetMax;
686 begin
687 raise EBox3DEmpty.Create('Empty box 3D (Box.IsEmpty), cannot set maximum point. Set the whole box to non-empty using the global Box3D() function');
688 end;
689
690 procedure RaiseRadius2DInvalidIgnoreIndex;
691 begin
692 raise EInternalError.Create('Invalid IgnoreIndex for TBox3D.Radius2D');
693 end;
694
695 { TBox3D --------------------------------------------------------------------- }
696
697 function TBox3D.GetMin: TVector3;
698 begin
699 if IsEmpty then RaiseGetMin;
700 Result := Data[0];
701 end;
702
703 procedure TBox3D.SetMin(const Value: TVector3);
704 begin
705 if IsEmpty then RaiseSetMin;
706 Data[0] := Value;
707 end;
708
709 function TBox3D.GetMax: TVector3;
710 begin
711 if IsEmpty then RaiseGetMax;
712 Result := Data[1];
713 end;
714
715 procedure TBox3D.SetMax(const Value: TVector3);
716 begin
717 if IsEmpty then RaiseSetMax;
718 Data[1] := Value;
719 end;
720
721 class function TBox3D.Empty: TBox3D;
722 const
723 R: TBox3D = (Data: ((X: 0; Y: 0; Z: 0), (X: -1; Y: -1; Z: -1)));
724 begin
725 Result := R;
726 end;
727
728 function TBox3D.IsEmpty: boolean;
729 begin
730 Result := Data[0].X > Data[1].X;
731 end;
732
733 function TBox3D.IsEmptyOrZero: boolean;
734 begin
735 Result := (Data[0].X > Data[1].X) or
736 ( (Data[0].X = Data[1].X) and
737 (Data[0].Y = Data[1].Y) and
738 (Data[0].Z = Data[1].Z)
739 );
740 end;
741
742 procedure TBox3D.CheckNonEmpty;
743 begin
744 if IsEmpty then
745 raise EBox3DEmpty.Create('Empty box 3d: no middle point, no sizes etc.');
746 end;
747
748 function TBox3D.Center: TVector3;
749 begin
750 CheckNonEmpty;
751 Result.X := (Data[0].X + Data[1].X) / 2;
752 Result.Y := (Data[0].Y + Data[1].Y) / 2;
753 Result.Z := (Data[0].Z + Data[1].Z) / 2;
754 end;
755
756 function TBox3D.Middle: TVector3;
757 begin
758 Result := Center;
759 end;
760
761 function TBox3D.AverageSize: Single;
762 begin
763 CheckNonEmpty;
764 Result := (
765 (Data[1].X - Data[0].X) +
766 (Data[1].Y - Data[0].Y) +
767 (Data[1].Z - Data[0].Z)) / 3;
768 end;
769
770 function TBox3D.AverageSize(const AllowZero: boolean;
771 const EmptyBoxSize: Single): Single;
772 begin
773 if IsEmpty then
774 Result := EmptyBoxSize else
775 begin
776 Result := ((Data[1].X - Data[0].X) +
777 (Data[1].Y - Data[0].Y) +
778 (Data[1].Z - Data[0].Z)) / 3;
779 if (not AllowZero) and (Result = 0) then
780 Result := EmptyBoxSize;
781 end;
782 end;
783
784 function TBox3D.AverageSize2D(const AllowZero: boolean;
785 const EmptyBoxSize: Single; const IgnoreIndex: T3DAxis): Single;
786 begin
787 if IsEmpty then
788 Result := EmptyBoxSize else
789 begin
790 case IgnoreIndex of
791 0: Result := ((Data[1].Y - Data[0].Y) +
792 (Data[1].Z - Data[0].Z)) / 2;
793 1: Result := ((Data[1].X - Data[0].X) +
794 (Data[1].Z - Data[0].Z)) / 2;
795 2: Result := ((Data[1].X - Data[0].X) +
796 (Data[1].Y - Data[0].Y)) / 2;
797 {$ifndef COMPILER_CASE_ANALYSIS}
798 else raise EInternalError.Create(20221209);
799 {$endif}
800 end;
801 if (not AllowZero) and (Result = 0) then
802 Result := EmptyBoxSize;
803 end;
804 end;
805
806 function TBox3D.MaxSize: Single;
807 begin
808 CheckNonEmpty;
809 Result := MaxValue([
810 Data[1].X - Data[0].X,
811 Data[1].Y - Data[0].Y,
812 Data[1].Z - Data[0].Z
813 ]);
814 end;
815
816 function TBox3D.MaxSize(const AllowZero: boolean;
817 const EmptyBoxSize: Single): Single;
818 begin
819 if IsEmpty then
820 Result := EmptyBoxSize else
821 begin
822 Result := MaxValue([
823 Data[1].X - Data[0].X,
824 Data[1].Y - Data[0].Y,
825 Data[1].Z - Data[0].Z
826 ]);
827 if (not AllowZero) and (Result = 0) then
828 Result := EmptyBoxSize;
829 end;
830 end;
831
832 function TBox3D.Area(const AllowZero: boolean;
833 const EmptyBoxArea: Single): Single;
834 var
835 A, B, C: Single;
836 begin
837 if IsEmpty then
838 Result := EmptyBoxArea else
839 begin
840 A := Data[1].X - Data[0].X;
841 B := Data[1].Y - Data[0].Y;
842 C := Data[1].Z - Data[0].Z;
843 Result := 2*A*B + 2*B*C + 2*A*C;
844 if (not AllowZero) and (Result = 0) then
845 Result := EmptyBoxArea;
846 end;
847 end;
848
849 function TBox3D.MinSize: Single;
850 begin
851 CheckNonEmpty;
852
853 Result := MinValue([
854 Data[1].X - Data[0].X,
855 Data[1].Y - Data[0].Y,
856 Data[1].Z - Data[0].Z
857 ]);
858
859 { Another version is below (but this is slower without any benefit...)
860
861 var sizes: TVector3;
862 sizes := Box3DSizes(box);
863 result := sizes[MaxVectorCoord(sizes)];
864 }
865 end;
866
867 function TBox3D.SizeX: Single;
868 begin
869 CheckNonEmpty;
870 Result := Data[1].X - Data[0].X;
871 end;
872
873 function TBox3D.SizeY: Single;
874 begin
875 CheckNonEmpty;
876 Result := Data[1].Y - Data[0].Y;
877 end;
878
879 function TBox3D.SizeZ: Single;
880 begin
881 CheckNonEmpty;
882 Result := Data[1].Z - Data[0].Z;
883 end;
884
885 procedure TBox3D.ExpandMe(const AExpand: Single);
886 begin
887 Data[0].X := Data[0].X - AExpand;
888 Data[0].Y := Data[0].Y - AExpand;
889 Data[0].Z := Data[0].Z - AExpand;
890
891 Data[1].X := Data[1].X + AExpand;
892 Data[1].Y := Data[1].Y + AExpand;
893 Data[1].Z := Data[1].Z + AExpand;
894 end;
895
896 procedure TBox3D.ExpandMe(const AExpand: TVector3);
897 begin
898 Data[0].X := Data[0].X - AExpand.X;
899 Data[0].Y := Data[0].Y - AExpand.Y;
900 Data[0].Z := Data[0].Z - AExpand.Z;
901
902 Data[1].X := Data[1].X + AExpand.X;
903 Data[1].Y := Data[1].Y + AExpand.Y;
904 Data[1].Z := Data[1].Z + AExpand.Z;
905 end;
906
907 function TBox3D.Grow(const AExpand: Single): TBox3D;
908 begin
909 if IsEmpty then Exit(Empty);
910
911 Result.Data[0].X := Data[0].X - AExpand;
912 Result.Data[0].Y := Data[0].Y - AExpand;
913 Result.Data[0].Z := Data[0].Z - AExpand;
914
915 Result.Data[1].X := Data[1].X + AExpand;
916 Result.Data[1].Y := Data[1].Y + AExpand;
917 Result.Data[1].Z := Data[1].Z + AExpand;
918 end;
919
920 function TBox3D.Grow(const AExpand: TVector3): TBox3D;
921 begin
922 if IsEmpty then Exit(Empty);
923
924 Result.Data[0].X := Data[0].X - AExpand.X;
925 Result.Data[0].Y := Data[0].Y - AExpand.Y;
926 Result.Data[0].Z := Data[0].Z - AExpand.Z;
927
928 Result.Data[1].X := Data[1].X + AExpand.X;
929 Result.Data[1].Y := Data[1].Y + AExpand.Y;
930 Result.Data[1].Z := Data[1].Z + AExpand.Z;
931 end;
932
933 function TBox3D.Expand(const AExpand: Single): TBox3D;
934 begin
935 Result := Grow(AExpand);
936 end;
937
938 function TBox3D.Expand(const AExpand: TVector3): TBox3D;
939 begin
940 Result := Grow(AExpand);
941 end;
942
943 function TBox3D.Contains(const Point: TVector3): boolean;
944 begin
945 if IsEmpty then Exit(false);
946 Result :=
947 (Data[0].X <= Point.X) and (Point.X <= Data[1].X) and
948 (Data[0].Y <= Point.Y) and (Point.Y <= Data[1].Y) and
949 (Data[0].Z <= Point.Z) and (Point.Z <= Data[1].Z);
950 end;
951
952 { Causes FPC error:
953 Error: Asm: Duplicate label CASTLEBOXES/home/michalis/bin/castle-engineTBOX3D_$__$$_CONTAINS$TGENERICVECTOR3$$BOOLEAN
954 See https://bugs.freepascal.org/view.php?id=32188
955
956 function TBox3D.Contains(const Point: TVector3Double): boolean;
957 begin
958 if IsEmpty then Exit(false);
959 Result :=
960 (Data[0].X <= Point.X) and (Point.X <= Data[1].X) and
961 (Data[0].Y <= Point.Y) and (Point.Y <= Data[1].Y) and
962 (Data[0].Z <= Point.Z) and (Point.Z <= Data[1].Z);
963 end;
964 }
965
966 function TBox3D.PointInside(const Point: TVector3): boolean;
967 begin
968 Result := Contains(Point);
969 end;
970
971 { Causes FPC error:
972 Error: Asm: Duplicate label CASTLEBOXES/home/michalis/bin/castle-engineTBOX3D_$__$$_POINTINSIDE$TGENERICVECTOR3$$BOOLEAN
973 See https://bugs.freepascal.org/view.php?id=32188
974
975 function TBox3D.PointInside(const Point: TVector3Double): boolean;
976 begin
977 Result := Contains(Point);
978 end;
979 }
980
981 { Separated from Contains2D, to not slowdown it by implicit
982 try/finally section because we use string. }
983 procedure Contains2D_InvalidIgnoreIndex;
984 begin
985 raise EInternalError.Create('Invalid IgnoreIndex for TBox3D.Contains2D');
986 end;
987
988 function TBox3D.Contains2D(const Point: TVector2): boolean;
989 begin
990 if IsEmpty then Exit(false);
991 Result :=
992 (Data[0].X <= Point.X) and (Point.X <= Data[1].X) and
993 (Data[0].Y <= Point.Y) and (Point.Y <= Data[1].Y);
994 end;
995
996 function TBox3D.Contains2D(const Point: TVector3;
997 const IgnoreIndex: T3DAxis): boolean;
998 begin
999 if IsEmpty then Exit(false);
1000 case IgnoreIndex of
1001 0: Result :=
1002 (Data[0].Y <= Point.Y) and (Point.Y <= Data[1].Y) and
1003 (Data[0].Z <= Point.Z) and (Point.Z <= Data[1].Z);
1004 1: Result :=
1005 (Data[0].Z <= Point.Z) and (Point.Z <= Data[1].Z) and
1006 (Data[0].X <= Point.X) and (Point.X <= Data[1].X);
1007 2: Result :=
1008 (Data[0].X <= Point.X) and (Point.X <= Data[1].X) and
1009 (Data[0].Y <= Point.Y) and (Point.Y <= Data[1].Y);
1010 {$ifndef COMPILER_CASE_ANALYSIS}
1011 else
1012 begin
1013 Contains2D_InvalidIgnoreIndex;
1014 Result := false; // just silence Delphi warning
1015 end;
1016 {$endif}
1017 end;
1018 end;
1019
1020 function TBox3D.PointInside2D(const Point: TVector2): boolean;
1021 begin
1022 Result := Contains2D(Point);
1023 end;
1024
1025 function TBox3D.PointInside2D(const Point: TVector3;
1026 const IgnoreIndex: T3DAxis): boolean;
1027 begin
1028 Result := Contains2D(Point, IgnoreIndex);
1029 end;
1030
1031 procedure TBox3D.Include(const box2: TBox3D);
1032 begin
1033 if Box2.IsEmpty then
1034 Exit else
1035 if IsEmpty then
1036 Data := Box2.Data else
1037 begin
1038 MinVar(Data[0].X, box2.Data[0].X);
1039 MaxVar(Data[1].X, box2.Data[1].X);
1040 MinVar(Data[0].Y, box2.Data[0].Y);
1041 MaxVar(Data[1].Y, box2.Data[1].Y);
1042 MinVar(Data[0].Z, box2.Data[0].Z);
1043 MaxVar(Data[1].Z, box2.Data[1].Z);
1044 end;
1045 end;
1046
1047 procedure TBox3D.Include(const Point: TVector3);
1048 begin
1049 if IsEmpty then
1050 begin
1051 Data[0] := Point;
1052 Data[1] := Point;
1053 end else
1054 begin
1055 MinVar(Data[0].X, Point.X);
1056 MaxVar(Data[1].X, Point.X);
1057 MinVar(Data[0].Y, Point.Y);
1058 MaxVar(Data[1].Y, Point.Y);
1059 MinVar(Data[0].Z, Point.Z);
1060 MaxVar(Data[1].Z, Point.Z);
1061 end;
1062 end;
1063
1064 procedure TBox3D.Include(const Points: TVector3List);
1065 var
1066 V: TVector3;
1067 I, StartIndex: Integer;
1068 begin
1069 if IsEmpty then
1070 begin
1071 Data[0] := Points.L[0];
1072 Data[1] := Points.L[0];
1073 StartIndex := 1;
1074 end else
1075 StartIndex := 0;
1076
1077 for I := StartIndex to Points.Count - 1 do
1078 begin
1079 V := Points.L[I];
1080 MinVar(Data[0].X, V.X);
1081 MaxVar(Data[1].X, V.X);
1082 MinVar(Data[0].Y, V.Y);
1083 MaxVar(Data[1].Y, V.Y);
1084 MinVar(Data[0].Z, V.Z);
1085 MaxVar(Data[1].Z, V.Z);
1086 end;
1087 end;
1088
1089 class function TBox3D.FromPoints(const Points: TVector3List): TBox3D;
1090 var
1091 V: TVector3;
1092 I: Integer;
1093 begin
1094 if Points.Count = 0 then
1095 Result := TBox3D.Empty
1096 else
1097 begin
1098 Result.Data[0] := Points.L[0];
1099 Result.Data[1] := Points.L[0];
1100 for I := 1 to Points.Count - 1 do
1101 begin
1102 { Note: On Delphi, we *have to* use L[...] below and depend on $pointermath on,
1103 instead of using List^[...].
1104 That's because on Delphi, List^[...] may have too small (declared) upper size
1105 due to Delphi not supporting SizeOf(T) in generics.
1106 See https://github.com/castle-engine/castle-engine/issues/474 . }
1107 V := Points.L[I];
1108 MinVar(Result.Data[0].X, V.X);
1109 MaxVar(Result.Data[1].X, V.X);
1110 MinVar(Result.Data[0].Y, V.Y);
1111 MaxVar(Result.Data[1].Y, V.Y);
1112 MinVar(Result.Data[0].Z, V.Z);
1113 MaxVar(Result.Data[1].Z, V.Z);
1114 end;
1115 end;
1116 end;
1117
1118 function TBox3D.Size: TVector3;
1119 begin
1120 CheckNonEmpty;
1121 Result.X := Data[1].X - Data[0].X;
1122 Result.Y := Data[1].Y - Data[0].Y;
1123 Result.Z := Data[1].Z - Data[0].Z;
1124 end;
1125
1126 function TBox3D.Sizes: TVector3;
1127 begin
1128 Result := Size;
1129 end;
1130
1131 procedure TBox3D.GetAllPoints(AllPoints: PVector3Array);
1132 begin
1133 AllPoints^[0] := Vector3(Data[0].X, Data[0].Y, Data[0].Z);
1134 AllPoints^[1] := Vector3(Data[0].X, Data[0].Y, Data[1].Z);
1135 AllPoints^[2] := Vector3(Data[0].X, Data[1].Y, Data[0].Z);
1136 AllPoints^[3] := Vector3(Data[0].X, Data[1].Y, Data[1].Z);
1137
1138 AllPoints^[4] := Vector3(Data[1].X, Data[0].Y, Data[0].Z);
1139 AllPoints^[5] := Vector3(Data[1].X, Data[0].Y, Data[1].Z);
1140 AllPoints^[6] := Vector3(Data[1].X, Data[1].Y, Data[0].Z);
1141 AllPoints^[7] := Vector3(Data[1].X, Data[1].Y, Data[1].Z);
1142 end;
1143
1144 procedure TBox3D.Corners(out AllPoints: TBoxCorners);
1145 begin
1146 {$warnings off} // using deprecated knowingly
1147 GetAllPoints(@AllPoints);
1148 {$warnings on}
1149 end;
1150
1151 function TBox3D.Transform(
1152 const Matrix: TMatrix4): TBox3D;
1153
1154 function Slower(const Matrix: TMatrix4): TBox3D;
1155 var
1156 BoxPoints: TBoxCorners;
1157 i: integer;
1158 begin
1159 Corners(BoxPoints);
1160 for i := 0 to 7 do BoxPoints[i] := Matrix.MultPoint(BoxPoints[i]);
1161
1162 { Non-optimized version:
1163 Result := CalculateBoundingBox(@BoxPoints, 8, 0);
1164
1165 But it turns out that the code below, that does essentially the same
1166 thing as CalculateBoundingBox implementation, works noticeably faster.
1167 This is noticeable on "The Castle" with many creatures: then a considerable
1168 time is spend inside TCreature.BoundingBox, that must calculate
1169 transformed bounding boxes.
1170 }
1171
1172 Result.Data[0] := BoxPoints[0];
1173 Result.Data[1] := BoxPoints[0];
1174 for I := 1 to High(BoxPoints) do
1175 begin
1176 if BoxPoints[I].X < Result.Data[0].X then Result.Data[0].X := BoxPoints[I].X;
1177 if BoxPoints[I].Y < Result.Data[0].Y then Result.Data[0].Y := BoxPoints[I].Y;
1178 if BoxPoints[I].Z < Result.Data[0].Z then Result.Data[0].Z := BoxPoints[I].Z;
1179
1180 if BoxPoints[I].X > Result.Data[1].X then Result.Data[1].X := BoxPoints[I].X;
1181 if BoxPoints[I].Y > Result.Data[1].Y then Result.Data[1].Y := BoxPoints[I].Y;
1182 if BoxPoints[I].Z > Result.Data[1].Z then Result.Data[1].Z := BoxPoints[I].Z;
1183 end;
1184 end;
1185
1186 function Faster(const Matrix: TMatrix4): TBox3D;
1187 { Reasoning why this works Ok: look at Slower approach, and imagine
1188 how each of the 8 points is multiplied by the same matrix.
1189 Each of the 8 points is
1190
1191 ( Data[0][0] or Data[1][0],
1192 Data[0][1] or Data[1][1],
1193 Data[0][2] or Data[1][2],
1194 1 )
1195
1196 To calculate X components of 8 resulting points, you multiply 8 original
1197 points by the same Matrix row. Since we're only interested in the minimum
1198 and maximum X component, we can actually just take
1199
1200 Result[0][0] := ( min( Matrix[0, 0] * Data[0][0], Matrix[0, 0] * Data[1][0] ),
1201 min( Matrix[1, 0] * Data[0][1], Matrix[1, 0] * Data[1][1] ),
1202 min( Matrix[2, 0] * Data[0][2], Matrix[2, 0] * Data[1][2] ),
1203 Matrix[3, 0] )
1204
1205 Result[0][1] is the same, but with max instead of min.
1206 This way we fully calculated X components.
1207
1208 Idea from http://www.soe.ucsc.edu/~pang/160/f98/Gems/Gems/TransBox.c,
1209 see also http://www.gamedev.net/community/forums/topic.asp?topic_id=349370.
1210
1211 This is 2-3 times faster than Slower (compiled with -dRELEASE, like
1212 0.44 to 0.13 =~ 3.3 times faster). See
1213 testcastleboxes.pas for speed (and correctness) test. }
1214 var
1215 I, J: Integer;
1216 A, B: Single;
1217 begin
1218 { Initially, both Result corners are copies of Matrix[3][0..2]
1219 (the "translate" numbers of Matrix) }
1220 Move(Matrix.Data[3], Result.Data[0], SizeOf(Result.Data[0]));
1221 Move(Matrix.Data[3], Result.Data[1], SizeOf(Result.Data[1]));
1222
1223 for I := 0 to 2 do
1224 begin
1225 { Calculate Result[0].Data[I], Result[1].Data[I] }
1226 for J := 0 to 2 do
1227 begin
1228 A := Matrix.Data[J, I] * Data[0].Data[J];
1229 B := Matrix.Data[J, I] * Data[1].Data[J];
1230 if A < B then
1231 begin
1232 Result.Data[0].Data[I] := Result.Data[0].Data[I] + A;
1233 Result.Data[1].Data[I] := Result.Data[1].Data[I] + B;
1234 end else
1235 begin
1236 Result.Data[0].Data[I] := Result.Data[0].Data[I] + B;
1237 Result.Data[1].Data[I] := Result.Data[1].Data[I] + A;
1238 end;
1239 end;
1240 end;
1241 end;
1242
1243 begin
1244 if IsEmpty then
1245 Exit(Empty);
1246
1247 if (Matrix.Data[0, 3] = 0) and
1248 (Matrix.Data[1, 3] = 0) and
1249 (Matrix.Data[2, 3] = 0) and
1250 (Matrix.Data[3, 3] = 1) then
1251 Result := Faster(Matrix)
1252 else
1253 Result := Slower(Matrix);
1254 end;
1255
1256 function TBox3D.Translate(
1257 const Translation: TVector3): TBox3D;
1258 begin
1259 if not IsEmpty then
1260 begin
1261 Result.Data[0] := Data[0] + Translation;
1262 Result.Data[1] := Data[1] + Translation;
1263 end else
1264 Result := Empty;
1265 end;
1266
1267 function TBox3D.AntiTranslate(
1268 const Translation: TVector3): TBox3D;
1269 begin
1270 if not IsEmpty then
1271 begin
1272 Result.Data[0] := Data[0] - Translation;
1273 Result.Data[1] := Data[1] - Translation;
1274 end else
1275 Result := Empty;
1276 end;
1277
1278 function TBox3D.ToString: string;
1279 begin
1280 if IsEmpty then
1281 Result := 'EMPTY'
1282 else
1283 Result := '(Min: ' + Data[0].ToString + ') - (Max: ' + Data[1].ToString + ')';
1284 end;
1285
1286 function TBox3D.ToRawString: string;
1287 begin
1288 if IsEmpty then
1289 Result := 'EMPTY'
1290 else
1291 Result := '(Min: ' + Data[0].ToRawString + ') - (Max: ' + Data[1].ToRawString + ')';
1292 end;
1293
1294 function TBox3D.ToNiceStr: string;
1295 begin
1296 Result := ToString;
1297 end;
1298
1299 function TBox3D.ToRawStr: string;
1300 begin
1301 Result := ToRawString;
1302 end;
1303
1304 procedure TBox3D.ClampVar(var point: TVector3);
1305 var
1306 I: Integer;
1307 begin
1308 for I := 0 to 2 do
1309 begin
1310 if Point.Data[I] < Data[0][I] then
1311 Point.Data[I] := Data[0][I]
1312 else
1313 if Point.Data[I] > Data[1][I] then
1314 Point.Data[I] := Data[1][I];
1315 end;
1316 end;
1317
1318 { Causes FPC errors:
1319 Error: Asm: Duplicate label CASTLEBOXES/home/michalis/bin/castle-engineTBOX3D_$__$$_CLAMPVAR$TGENERICVECTOR3
1320 See https://bugs.freepascal.org/view.php?id=32188
1321
1322 procedure TBox3D.ClampVar(var point: TVector3Double);
1323 var
1324 I: Integer;
1325 begin
1326 for I := 0 to 2 do
1327 begin
1328 if Point.Data[I] < Data[0].Data[I] then
1329 Point.Data[I] := Data[0].Data[I]
1330 else
1331 if Point.Data[I] > Data[1].Data[I] then
1332 Point.Data[I] := Data[1].Data[I];
1333 end;
1334 end;
1335 }
1336
1337 function TBox3D.TryRayClosestIntersection(
1338 out Intersection: TVector3;
1339 out IntersectionDistance: Single;
1340 const RayOrigin, RayDirection: TVector3): boolean;
1341 var
1342 IntrProposed: boolean absolute result;
1343
1344 procedure ProposeBoxIntr(const PlaneConstCoord: T3DAxis;
1345 const PlaneConstValue: Single);
1346 var
1347 NowIntersection: TVector3;
1348 NowIntersectionDistance: Single;
1349 c1, c2: T3DAxis;
1350 begin
1351 if TrySimplePlaneRayIntersection(NowIntersection, NowIntersectionDistance,
1352 PlaneConstCoord, PlaneConstValue, RayOrigin, RayDirection) then
1353 begin
1354 RestOf3DCoords(PlaneConstCoord, c1, c2);
1355 if Between(NowIntersection[c1], Data[0][c1], Data[1][c1]) and
1356 Between(NowIntersection[c2], Data[0][c2], Data[1][c2]) then
1357 begin
1358 if (not IntrProposed) or
1359 (NowIntersectionDistance < IntersectionDistance) then
1360 begin
1361 IntrProposed := true;
1362 Intersection := NowIntersection;
1363 IntersectionDistance := NowIntersectionDistance;
1364 end;
1365 end;
1366 end;
1367 end;
1368
1369 var
1370 I: integer;
1371 begin
1372 IntrProposed := false;
1373 for I := 0 to 2 do
1374 begin
1375 { wykorzystujemy ponizej fakt ze jezeli RayOrigin[i] < Data[0][i] to na pewno
1376 promien ktory przecinalby scianke Data[1][i] pudelka przecinalby najpierw
1377 tez inna scianke. Wiec jezeli RayOrigin[i] < Data[0][i] to nie musimy sprawdzac
1378 przeciecia z plaszczyzna Data[1][i]. }
1379 if RayOrigin[i] < Data[0][i] then
1380 ProposeBoxIntr(i, Data[0][i]) else
1381 if RayOrigin[i] > Data[1][i] then
1382 ProposeBoxIntr(i, Data[1][i]) else
1383 begin
1384 ProposeBoxIntr(i, Data[0][i]);
1385 ProposeBoxIntr(i, Data[1][i]);
1386 end;
1387 end;
1388 end;
1389
1390 function TBox3D.TryRayClosestIntersection(
1391 out Intersection: TVector3;
1392 const RayOrigin, RayDirection: TVector3): boolean;
1393 var
1394 IntersectionDistance: Single;
1395 begin
1396 Result := TryRayClosestIntersection(
1397 Intersection, IntersectionDistance, RayOrigin, RayDirection);
1398 end;
1399
1400 function TBox3D.TryRayClosestIntersection(
1401 out IntersectionDistance: Single;
1402 const RayOrigin, RayDirection: TVector3): boolean;
1403 var
1404 Intersection: TVector3;
1405 begin
1406 Result := TryRayClosestIntersection(
1407 Intersection, IntersectionDistance, RayOrigin, RayDirection);
1408 end;
1409
1410 function TBox3D.TryRayEntrance(
1411 out Entrance: TVector3; out EntranceDistance: Single;
1412 const RayOrigin, RayDirection: TVector3): boolean;
1413 begin
1414 if Contains(RayOrigin) then
1415 begin
1416 Entrance := RayOrigin;
1417 EntranceDistance := 0;
1418 result := true;
1419 end else
1420 result := TryRayClosestIntersection(Entrance, EntranceDistance, RayOrigin, RayDirection);
1421 end;
1422
1423 function TBox3D.TryRayEntrance(
1424 out Entrance: TVector3;
1425 const RayOrigin, RayDirection: TVector3): boolean;
1426 begin
1427 if Contains(RayOrigin) then
1428 begin
1429 Entrance := RayOrigin;
1430 result := true;
1431 end else
1432 result := TryRayClosestIntersection(Entrance, RayOrigin, RayDirection);
1433 end;
1434
1435 function TBox3D.IsSegmentCollision(
1436 const Segment1, Segment2: TVector3): boolean;
1437 begin
1438 Result := SegmentCollision(Segment1, Segment2);
1439 end;
1440
1441 function TBox3D.SegmentCollision(
1442 const Segment1, Segment2: TVector3): boolean;
1443
1444 function IsCollisionWithBoxPlane(const PlaneConstCoord: T3DAxis;
1445 const PlaneConstValue: Single): boolean;
1446 var
1447 NowIntersection: TVector3;
1448 c1, c2: T3DAxis;
1449 begin
1450 if TrySimplePlaneSegmentIntersection(NowIntersection,
1451 PlaneConstCoord, PlaneConstValue, Segment1, Segment2) then
1452 begin
1453 RestOf3DCoords(PlaneConstCoord, c1, c2);
1454 Result :=
1455 Between(NowIntersection[c1], Data[0][c1], Data[1][c1]) and
1456 Between(NowIntersection[c2], Data[0][c2], Data[1][c2]);
1457 end else
1458 Result := false;
1459 end;
1460
1461 var
1462 I: integer;
1463 begin
1464 for I := 0 to 2 do
1465 begin
1466 { wykorzystujemy ponizej fakt ze jezeli Segment1[i] < Data[0][i] to na pewno
1467 promien ktory przecinalby scianke Data[1][i] pudelka przecinalby najpierw
1468 tez inna scianke. Wiec jezeli Segment1[i] < Data[0][i] to nie musimy sprawdzac
1469 przeciecia z plaszczyzna Data[1][i]. }
1470 if Segment1[i] < Data[0][i] then
1471 begin
1472 if IsCollisionWithBoxPlane(i, Data[0][i]) then Exit(true);
1473 end else
1474 if Segment1[i] > Data[1][i] then
1475 begin
1476 if IsCollisionWithBoxPlane(i, Data[1][i]) then Exit(true);
1477 end else
1478 begin
1479 if IsCollisionWithBoxPlane(i, Data[0][i]) then Exit(true);
1480 if IsCollisionWithBoxPlane(i, Data[1][i]) then Exit(true);
1481 end;
1482 end;
1483
1484 Result := false;
1485 end;
1486
1487 function TBox3D.PlaneCollision(
1488 const Plane: TVector4): TPlaneCollision;
1489 { This generalizes the idea from IsCenteredBox3DPlaneCollision
1490 in castleboxes_generic_float.inc.
1491 It's also explained in
1492 Akenine-Moller, Haines "Real-Time Rendering" (2nd ed), 13.9 (page 586)
1493 }
1494 var
1495 I: Integer;
1496 VMin, VMax: TVector3;
1497 B: boolean;
1498 BoxBool: TBox3DBool absolute Data;
1499 begin
1500 if IsEmpty then
1501 Exit(pcNone);
1502
1503 for I := 0 to 2 do
1504 begin
1505 { Normal code:
1506 if Plane[I] >= 0 then
1507 begin
1508 VMin[I] := Data[0][I];
1509 VMax[I] := Data[1][I];
1510 end else
1511 begin
1512 VMin[I] := Data[1][I];
1513 VMax[I] := Data[0][I];
1514 end;
1515 }
1516
1517 { Code optimized to avoid "if", instead doing table lookup by BoxBool }
1518 B := Plane[I] >= 0;
1519 VMin.Data[I] := BoxBool[not B][I];
1520 VMax.Data[I] := BoxBool[B][I];
1521 end;
1522
1523 if Plane.X * VMin.X +
1524 Plane.Y * VMin.Y +
1525 Plane.Z * VMin.Z +
1526 Plane.W > 0 then
1527 Exit(pcOutside);
1528
1529 if Plane.X * VMax.X +
1530 Plane.Y * VMax.Y +
1531 Plane.Z * VMax.Z +
1532 Plane.W < 0 then
1533 Exit(pcInside);
1534
1535 Result := pcIntersecting;
1536 end;
1537
1538 function TBox3D.PlaneCollisionInside(
1539 const Plane: TVector4): boolean;
1540 { Based on Box3DPlaneCollision, except now we need only VMax point.
1541
1542 Actually, we don't even store VMax. Instead, we calculate to
1543 PlaneResult the equation
1544
1545 Plane[0] * VMax[0] +
1546 Plane[1] * VMax[1] +
1547 Plane[2] * VMax[2] +
1548 Plane[3]
1549 }
1550 var
1551 BoxBool: TBox3DBool absolute Data;
1552 begin
1553 if IsEmpty then
1554 Exit(false);
1555
1556 Result :=
1557 BoxBool[Plane.X >= 0].X * Plane.X +
1558 BoxBool[Plane.Y >= 0].Y * Plane.Y +
1559 BoxBool[Plane.Z >= 0].Z * Plane.Z +
1560 Plane.W < 0;
1561 end;
1562
1563 function TBox3D.PlaneCollisionOutside(
1564 const Plane: TVector4): boolean;
1565 var
1566 BoxBool: TBox3DBool absolute Data;
1567 begin
1568 if IsEmpty then
1569 Exit(false);
1570
1571 Result :=
1572 BoxBool[Plane.X < 0].X * Plane.X +
1573 BoxBool[Plane.Y < 0].Y * Plane.Y +
1574 BoxBool[Plane.Z < 0].Z * Plane.Z +
1575 Plane.W > 0;
1576 end;
1577
1578 function TBox3D.IsTriangleCollision(const Triangle: TTriangle3): boolean;
1579
1580 { Implementation based on
1581 [http://jgt.akpeters.com/papers/AkenineMoller01/tribox.html],
1582 by Tomas Akenine-Möller, described
1583 in his paper [http://jgt.akpeters.com/papers/AkenineMoller01/]
1584 "Fast 3D Triangle-Box Overlap Testing", downloadable from
1585 [http://www.cs.lth.se/home/Tomas_Akenine_Moller/pubs/tribox.pdf].
1586
1587 Use separating axis theorem to test overlap between triangle and box
1588 need to test for overlap in these directions:
1589 1) the (x,y,z)-directions
1590 2) normal of the triangle
1591 3) crossproduct(edge from tri, (x,y,z)-direction)
1592 this gives 3x3=9 more tests
1593 }
1594
1595 const
1596 { Special equality epsilon used by IsCenteredBox3DPlaneCollision.
1597 For implementation reasons, they always
1598 use Double precision (even when called with arguments with Single precision),
1599 and still have to use epsilon slightly larger than usual
1600 CastleVectors.DoubleEpsilon. }
1601 Epsilon: Double = 1e-5;
1602
1603 { It's better to make these calculations using Double precision. }
1604 {$define IsTriangleCollision_DoublePrecision}
1605
1606 type
1607 TVector3 = {$ifdef IsTriangleCollision_DoublePrecision}
1608 CastleVectors.TVector3Double {$else}
1609 CastleVectors.TVector3 {$endif};
1610 TVector4 = {$ifdef IsTriangleCollision_DoublePrecision}
1611 CastleVectors.TVector4Double {$else}
1612 CastleVectors.TVector4 {$endif};
1613 TScalar = {$ifdef IsTriangleCollision_DoublePrecision}
1614 Double {$else}
1615 Single {$endif};
1616 TTriangle3 = array [0..2] of TVector3;
1617
1618 var
1619 TriangleMoved: TTriangle3;
1620 BoxHalfSize: TVector3;
1621
1622 { ======================== X-tests ======================== }
1623 function AXISTEST_X01(const a, b, fa, fb: TScalar): boolean;
1624 var
1625 p0, p2, rad, min, max: TScalar;
1626 begin
1627 p0 := a * TriangleMoved[0].Y - b * TriangleMoved[0].Z;
1628 p2 := a * TriangleMoved[2].Y - b * TriangleMoved[2].Z;
1629 if p0<p2 then begin min := p0; max := p2; end else
1630 begin min := p2; max := p0; end;
1631 rad := fa * BoxHalfSize.Y + fb * BoxHalfSize.Z;
1632 Result := (min > rad + Epsilon) or (max < -rad - Epsilon);
1633 end;
1634
1635 function AXISTEST_X2(const a, b, fa, fb: TScalar): boolean;
1636 var
1637 p0, p1, rad, min, max: TScalar;
1638 begin
1639 p0 := a * TriangleMoved[0].Y - b * TriangleMoved[0].Z;
1640 p1 := a * TriangleMoved[1].Y - b * TriangleMoved[1].Z;
1641 if p0<p1 then begin min := p0; max := p1; end else
1642 begin min := p1; max := p0; end;
1643 rad := fa * BoxHalfSize.Y + fb * BoxHalfSize.Z;
1644 Result := (min > rad + Epsilon) or (max < -rad - Epsilon);
1645 end;
1646
1647 { ======================== Y-tests ======================== }
1648 function AXISTEST_Y02(const a, b, fa, fb: TScalar): boolean;
1649 var
1650 p0, p2, rad, min, max: TScalar;
1651 begin
1652 p0 := -a * TriangleMoved[0].X + b * TriangleMoved[0].Z;
1653 p2 := -a * TriangleMoved[2].X + b * TriangleMoved[2].Z;
1654 if p0<p2 then begin min := p0; max := p2; end else
1655 begin min := p2; max := p0; end;
1656 rad := fa * BoxHalfSize.X + fb * BoxHalfSize.Z;
1657 Result := (min > rad + Epsilon) or (max < -rad - Epsilon);
1658 end;
1659
1660 function AXISTEST_Y1(const a, b, fa, fb: TScalar): boolean;
1661 var
1662 p0, p1, rad, min, max: TScalar;
1663 begin
1664 p0 := -a * TriangleMoved[0].X + b * TriangleMoved[0].Z;
1665 p1 := -a * TriangleMoved[1].X + b * TriangleMoved[1].Z;
1666 if p0<p1 then begin min := p0; max := p1; end else
1667 begin min := p1; max := p0; end;
1668 rad := fa * BoxHalfSize.X + fb * BoxHalfSize.Z;
1669 Result := (min > rad + Epsilon) or (max < -rad - Epsilon);
1670 end;
1671
1672 { ======================== Z-tests ======================== }
1673 function AXISTEST_Z12(const a, b, fa, fb: TScalar): boolean;
1674 var
1675 p1, p2, rad, min, max: TScalar;
1676 begin
1677 p1 := a * TriangleMoved[1].X - b * TriangleMoved[1].Y;
1678 p2 := a * TriangleMoved[2].X - b * TriangleMoved[2].Y;
1679 if p2<p1 then begin min := p2; max := p1; end else
1680 begin min := p1; max := p2; end;
1681 rad := fa * BoxHalfSize.X + fb * BoxHalfSize.Y;
1682 Result := (min > rad + Epsilon) or (max < -rad - Epsilon);
1683 end;
1684
1685 function AXISTEST_Z0(const a, b, fa, fb: TScalar): boolean;
1686 var
1687 p0, p1, rad, min, max: TScalar;
1688 begin
1689 p0 := a * TriangleMoved[0].X - b * TriangleMoved[0].Y;
1690 p1 := a * TriangleMoved[1].X - b * TriangleMoved[1].Y;
1691 if p0<p1 then begin min := p0; max := p1; end else
1692 begin min := p1; max := p0; end;
1693 rad := fa * BoxHalfSize.X + fb * BoxHalfSize.Y;
1694 Result := (min > rad + Epsilon) or (max < -rad - Epsilon);
1695 end;
1696
1697 var
1698 BoxCenter: TVector3;
1699 I: Integer;
1700 TriangleEdges: TTriangle3;
1701 EdgeAbs: TVector3;
1702 TriMin, TriMax: TScalar;
1703 Plane: TVector4;
1704 PlaneDir: TVector3 absolute Plane;
1705 begin
1706 if IsEmpty then
1707 Exit(false);
1708
1709 { calculate BoxCenter and BoxHalfSize }
1710 for I := 0 to 2 do
1711 begin
1712 BoxCenter.Data[I] := (Data[0][I] + Data[1][I]) / 2;
1713 BoxHalfSize.Data[I] := (Data[1][I] - Data[0][I]) / 2;
1714 end;
1715
1716 { calculate TriangleMoved (Triangle shifted by -BoxCenter,
1717 so that we can treat the BoxHalfSize as centered around origin) }
1718 TriangleMoved[0] := {$ifdef IsTriangleCollision_DoublePrecision}Vector3Double{$endif}(Triangle.Data[0]) - BoxCenter;
1719 TriangleMoved[1] := {$ifdef IsTriangleCollision_DoublePrecision}Vector3Double{$endif}(Triangle.Data[1]) - BoxCenter;
1720 TriangleMoved[2] := {$ifdef IsTriangleCollision_DoublePrecision}Vector3Double{$endif}(Triangle.Data[2]) - BoxCenter;
1721
1722 { calculate TriangleMoved edges }
1723 TriangleEdges[0] := TriangleMoved[1] - TriangleMoved[0];
1724 TriangleEdges[1] := TriangleMoved[2] - TriangleMoved[1];
1725 TriangleEdges[2] := TriangleMoved[0] - TriangleMoved[2];
1726
1727 { tests 3) }
1728 EdgeAbs.X := Abs(TriangleEdges[0].X);
1729 EdgeAbs.Y := Abs(TriangleEdges[0].Y);
1730 EdgeAbs.Z := Abs(TriangleEdges[0].Z);
1731 if AXISTEST_X01(TriangleEdges[0].Z, TriangleEdges[0].Y, EdgeAbs.Z, EdgeAbs.Y) then Exit(false);
1732 if AXISTEST_Y02(TriangleEdges[0].Z, TriangleEdges[0].X, EdgeAbs.Z, EdgeAbs.X) then Exit(false);
1733 if AXISTEST_Z12(TriangleEdges[0].Y, TriangleEdges[0].X, EdgeAbs.Y, EdgeAbs.X) then Exit(false);
1734
1735 EdgeAbs.X := Abs(TriangleEdges[1].X);
1736 EdgeAbs.Y := Abs(TriangleEdges[1].Y);
1737 EdgeAbs.Z := Abs(TriangleEdges[1].Z);
1738 if AXISTEST_X01(TriangleEdges[1].Z, TriangleEdges[1].Y, EdgeAbs.Z, EdgeAbs.Y) then Exit(false);
1739 if AXISTEST_Y02(TriangleEdges[1].Z, TriangleEdges[1].X, EdgeAbs.Z, EdgeAbs.X) then Exit(false);
1740 if AXISTEST_Z0 (TriangleEdges[1].Y, TriangleEdges[1].X, EdgeAbs.Y, EdgeAbs.X) then Exit(false);
1741
1742 EdgeAbs.X := Abs(TriangleEdges[2].X);
1743 EdgeAbs.Y := Abs(TriangleEdges[2].Y);
1744 EdgeAbs.Z := Abs(TriangleEdges[2].Z);
1745 if AXISTEST_X2 (TriangleEdges[2].Z, TriangleEdges[2].Y, EdgeAbs.Z, EdgeAbs.Y) then Exit(false);
1746 if AXISTEST_Y1 (TriangleEdges[2].Z, TriangleEdges[2].X, EdgeAbs.Z, EdgeAbs.X) then Exit(false);
1747 if AXISTEST_Z12(TriangleEdges[2].Y, TriangleEdges[2].X, EdgeAbs.Y, EdgeAbs.X) then Exit(false);
1748
1749 { tests 1)
1750 first test overlap in the (x,y,z)-directions
1751 find TriMin, TriMax of the triangle each direction, and test for overlap in
1752 that direction -- this is equivalent to testing a minimal AABB around
1753 the triangle against the AABB }
1754
1755 { test in X-direction }
1756 MinMax(TriangleMoved[0].X, TriangleMoved[1].X, TriangleMoved[2].X, TriMin, TriMax);
1757 if (TriMin > boxhalfsize.X + Epsilon) or
1758 (TriMax < -boxhalfsize.X - Epsilon) then Exit(false);
1759
1760 { test in Y-direction }
1761 MinMax(TriangleMoved[0].Y, TriangleMoved[1].Y, TriangleMoved[2].Y, TriMin, TriMax);
1762 if (TriMin > boxhalfsize.Y + Epsilon) or
1763 (TriMax < -boxhalfsize.Y - Epsilon) then Exit(false);
1764
1765 { test in Z-direction }
1766 MinMax(TriangleMoved[0].Z, TriangleMoved[1].Z, TriangleMoved[2].Z, TriMin, TriMax);
1767 if (TriMin > boxhalfsize.Z + Epsilon) or
1768 (TriMax < -boxhalfsize.Z - Epsilon) then Exit(false);
1769
1770 { tests 2)
1771 test if the box intersects the plane of the triangle
1772 compute plane equation of triangle: normal*x+d=0 }
1773 PlaneDir := TVector3.CrossProduct(TriangleEdges[0], TriangleEdges[1]);
1774 Plane.W := -TVector3.DotProduct(PlaneDir, TriangleMoved[0]);
1775 if not {$ifdef IsTriangleCollision_DoublePrecision}
1776 IsCenteredBox3DPlaneCollisionDouble{$else}
1777 IsCenteredBox3DPlaneCollision{$endif}
1778 (BoxHalfSize, Plane) then
1779 Exit(false);
1780
1781 Result := true; { box and triangle overlaps }
1782 end;
1783
1784 procedure TBox3D.BoundingSphere(
1785 var SphereCenter: TVector3; var SphereRadiusSqr: Single);
1786 begin
1787 if IsEmpty then
1788 begin
1789 SphereRadiusSqr := 0;
1790 end else
1791 begin
1792 SphereCenter := Center;
1793 SphereRadiusSqr := PointsDistanceSqr(SphereCenter, Data[0]);
1794 end;
1795 end;
1796
1797 function TBox3D.Collision(const Box2: TBox3D): boolean;
1798 begin
1799 Result := Collides(Box2);
1800 end;
1801
1802 function TBox3D.Collides(const Box2: TBox3D): boolean;
1803 begin
1804 Result :=
1805 (not IsEmpty) and
1806 (not Box2.IsEmpty) and
1807 (not ((Data[1].X < Box2.Data[0].X) or (Box2.Data[1].X < Data[0].X))) and
1808 (not ((Data[1].Y < Box2.Data[0].Y) or (Box2.Data[1].Y < Data[0].Y))) and
1809 (not ((Data[1].Z < Box2.Data[0].Z) or (Box2.Data[1].Z < Data[0].Z)));
1810 end;
1811
1812 function TBox3D.Radius: Single;
1813 begin
1814 if IsEmpty then
1815 Result := 0
1816 else
1817 Result := Sqrt(MaxValue([
1818 Vector3(Data[0].X, Data[0].Y, Data[0].Z).LengthSqr,
1819 Vector3(Data[1].X, Data[0].Y, Data[0].Z).LengthSqr,
1820 Vector3(Data[1].X, Data[1].Y, Data[0].Z).LengthSqr,
1821 Vector3(Data[0].X, Data[1].Y, Data[0].Z).LengthSqr,
1822 Vector3(Data[0].X, Data[0].Y, Data[1].Z).LengthSqr,
1823 Vector3(Data[1].X, Data[0].Y, Data[1].Z).LengthSqr,
1824 Vector3(Data[1].X, Data[1].Y, Data[1].Z).LengthSqr,
1825 Vector3(Data[0].X, Data[1].Y, Data[1].Z).LengthSqr
1826 ]));
1827 end;
1828
1829 function TBox3D.Radius2D(const IgnoreIndex: T3DAxis): Single;
1830 begin
1831 if IsEmpty then
1832 Result := 0 else
1833 begin
1834 case IgnoreIndex of
1835 0: Result := MaxValue([
1836 Vector2(Data[0].Y, Data[0].Z).LengthSqr,
1837 Vector2(Data[1].Y, Data[0].Z).LengthSqr,
1838 Vector2(Data[1].Y, Data[1].Z).LengthSqr,
1839 Vector2(Data[0].Y, Data[1].Z).LengthSqr
1840 ]);
1841 1: Result := MaxValue([
1842 Vector2(Data[0].Z, Data[0].X).LengthSqr,
1843 Vector2(Data[1].Z, Data[0].X).LengthSqr,
1844 Vector2(Data[1].Z, Data[1].X).LengthSqr,
1845 Vector2(Data[0].Z, Data[1].X).LengthSqr
1846 ]);
1847 2: Result := MaxValue([
1848 Vector2(Data[0].X, Data[0].Y).LengthSqr,
1849 Vector2(Data[1].X, Data[0].Y).LengthSqr,
1850 Vector2(Data[1].X, Data[1].Y).LengthSqr,
1851 Vector2(Data[0].X, Data[1].Y).LengthSqr
1852 ]);
1853 {$ifndef COMPILER_CASE_ANALYSIS}
1854 else
1855 begin
1856 RaiseRadius2DInvalidIgnoreIndex;
1857 Result := 0; // just silence Delphi warning
1858 end;
1859 {$endif}
1860 end;
1861
1862 Result := Sqrt(Result);
1863 end;
1864 end;
1865
1866 function TBox3D.SphereSimpleCollision(
1867 const SphereCenter: TVector3; const SphereRadius: Single): boolean;
1868 begin
1869 Result := (not IsEmpty) and
1870 (SphereCenter.X >= Data[0].X - SphereRadius) and
1871 (SphereCenter.X <= Data[1].X + SphereRadius) and
1872 (SphereCenter.Y >= Data[0].Y - SphereRadius) and
1873 (SphereCenter.Y <= Data[1].Y + SphereRadius) and
1874 (SphereCenter.Z >= Data[0].Z - SphereRadius) and
1875 (SphereCenter.Z <= Data[1].Z + SphereRadius);
1876 end;
1877
1878 function TBox3D.SphereCollision(
1879 const SphereCenter: TVector3; const SphereRadius: Single): boolean;
1880 { This great and simple algorithm was invented by Arvo, I read about
1881 it in "Real-Time Rendering" by Moller and Haines.
1882 The idea is beatifully simple: we can easily find point on the Box
1883 that is closest to SphereCenter: on each of X, Y, Z axis,
1884 1. SphereCenter[I] is within Box, so distance on this axis is 0
1885 2. SphereCenter[I] is not within Box, so the closest point is taken
1886 from appropriate box corner
1887 Then just compare distance between these points and radius.
1888
1889 Implementation below is low-optimized: we actually calculate
1890 distance, d, as we go (we don't keep explicitly our "closest point",
1891 although we think about calculating it). And loop over three planes
1892 is unfolded to be sure. }
1893 var
1894 D: Single;
1895 begin
1896 if IsEmpty then Exit(false);
1897
1898 D := 0;
1899
1900 { Uses:
1901 4 up to 7 comparisons,
1902 6 additions,
1903 4 multiplications.
1904
1905 Ok, that's damn fast, but still a little slower than
1906 TBox3D.SphereSimpleCollision (that has 1 up to 6 comparisons and additions). }
1907
1908 if SphereCenter.X < Data[0].X then D := D + (Sqr(SphereCenter.X - Data[0].X)) else
1909 if SphereCenter.X > Data[1].X then D := D + (Sqr(SphereCenter.X - Data[1].X));
1910
1911 if SphereCenter.Y < Data[0].Y then D := D + (Sqr(SphereCenter.Y - Data[0].Y)) else
1912 if SphereCenter.Y > Data[1].Y then D := D + (Sqr(SphereCenter.Y - Data[1].Y));
1913
1914 if SphereCenter.Z < Data[0].Z then D := D + (Sqr(SphereCenter.Z - Data[0].Z)) else
1915 if SphereCenter.Z > Data[1].Z then D := D + (Sqr(SphereCenter.Z - Data[1].Z));
1916
1917 Result := D <= Sqr(SphereRadius);
1918 end;
1919
1920 function TBox3D.SphereCollision2D(
1921 const SphereCenter: TVector2; const SphereRadius: Single): boolean;
1922 var
1923 D: Single;
1924 begin
1925 if IsEmpty then Exit(false);
1926
1927 D := 0;
1928
1929 if SphereCenter.X < Data[0].X then D := D + (Sqr(SphereCenter.X - Data[0].X)) else
1930 if SphereCenter.X > Data[1].X then D := D + (Sqr(SphereCenter.X - Data[1].X));
1931
1932 if SphereCenter.Y < Data[0].Y then D := D + (Sqr(SphereCenter.Y - Data[0].Y)) else
1933 if SphereCenter.Y > Data[1].Y then D := D + (Sqr(SphereCenter.Y - Data[1].Y));
1934
1935 Result := D <= Sqr(SphereRadius);
1936 end;
1937
1938 function TBox3D.MaximumPlane(
1939 const Direction: TVector3): TVector4;
1940 var
1941 BoxBool: TBox3DBool absolute Data;
1942 ResultDir: TVector3 absolute Result;
1943 begin
1944 CheckNonEmpty;
1945
1946 { first 3 plane components are just copied from Direction }
1947 ResultDir := Direction;
1948
1949 (*
1950 { calculate box corner that intersects resulting plane:
1951 just choose appropriate coords using Direction. }
1952 P[0] := BoxBool[Direction[0] >= 0].X;
1953 P[1] := BoxBool[Direction[1] >= 0].Y;
1954 P[2] := BoxBool[Direction[2] >= 0].Z;
1955
1956 { calculate 4th plane component.
1957 Plane must intersect P, so
1958 P[0] * Result[0] + .... + Result[3] = 0
1959 }
1960 Result[3] := - (P[0] * Result[0] +
1961 P[1] * Result[1] +
1962 P[2] * Result[2]);
1963 *)
1964
1965 { optimized version, just do this in one go: }
1966 Result.W := - (
1967 BoxBool[Direction.X >= 0].X * Result.X +
1968 BoxBool[Direction.Y >= 0].Y * Result.Y +
1969 BoxBool[Direction.Z >= 0].Z * Result.Z);
1970 end;
1971
1972 function TBox3D.MinimumPlane(const Direction: TVector3): TVector4;
1973 var
1974 BoxBool: TBox3DBool absolute Data;
1975 ResultDir: TVector3 absolute Result;
1976 begin
1977 CheckNonEmpty;
1978
1979 { first 3 plane components are just copied from Direction }
1980 ResultDir := Direction;
1981
1982 { optimized version, just do this in one go: }
1983 Result.W := - (
1984 BoxBool[Direction.X < 0].X * Result.X +
1985 BoxBool[Direction.Y < 0].Y * Result.Y +
1986 BoxBool[Direction.Z < 0].Z * Result.Z);
1987 end;
1988
1989 function TBox3D.MaximumCorner(const Direction: TVector3): TVector3;
1990 var
1991 BoxBool: TBox3DBool absolute Data;
1992 begin
1993 CheckNonEmpty;
1994 Result.X := BoxBool[Direction.X >= 0].X;
1995 Result.Y := BoxBool[Direction.Y >= 0].Y;
1996 Result.Z := BoxBool[Direction.Z >= 0].Z;
1997 end;
1998
1999 function TBox3D.MinimumCorner(const Direction: TVector3): TVector3;
2000 var
2001 BoxBool: TBox3DBool absolute Data;
2002 begin
2003 CheckNonEmpty;
2004 Result.X := BoxBool[Direction.X < 0].X;
2005 Result.Y := BoxBool[Direction.Y < 0].Y;
2006 Result.Z := BoxBool[Direction.Z < 0].Z;
2007 end;
2008
2009 procedure TBox3D.PointDistances(const P: TVector3;
2010 out MinDistance, MaxDistance: Single);
2011 var
2012 Dist0, Dist1: Single;
2013 I: Integer;
2014 begin
2015 CheckNonEmpty;
2016
2017 MinDistance := 0;
2018 MaxDistance := 0;
2019
2020 { For each coordinate (0, 1, 2), find which side of the box is closest.
2021 Effectively, we find the closest of the 8 box corners.
2022 The opposite corner is the farthest.
2023 We want to calculate distance to this point, so we do it by the way. }
2024 for I := 0 to 2 do
2025 begin
2026 Dist0 := Sqr(P[I] - Data[0][I]);
2027 Dist1 := Sqr(P[I] - Data[1][I]);
2028 if Dist0 < Dist1 then
2029 begin
2030 MinDistance := MinDistance + Dist0;
2031 MaxDistance := MaxDistance + Dist1;
2032 end else
2033 begin
2034 MinDistance := MinDistance + Dist1;
2035 MaxDistance := MaxDistance + Dist0;
2036 end;
2037 end;
2038
2039 if Contains(P) then
2040 MinDistance := 0;
2041
2042 MinDistance := Sqrt(MinDistance);
2043 MaxDistance := Sqrt(MaxDistance);
2044
2045 { Because of floating point inaccuracy, MinDistance may be larger
2046 by epsilon than MaxDistance? Fix it to be sure. }
2047 { For now: just assert it: }
2048 Assert(MinDistance <= MaxDistance);
2049 end;
2050
2051 procedure TBox3D.DirectionDistances(
2052 const Point, Dir: TVector3;
2053 out MinDistance, MaxDistance: Single);
2054 var
2055 B: TBox3DBool absolute Data;
2056 XMin, YMin, ZMin: boolean;
2057 MinPoint, MaxPoint: TVector3;
2058 Coord: Integer;
2059 begin
2060 CheckNonEmpty;
2061
2062 XMin := Dir.X < 0;
2063 YMin := Dir.Y < 0;
2064 ZMin := Dir.Z < 0;
2065
2066 MinPoint := PointOnLineClosestToPoint(Point, Dir,
2067 Vector3(B[XMin].X, B[YMin].Y, B[ZMin].Z));
2068 MaxPoint := PointOnLineClosestToPoint(Point, Dir,
2069 Vector3(B[not XMin].X, B[not YMin].Y, B[not ZMin].Z));
2070
2071 MinDistance := PointsDistance(Point, MinPoint);
2072 MaxDistance := PointsDistance(Point, MaxPoint);
2073
2074 { choose one of the 3 coordinates where Dir is largest, for best
2075 numerical stability. We need to compare now and see which
2076 distances should be negated. }
2077 Coord := MaxAbsVectorCoord(Dir);
2078
2079 if Dir[Coord] > 0 then
2080 begin
2081 { So the distances to points that are *larger* on Coord are positive.
2082 Others should be negative. }
2083 if MinPoint[Coord] < Point[Coord] then
2084 MinDistance := -MinDistance;
2085 if MaxPoint[Coord] < Point[Coord] then
2086 MaxDistance := -MaxDistance;
2087 end else
2088 begin
2089 if MinPoint[Coord] > Point[Coord] then
2090 MinDistance := -MinDistance;
2091 if MaxPoint[Coord] > Point[Coord] then
2092 MaxDistance := -MaxDistance;
2093 end;
2094
2095 { Because of floating point inaccuracy, MinDistance may be larger
2096 by epsilon than MaxDistance? Fix it to be sure. }
2097 { For now: just assert it: }
2098 Assert(MinDistance <= MaxDistance);
2099 end;
2100
2101 (* MaxDistanceAlongDirection not used, so not defined for now.
2102 function TBox3D.MaxDistanceAlongDirection(const Point, Dir: TVector3): Single;
2103 var
2104 B: TBox3DBool absolute Data;
2105 XMin, YMin, ZMin: boolean;
2106 MaxPoint: TVector3;
2107 Coord: Integer;
2108 begin
2109 CheckNonEmpty;
2110
2111 XMin := Dir.X < 0;
2112 YMin := Dir.Y < 0;
2113 ZMin := Dir.Z < 0;
2114
2115 MaxPoint := PointOnLineClosestToPoint(Point, Dir,
2116 Vector3(B[not XMin].X, B[not YMin].Y, B[not ZMin].Z));
2117
2118 Result := PointsDistance(Point, MaxPoint);
2119
2120 { choose one of the 3 coordinates where Dir is largest, for best
2121 numerical stability. We need to compare now and see which
2122 distances should be negated. }
2123 Coord := MaxAbsVectorCoord(Dir);
2124
2125 if Dir[Coord] > 0 then
2126 begin
2127 { So the distances to points that are *larger* on Coord are positive.
2128 Others should be negative. }
2129 if MaxPoint[Coord] < Point[Coord] then
2130 Result := -Result;
2131 end else
2132 begin
2133 if MaxPoint[Coord] > Point[Coord] then
2134 Result := -Result;
2135 end;
2136 end;
2137 *)
2138
2139 function TBox3D.PointDistance(const Point: TVector3): Single;
2140 begin
2141 Result := Sqrt(PointDistanceSqr(Point));
2142 end;
2143
2144 function TBox3D.PointDistanceSqr(const Point: TVector3): Single;
2145 var
2146 I: Integer;
2147 begin
2148 CheckNonEmpty;
2149
2150 { There are 4 cases:
2151 0. point is in no box range - calculate distance to closest corner
2152 1. point is 1 box range - calculate distance to closest edge
2153 2. point is 2 box ranges - calculate distance to closest side
2154 3. point is 3 box ranges - so point is inside, distance = 0
2155
2156 First naive implementation was detecting these cases by calculating
2157 InsideRangeCount, InsideRange and such.
2158 But actually you can calculate all cases at once. }
2159
2160 Result := 0;
2161 for I := 0 to 2 do
2162 begin
2163 if Point[I] < Data[0][I] then
2164 Result := Result + (Sqr(Point[I] - Data[0][I])) else
2165 if Point[I] > Data[1][I] then
2166 Result := Result + (Sqr(Point[I] - Data[1][I]));
2167 end;
2168 end;
2169
2170 (*
2171 function TBox3D.PointMaxDistance(const Point: TVector3;
2172 const EmptyBoxDistance: Single): Single;
2173 var
2174 B: TBox3DBool absolute Data;
2175 begin
2176 if IsEmpty then
2177 Result := EmptyBoxDistance
2178 else
2179 Result := Sqrt(
2180 Sqr(Point.X - B[Point.X < (Data[0].X + Data[1].X) / 2].X) +
2181 Sqr(Point.Y - B[Point.Y < (Data[0].Y + Data[1].Y) / 2].Y) +
2182 Sqr(Point.Z - B[Point.Z < (Data[0].Z + Data[1].Z) / 2].Z)
2183 );
2184 end;
2185
2186 function TBox3D.PointMaxDistanceSqr(const Point: TVector3;
2187 const EmptyBoxDistance: Single): Single;
2188 var
2189 B: TBox3DBool absolute Data;
2190 begin
2191 if IsEmpty then
2192 Result := EmptyBoxDistance
2193 else
2194 Result :=
2195 Sqr(Point.X - B[Point.X < (Data[0].X + Data[1].X) / 2].X) +
2196 Sqr(Point.Y - B[Point.Y < (Data[0].Y + Data[1].Y) / 2].Y) +
2197 Sqr(Point.Z - B[Point.Z < (Data[0].Z + Data[1].Z) / 2].Z)
2198 ;
2199 end;
2200 *)
2201
2202 function TBox3D.Equal(const Box2: TBox3D): boolean;
2203 begin
2204 if IsEmpty then
2205 Result := Box2.IsEmpty else
2206 Result := (not Box2.IsEmpty) and
2207 TVector3.Equals(Data[0], Box2.Data[0]) and
2208 TVector3.Equals(Data[1], Box2.Data[1]);
2209 end;
2210
2211 function TBox3D.Equal(const Box2: TBox3D; const Epsilon: Single): boolean;
2212 begin
2213 if IsEmpty then
2214 Result := Box2.IsEmpty else
2215 Result := (not Box2.IsEmpty) and
2216 TVector3.Equals(Data[0], Box2.Data[0], Epsilon) and
2217 TVector3.Equals(Data[1], Box2.Data[1], Epsilon);
2218 end;
2219
2220 function TBox3D.Diagonal: Single;
2221 begin
2222 if IsEmpty then
2223 Result := 0 else
2224 Result := Sqrt(Sqr(Data[1].X - Data[0].X) +
2225 Sqr(Data[1].Y - Data[0].Y) +
2226 Sqr(Data[1].Z - Data[0].Z));
2227 end;
2228
2229 function TBox3D.RectangleXY: TFloatRectangle;
2230 begin
2231 if IsEmpty then
2232 Exit(TFloatRectangle.Empty) else
2233 begin
2234 Result.Left := Data[0].X;
2235 Result.Bottom := Data[0].Y;
2236 Result.Width := Data[1].X - Data[0].X;
2237 Result.Height := Data[1].Y - Data[0].Y;
2238 end;
2239 end;
2240
2241 function TBox3D.RectangleXZ: TFloatRectangle;
2242 begin
2243 if IsEmpty then
2244 Exit(TFloatRectangle.Empty) else
2245 begin
2246 Result.Left := Data[0].X;
2247 Result.Bottom := Data[0].Z;
2248 Result.Width := Data[1].X - Data[0].X;
2249 Result.Height := Data[1].Z - Data[0].Z;
2250 end;
2251 end;
2252
2253 function TBox3D.OrthoProject(const Pos, Dir, Side, Up: TVector3): TFloatRectangle;
2254
2255 function ProjectPoint(const P: TVector3): TVector2;
2256 var
2257 PDiff: TVector3;
2258 begin
2259 PDiff := P - Pos;
2260 Result.Data[0] := TVector3.DotProduct(PDiff, Side);
2261 Result.Data[1] := TVector3.DotProduct(PDiff, Up);
2262 end;
2263
2264 var
2265 C: TBoxCorners;
2266 I: Integer;
2267 begin
2268 Corners(C);
2269 Result := FloatRectangle(ProjectPoint(C[0]), 0, 0);
2270 for I := 1 to 7 do
2271 Result := Result.Include(ProjectPoint(C[I]));
2272 end;
2273
2274 class function TBox3D.CompareBackToFront2D(
2275 const A, B: TBox3D): Integer;
2276 begin
2277 { Note that we ignore camera position/direction for 2D comparison.
2278 We merely look at Z coordinates.
2279 This way looking at 2D Spine scene from the other side is also Ok.
2280
2281 For speed, we don't look at bounding box Middle, only at it's min point.
2282 The assumption here is that shape is 2D, so
2283 BoundingBox.Data[0].Z ~=
2284 BoundingBox.Data[1].Z ~=
2285 BoundingBox.Center.Z .
2286 }
2287
2288 if (not A.IsEmpty) and
2289 ( B.IsEmpty or
2290 ( A.Data[0].Z < B.Data[0].Z )) then
2291 Result := -1 else
2292 if (not B.IsEmpty) and
2293 ( A.IsEmpty or
2294 ( B.Data[0].Z < A.Data[0].Z )) then
2295 Result := 1 else
2296 Result := 0;
2297 end;
2298
2299 class operator TBox3D.{$ifdef FPC}+{$else}Add{$endif} (const Box1, Box2: TBox3D): TBox3D;
2300 begin
2301 if Box1.IsEmpty then
2302 Result := Box2 else
2303 if Box2.IsEmpty then
2304 Result := Box1 else
2305 begin
2306 Result.Data[0].X := Math.Min(Box1.Data[0].X, Box2.Data[0].X);
2307 Result.Data[1].X := Math.Max(Box1.Data[1].X, Box2.Data[1].X);
2308 Result.Data[0].Y := Math.Min(Box1.Data[0].Y, Box2.Data[0].Y);
2309 Result.Data[1].Y := Math.Max(Box1.Data[1].Y, Box2.Data[1].Y);
2310 Result.Data[0].Z := Math.Min(Box1.Data[0].Z, Box2.Data[0].Z);
2311 Result.Data[1].Z := Math.Max(Box1.Data[1].Z, Box2.Data[1].Z);
2312 end;
2313 end;
2314
2315 class operator TBox3D.{$ifdef FPC}+{$else}Add{$endif} (const B: TBox3D; const V: TVector3): TBox3D;
2316 begin
2317 Result := B.Translate(V);
2318 end;
2319
2320 class operator TBox3D.{$ifdef FPC}+{$else}Add{$endif} (const V: TVector3; const B: TBox3D): TBox3D;
2321 begin
2322 Result := B.Translate(V);
2323 end;
2324
2325 class function TBox3D.FromCenterSize(const ACenter, ASize: TVector3): TBox3D;
2326 begin
2327 Result := Box3DAroundPoint(ACenter, ASize);
2328 end;
2329
2330 procedure TBox3D.ToCenterSize(out ACenter, ASize: TVector3);
2331 begin
2332 if IsEmpty then
2333 begin
2334 ACenter := TVector3.Zero;
2335 ASize := Vector3(-1, -1, -1);
2336 end else
2337 begin
2338 ACenter := Center;
2339 ASize := Size;
2340 end;
2341 end;
2342
2343 { Routines ------------------------------------------------------------------- }
2344
2345 function IsCenteredBox3DPlaneCollisionDouble(
2346 const BoxHalfSize: TVector3Double;
2347 const Plane: TVector4Double): boolean;
2348
2349 { Implementation of this is based on
2350 [http://jgt.akpeters.com/papers/AkenineMoller01/tribox.html]
2351 planeBoxOverlap routine, by Tomas Akenine-Moller,
2352 mentioned in his paper [http://jgt.akpeters.com/papers/AkenineMoller01/]
2353 about "Fast 3D Triangle-Box Overlap Testing", downloadable from
2354 [http://www.cs.lth.se/home/Tomas_Akenine_Moller/pubs/tribox.pdf].
2355
2356 The idea: we need to test plane equation with only two points
2357 (instead of eight points, as in naive version). Think about the plane
2358 normal vector; imagine 8 box points projected on this vector; now
2359 we can find 2 box points, one that has minimal value when projected
2360 on normal vector, and one that has maximum value. Now you need to test
2361 is the plane between these two points. }
2362
2363 { Tests (see TTestCastleBoxes.TestIsBox3DTriangleCollisionEpsilonsSingle)
2364 show that this calculation should really be done on at least Double precision.
2365 The values for these tests were taken from debugging behavior on
2366 castle.wrl test VRML model, so yes, these errors produce real errors
2367 (they make some valid triangles not appear at all in the octree, so collision detection
2368 and picking fail on these areas).
2369 Otherwise floating point errors will force you to define really large Epsilon:
2370 when trying to set this experimentally, I had to set Epsilon = 1e-3 (even
2371 Epsilon = 1e-4 was still too small epsilon !).
2372
2373 With Double, I can use Epsilon below. OK, that's stil a large epsilon...
2374 You can test on VRML models like malfunction/trunk/vrmls/wawoz.wrl:
2375 castle-model-viewer (when compiled with -dDEBUG) with fail loading
2376 (Assert(AddedSomewhere) will trigger) with too small epsilon. }
2377
2378 const
2379 { Special equality epsilon used by IsCenteredBox3DPlaneCollision.
2380 For implementation reasons, it always uses Double precision,
2381 and it still has to use epsilon slightly larger than usual
2382 CastleVectors.DoubleEpsilon. }
2383 Epsilon: Double = 1e-5;
2384 var
2385 I: Integer;
2386 VMin, VMax: TVector3Double;
2387 begin
2388 for I := 0 to 2 do
2389 if Plane[I] > 0 then
2390 begin
2391 VMin.Data[I] := -BoxHalfSize[I];
2392 VMax.Data[I] := BoxHalfSize[I];
2393 end else
2394 begin
2395 VMin.Data[I] := BoxHalfSize[I];
2396 VMax.Data[I] := -BoxHalfSize[I];
2397 end;
2398
2399 { If VMin is above the plane (plane equation is > 0), then VMax
2400 is also above, no need to test anything else. }
2401 if Plane.X * VMin.X +
2402 Plane.Y * VMin.Y +
2403 Plane.Z * VMin.Z +
2404 Plane.W > Epsilon then
2405 Exit(false);
2406
2407 { So VMin is <= plane. So if VMax is >= 0, then there's a collision. }
2408 Result := Plane.X * VMax.X +
2409 Plane.Y * VMax.Y +
2410 Plane.Z * VMax.Z +
2411 Plane.W >= -Epsilon;
2412 end;
2413
2414 function IsCenteredBox3DPlaneCollision(
2415 const BoxHalfSize: TVector3;
2416 const Plane: TVector4): boolean;
2417 begin
2418 // redirect to Double-precision version
2419 Result := IsCenteredBox3DPlaneCollisionDouble(
2420 Vector3Double(BoxHalfSize),
2421 Vector4Double(Plane));
2422 end;
2423
2424 function Box3D(const p0, p1: TVector3): TBox3D;
2425 begin
2426 result.Data[0] := p0;
2427 result.Data[1] := p1;
2428 end;
2429
2430 function Box3DAroundPoint(const Pt: TVector3; Size: Single): TBox3D;
2431 begin
2432 if Size < 0 then
2433 Exit(TBox3D.Empty);
2434
2435 Size := Size / 2;
2436 Result.Data[0].X := Pt.X - Size;
2437 Result.Data[0].Y := Pt.Y - Size;
2438 Result.Data[0].Z := Pt.Z - Size;
2439 Result.Data[1].X := Pt.X + Size;
2440 Result.Data[1].Y := Pt.Y + Size;
2441 Result.Data[1].Z := Pt.Z + Size;
2442 end;
2443
2444 function Box3DAroundPoint(const Pt: TVector3; Size: TVector3): TBox3D;
2445 begin
2446 if (Size.X < 0) or
2447 (Size.Y < 0) or
2448 (Size.Z < 0) then
2449 Exit(TBox3D.Empty);
2450
2451 Size := Size / 2;
2452 Result.Data[0].X := Pt.X - Size.X;
2453 Result.Data[0].Y := Pt.Y - Size.Y;
2454 Result.Data[0].Z := Pt.Z - Size.Z;
2455 Result.Data[1].X := Pt.X + Size.X;
2456 Result.Data[1].Y := Pt.Y + Size.Y;
2457 Result.Data[1].Z := Pt.Z + Size.Z;
2458 end;
2459
2460 function CalculateBoundingBox(
2461 GetVertex: TGetVertexFromIndexFunc;
2462 VertsCount: integer): TBox3D;
2463 var
2464 I: Integer;
2465 V: TVector3;
2466 begin
2467 if VertsCount = 0 then
2468 Result := TBox3D.Empty else
2469 begin
2470 Result.Data[0] := GetVertex(0);
2471 Result.Data[1] := Result.Data[0];
2472 for I := 1 to VertsCount - 1 do
2473 begin
2474 V := GetVertex(I);
2475 MinVar(Result.Data[0].X, V.X);
2476 MinVar(Result.Data[0].Y, V.Y);
2477 MinVar(Result.Data[0].Z, V.Z);
2478
2479 MaxVar(Result.Data[1].X, V.X);
2480 MaxVar(Result.Data[1].Y, V.Y);
2481 MaxVar(Result.Data[1].Z, V.Z);
2482 end;
2483 end;
2484 end;
2485
2486 type
2487 { Internal helper for CalculateBoundingBox }
2488 TBBox_Calculator = class
2489 Verts: PVector3;
2490 VertsStride: Cardinal; { tutaj VertsStride juz nie moze byc = 0 }
2491 PMatrix: PMatrix4;
2492 function GetVertexNotTransform(index: integer): TVector3;
2493 function GetVertexTransform(index: integer): TVector3;
2494 end;
2495
2496 function TBBox_Calculator.GetVertexNotTransform(index: integer): TVector3;
2497 begin
2498 result := PVector3(PointerAdd(Verts, VertsStride*Cardinal(index)))^;
2499 end;
2500
2501 function TBBox_Calculator.GetVertexTransform(index: integer): TVector3;
2502 begin
2503 result := PMatrix^.MultPoint(PVector3(PointerAdd(Verts, VertsStride*Cardinal(index)))^);
2504 end;
2505
2506 function CalculateBoundingBox(
2507 Verts: PVector3; VertsCount: Cardinal; VertsStride: Cardinal): TBox3D;
2508 var
2509 Calculator: TBBox_Calculator;
2510 begin
2511 if VertsStride = 0 then VertsStride := SizeOf(TVector3);
2512 Calculator := TBBox_Calculator.Create;
2513 try
2514 Calculator.VertsStride := VertsStride;
2515 Calculator.Verts := Verts;
2516 result := CalculateBoundingBox(
2517 {$ifdef FPC} @ {$endif} Calculator.GetVertexNotTransform, VertsCount);
2518 finally Calculator.Free end;
2519 end;
2520
2521 function CalculateBoundingBox(
2522 Verts: PVector3; VertsCount: Cardinal; VertsStride: Cardinal;
2523 const Transform: TMatrix4): TBox3D;
2524 var
2525 Calculator: TBBox_Calculator;
2526 begin
2527 if VertsStride = 0 then VertsStride := SizeOf(TVector3);
2528 Calculator := TBBox_Calculator.Create;
2529 try
2530 Calculator.VertsStride := VertsStride;
2531 Calculator.Verts := Verts;
2532 Calculator.PMatrix := @Transform;
2533 result := CalculateBoundingBox(
2534 {$ifdef FPC} @ {$endif} Calculator.GetVertexTransform, VertsCount);
2535 finally Calculator.Free end;
2536 end;
2537
2538 function CalculateBoundingBox(Verts: TVector3List): TBox3D;
2539 begin
2540 Result := CalculateBoundingBox(PVector3(Verts.L), Verts.Count, 0);
2541 end;
2542
2543 function CalculateBoundingBox(Verts: TVector3List;
2544 const Transform: TMatrix4): TBox3D;
2545 begin
2546 Result := CalculateBoundingBox(PVector3(Verts.L), Verts.Count, 0,
2547 Transform);
2548 end;
2549
2550 function CalculateBoundingBoxFromIndices(
2551 const GetVertIndex: TGetIndexFromIndexNumFunc;
2552 const VertsIndicesCount: integer;
2553 const GetVertex: TGetVertexFromIndexFunc): TBox3D;
2554 var
2555 { pozycja pierwszego nieujemnego indexu.
2556 Zwracamy TBox3D.Empty wtw. gdy firstIndex nie istnieje }
2557 FirstIndexNum: integer;
2558
2559 IndexNum, Index: integer;
2560 ThisVertex: TVector3;
2561 begin
2562 {seek for firstIndex}
2563 firstIndexNum := 0;
2564 while (firstIndexNum < VertsIndicesCount) and (GetVertIndex(firstIndexNum) < 0) do
2565 Inc(firstIndexNum);
2566
2567 if firstIndexNum = VertsIndicesCount then {firstIndex not found ?}
2568 begin
2569 result := TBox3D.Empty;
2570 exit;
2571 end;
2572
2573 { Note that I do only one pass, getting all vertexes.
2574
2575 This is important, because GetVertex may be quite expensive
2576 operation (in case of e.g. TVertTransform_Calculator.GetTransformed,
2577 this is Matrix.MultPoint for every vertex). At the beginning
2578 I implemented this by caling 6 time find_extremum function,
2579 and each call to find_extremum was iterating over every vertex.
2580 This was obviously wrong, because this caused calling GetVertex
2581 6 times more often than necessary. In some cases (like preparing
2582 animations in "The Castle") this can cause really significant
2583 slowdown. }
2584
2585 ThisVertex := GetVertex(GetVertIndex(firstIndexNum));
2586 Result.Data[0] := ThisVertex;
2587 Result.Data[1] := ThisVertex;
2588 for IndexNum := FirstIndexNum+1 to VertsIndicesCount - 1 do
2589 begin
2590 Index := GetVertIndex(IndexNum);
2591 if Index >= 0 then
2592 begin
2593 ThisVertex := GetVertex(Index);
2594 if ThisVertex.X < Result.Data[0].X then Result.Data[0].X := ThisVertex.X;
2595 if ThisVertex.Y < Result.Data[0].Y then Result.Data[0].Y := ThisVertex.Y;
2596 if ThisVertex.Z < Result.Data[0].Z then Result.Data[0].Z := ThisVertex.Z;
2597 if ThisVertex.X > Result.Data[1].X then Result.Data[1].X := ThisVertex.X;
2598 if ThisVertex.Y > Result.Data[1].Y then Result.Data[1].Y := ThisVertex.Y;
2599 if ThisVertex.Z > Result.Data[1].Z then Result.Data[1].Z := ThisVertex.Z;
2600 end;
2601 end;
2602 end;
2603
2604 type
2605 TVertTransform_Calculator = class
2606 PTransform: PMatrix4;
2607 GetNotTransformed: TGetVertexFromIndexFunc;
2608 function GetTransformed(index: integer): TVector3;
2609 end;
2610 function TVertTransform_Calculator.GetTransformed(index: integer): TVector3;
2611 begin
2612 result := PTransform^.MultPoint(GetNotTransformed(index));
2613 end;
2614
2615 function CalculateBoundingBoxFromIndices(
2616 const GetVertIndex: TGetIndexFromIndexNumFunc;
2617 const VertsIndicesCount: integer;
2618 const GetVertex: TGetVertexFromIndexFunc;
2619 const Transform: TMatrix4): TBox3D;
2620 var
2621 Calculator: TVertTransform_Calculator;
2622 begin
2623 Calculator := TVertTransform_Calculator.Create;
2624 try
2625 Calculator.PTransform := @Transform;
2626 Calculator.GetNotTransformed := GetVertex;
2627 result := CalculateBoundingBoxFromIndices(
2628 GetVertIndex,
2629 VertsIndicesCount,
2630 {$ifdef FPC} @ {$endif} Calculator.GetTransformed);
2631 finally Calculator.Free end;
2632 end;
2633
2634 function TriangleBoundingBox(const T: TTriangle3): TBox3D;
2635 begin
2636 MinMax(T.Data[0].X, T.Data[1].X, T.Data[2].X, Result.Data[0].X, Result.Data[1].X);
2637 MinMax(T.Data[0].Y, T.Data[1].Y, T.Data[2].Y, Result.Data[0].Y, Result.Data[1].Y);
2638 MinMax(T.Data[0].Z, T.Data[1].Z, T.Data[2].Z, Result.Data[0].Z, Result.Data[1].Z);
2639 end;
2640
2641 function BoundingBox3DFromSphere(const Center: TVector3;
2642 const Radius: Single): TBox3D;
2643 begin
2644 Result.Data[0] := Center;
2645 Result.Data[0].X := Result.Data[0].X - Radius;
2646 Result.Data[0].Y := Result.Data[0].Y - Radius;
2647 Result.Data[0].Z := Result.Data[0].Z - Radius;
2648
2649 Result.Data[1] := Center;
2650 Result.Data[1].X := Result.Data[1].X + Radius;
2651 Result.Data[1].Y := Result.Data[1].Y + Radius;
2652 Result.Data[1].Z := Result.Data[1].Z + Radius;
2653 end;
2654
2655 end.