Debian Codegraph @

src/physics/kraft/kraft.pas

raw
1 (******************************************************************************
2 * KRAFT PHYSICS ENGINE *
3 ******************************************************************************
4 * Version 2019-08-26-10-17-0000 *
5 ******************************************************************************
6 * zlib license *
7 *============================================================================*
8 * *
9 * Copyright (c) 2015-2018, Benjamin Rosseaux ([email protected]) *
10 * *
11 * This software is provided 'as-is', without any express or implied *
12 * warranty. In no event will the authors be held liable for any damages *
13 * arising from the use of this software. *
14 * *
15 * Permission is granted to anyone to use this software for any purpose, *
16 * including commercial applications, and to alter it and redistribute it *
17 * freely, subject to the following restrictions: *
18 * *
19 * 1. The origin of this software must not be misrepresented; you must not *
20 * claim that you wrote the original software. If you use this software *
21 * in a product, an acknowledgement in the product documentation would be *
22 * appreciated but is not required. *
23 * 2. Altered source versions must be plainly marked as such, and must not be *
24 * misrepresented as being the original software. *
25 * 3. This notice may not be removed or altered from any source distribution. *
26 * *
27 ******************************************************************************
28 * General guidelines for code contributors *
29 *============================================================================*
30 * *
31 * 1. Make sure you are legally allowed to make a contribution under the zlib *
32 * license. *
33 * 2. The zlib license header goes at the top of each source file, with *
34 * appropriate copyright notice. *
35 * 3. After a pull request, check the status of your pull request on *
36 http://github.com/BeRo1985/kraft *
37 * 4. Write code, which is compatible with Delphi 7-XE7 and FreePascal >= 2.6 *
38 * so don't use generics/templates, operator overloading and another newer *
39 * syntax features than Delphi 7 has support for that. *
40 * 5. Don't use Delphi VCL, FreePascal FCL or Lazarus LCL libraries/units. *
41 * 6. No use of third-party libraries/units as possible, but if needed, make *
42 * it out-ifdef-able *
43 * 7. Try to use const when possible. *
44 * 8. Make sure to comment out writeln, used while debugging *
45 * 9. Use TKraftScalar instead of float/double so that Kraft can be compiled *
46 * as double/single precision. *
47 * 10. Make sure the code compiles on 32-bit and 64-bit platforms in single *
48 * and double precision. *
49 * *
50 ******************************************************************************)
51 unit kraft;
52 {$ifdef fpc}
53 {$mode delphi}
54 {$warnings off}
55 {$hints off}
56 {$define caninline}
57 {$ifdef cpui386}
58 {$define cpu386}
59 {$endif}
60 {$ifdef cpuamd64}
61 {$define cpux86_64}
62 {$define cpux64}
63 {$else}
64 {$ifdef cpux86_64}
65 {$define cpuamd64}
66 {$define cpux64}
67 {$endif}
68 {$endif}
69 {$ifdef cpu386}
70 {$define cpu386}
71 {$asmmode intel}
72 {$define canx86simd}
73 {$endif}
74 {$ifdef FPC_LITTLE_ENDIAN}
75 {$define LITTLE_ENDIAN}
76 {$else}
77 {$ifdef FPC_BIG_ENDIAN}
78 {$define BIG_ENDIAN}
79 {$endif}
80 {$endif}
81 {$else} // Delphi
82 {$define LITTLE_ENDIAN}
83 {$ifndef cpu64}
84 {$define cpu32}
85 {$endif}
86 {$safedivide off}
87 {$optimization on}
88 {$undef caninline}
89 {$undef canx86simd}
90 {$ifdef conditionalexpressions}
91 {$if CompilerVersion>=24.0}
92 {$legacyifend on}
93 {$ifend}
94 {$endif}
95 {$ifdef ver180}
96 {$define caninline}
97 {$ifdef cpu386}
98 {$define canx86simd}
99 {$endif}
100 {$finitefloat off}
101 {$endif}
102 {$endif}
103 {$ifdef win32}
104 {$define windows}
105 {$endif}
106 {$ifdef win64}
107 {$define windows}
108 {$endif}
109 {$extendedsyntax on}
110 {$writeableconst on}
111 {$varstringchecks on}
112 {$typedaddress off}
113 {$overflowchecks off}
114 {$rangechecks off}
115 {$ifndef fpc}
116 {$realcompatibility off}
117 {$endif}
118 {$openstrings on}
119 {$longstrings on}
120 {$booleval off}
121 {$typeinfo on}
122
123 {-$define UseMoreCollisionGroups}
124
125 {$define UseTriangleMeshFullPerturbation}
126
127 {-$define DebugDraw}
128
129 {-$define memdebug}
130
131 {$ifdef UseDouble}
132 {$define NonSIMD}
133 {$endif}
134
135 { Apply some Castle Game Engine compilation defines.
136
137 This may change state of symbols:
138 - caninline
139 - NonSIMD
140 so include it *after* Kraft code above (potentially) defined them,
141 and *before* these symbols are acted upon.
142 This way castlekraft.inc can "override" what Kraft is doing. }
143 {$I castlekraft.inc}
144
145 {$ifdef NonSIMD}
146 {$undef CPU386ASMForSinglePrecision}
147 {$undef SIMD}
148 {$else}
149 {$ifdef cpu386}
150 {$if not (defined(Darwin) or defined(CompileForWithPIC))}
151 {$define CPU386ASMForSinglePrecision}
152 {$ifend}
153 {$endif}
154 {$undef SIMD}
155 {$ifdef CPU386ASMForSinglePrecision}
156 {$define SIMD}
157 {$endif}
158 {$endif}
159
160 interface
161
162 uses {$ifdef windows}
163 Windows,
164 MMSystem,
165 {$else}
166 {$ifdef unix}
167 BaseUnix,
168 Unix,
169 UnixType,
170 {$if defined(linux) or defined(android)}
171 linux,
172 {$ifend}
173 {$else}
174 // Use CGE cross-platform routines for time, instead of relying on SDL.
175 // SDL,
176 CastleTimeUtils,
177 {$define USE_CASTLE_TIME_UTILS}
178 {$endif}
179 {$endif}
180 {$ifdef DebugDraw}
181 {$ifdef fpc}
182 GL,
183 GLext,
184 {$else}
185 OpenGL,
186 {$endif}
187 {$endif}
188 SysUtils,
189 Classes,
190 SyncObjs,
191 {$ifdef KraftPasMP}
192 PasMP,
193 {$endif}
194 Math;
195
196 { CGE: Delphi on Linux doesn't define
197 - TFPUPrecisionMode, SetPrecisionMode
198 - TFPUExceptionMask, SetFPUExceptionMask }
199 {$if defined(FPC) or defined(MSWINDOWS)}
200 {$define HAS_FPU_TYPES}
201 {$ifend}
202
203 { Delphi on non-Windows redefines LongInt/LongWord in a way inconsistent
204 with Delphi/Windows or FPC.
205 Make Kraft use expected type sizes.
206 We don't just search + replace this in Kraft sources, to ease upgrading
207 Kraft in the future.
208 See https://castle-engine.io/coding_conventions#no_longint_longword .
209 This seems already handled better in recent Kraft,
210 https://github.com/BeRo1985/kraft/blob/master/src/kraft.pas ,
211 that avoids LongInt/LongWord just like CGE. }
212 {$if (not defined(FPC)) and (not defined(MSWINDOWS))}
213 type
214 LongInt = Integer;
215 LongWord = Cardinal;
216 {$ifend}
217
218 const EPSILON={$ifdef UseDouble}1e-14{$else}1e-5{$endif}; // actually {$ifdef UseDouble}1e-16{$else}1e-7{$endif}; but we are conservative here
219
220 MAX_SCALAR={$ifdef UseDouble}1.7e+308{$else}3.4e+28{$endif};
221
222 DEG2RAD=pi/180.0;
223 RAD2DEG=180.0/PI;
224
225 MAX_CONTACTS=4; // After largest-area contact reduction
226
227 MAX_TEMPORARY_CONTACTS=256; // Before largest-area contact reduction
228
229 MAX_THREADS=32;
230
231 MaxSATSupportVertices=64;
232 MaxSATContacts=64;
233
234 MPRTolerance=1e-3;
235
236 MPRMaximumIterations=128;
237
238 MPRSweepCastMaximumIterations=32;
239
240 GJKTolerance=1e-4;
241
242 GJKMaximumIterations=128;
243
244 TimeOfImpactTolerance=1e-3;
245
246 TimeOfImpactMaximumIterations=64;
247
248 TimeOfImpactSphericalExpansionRadius=1e-5;
249
250 {$ifdef HAS_FPU_TYPES}
251 PhysicsFPUPrecisionMode:TFPUPrecisionMode={$ifdef cpu386}pmExtended{$else}{$ifdef cpux64}pmExtended{$else}pmDouble{$endif}{$endif};
252
253 PhysicsFPUExceptionMask:TFPUExceptionMask=[exInvalidOp,exDenormalized,exZeroDivide,exOverflow,exUnderflow,exPrecision];
254 {$endif}
255
256 KRAFT_QUICKHULL_FACE_MARK_VISIBLE=1;
257 KRAFT_QUICKHULL_FACE_MARK_NON_CONVEX=2;
258 KRAFT_QUICKHULL_FACE_MARK_NON_DELETED=3;
259
260 KRAFT_QUICKHULL_FACE_FLAG_CLOCKWISE=1 shl 0;
261 KRAFT_QUICKHULL_FACE_FLAG_INDEXED_FROM_ONE=1 shl 1;
262 KRAFT_QUICKHULL_FACE_FLAG_INDEXED_FROM_ZERO=1 shl 2;
263 KRAFT_QUICKHULL_FACE_FLAG_POINT_RELATIVE=1 shl 3;
264
265 KRAFT_QUICKHULL_AUTOMATIC_TOLERANCE=-1;
266
267 KRAFT_QUICKHULL_MERGE_TYPE_NONCONVEX_WRT_LARGER_FACE=1;
268 KRAFT_QUICKHULL_MERGE_TYPE_NONCONVEX=2;
269
270 KRAFT_QUICKHULL_HASHBITS=8;
271 KRAFT_QUICKHULL_HASHSIZE=1 shl KRAFT_QUICKHULL_HASHBITS;
272 KRAFT_QUICKHULL_HASHMASK=KRAFT_QUICKHULL_HASHSIZE-1;
273
274 type PKraftForceMode=^TKraftForceMode;
275 TKraftForceMode=(kfmForce, // The unit of the force parameter is applied to the rigidbody as mass*distance/time^2.
276 kfmAcceleration, // The unit of the force parameter is applied to the rigidbody as distance/time^2.
277 kfmImpulse, // The unit of the force parameter is applied to the rigidbody as mass*distance/time.
278 kfmVelocity); // The unit of the force parameter is applied to the rigidbody as distance/time.
279
280 PKraftContinuousMode=^TKraftContinuousMode;
281 TKraftContinuousMode=(kcmNone, // No continuous collision detection and response
282 kcmSpeculativeContacts, // Fake continuous collision detection and response with speculative contacts
283 kcmMotionClamping, // Continuous collision detection and response with motion clamping
284 kcmTimeOfImpactSubSteps); // Continuous collision detection and response with time of impact sub stepping
285 // (needs kpcmNonLinearGaussSeidel at ContactPositionCorrectionMode, otherwise it
286 // fallbacks to kcmMotionClamping, when kpcmBaumgarte is used at
287 // ContactPositionCorrectionMode)
288
289 PKraftTimeOfImpactAlgorithm=^TKraftTimeOfImpactAlgorithm;
290 TKraftTimeOfImpactAlgorithm=(ktoiaConservativeAdvancement, // Time of impact detection with conservative advancement
291 ktoiaBilateralAdvancement); // Time of impact detection with bilateral advancement
292
293 PKraftPositionCorrectionMode=^TKraftPositionCorrectionMode;
294 TKraftPositionCorrectionMode=(kpcmBaumgarte, // Faster but it can be inaccurate in some situations
295 kpcmNonLinearGaussSeidel); // Slower but it's more precise (default)
296
297 PKraftContactFlag=^TKraftContactFlag;
298 TKraftContactFlag=(kcfEnabled, // To disable contacts by users and for internal usage for processing continuous collection detection
299 kcfColliding, // Set when contact collides during a step
300 kcfWasColliding, // Set when two objects stop colliding
301 kcfInIsland, // For internal marking during island forming
302 kcfFiltered, // For internal filering
303 kcfTimeOfImpact); // For internal marking during time of impact stuff
304
305 PKraftContactFlags=^TKraftContactFlags;
306 TKraftContactFlags=set of TKraftContactFlag;
307
308 PKraftConstraintFlag=^TKraftConstraintFlag;
309 TKraftConstraintFlag=(kcfCollideConnected,
310 kcfBreakable,
311 kcfActive,
312 kcfVisited,
313 kcfBreaked,
314 kcfFreshBreaked);
315
316 PKraftConstraintFlags=^TKraftConstraintFlags;
317
318 TKraftConstraintFlags=set of TKraftConstraintFlag;
319
320 PKraftConstraintLimitBehavior=^TKraftConstraintLimitBehavior;
321 TKraftConstraintLimitBehavior=(kclbLimitDistance,
322 kclbLimitMaximumDistance,
323 kclbLimitMinimumDistance);
324
325 PKraftShapeType=^TKraftShapeType;
326 TKraftShapeType=(kstUnknown=0,
327 kstSphere,
328 kstCapsule,
329 kstConvexHull,
330 kstBox, // Internally derived from convex hull
331 kstPlane, // Internally derived from convex hull
332 kstTriangle, // Internally derived from convex hull and only for internal usage only at mesh shapes
333 kstMesh); // Static only
334
335 PKraftShapeFlag=^TKraftShapeFlag;
336 TKraftShapeFlag=(ksfCollision,
337 ksfMass,
338 ksfSensor,
339 ksfRayCastable);
340
341 PKraftShapeFlags=^TKraftShapeFlags;
342 TKraftShapeFlags=set of TKraftShapeFlag;
343
344 PKraftRigidBodyType=^TKraftRigidBodyType;
345 TKraftRigidBodyType=(krbtUnknown,
346 krbtStatic,
347 krbtDynamic,
348 krbtKinematic);
349
350 PKraftRigidBodyFlag=^TKraftRigidBodyFlag;
351 TKraftRigidBodyFlag=(krbfHasOwnGravity,
352 krbfContinuous,
353 krbfContinuousAgainstDynamics,
354 krbfAllowSleep,
355 krbfAwake,
356 krbfActive,
357 krbfLockTranslationAxisX,
358 krbfLockTranslationAxisY,
359 krbfLockTranslationAxisZ,
360 krbfLockRotationAxisX,
361 krbfLockRotationAxisY,
362 krbfLockRotationAxisZ,
363 krbfSensor,
364 krbfIslandVisited,
365 krbfIslandStatic);
366
367 PKraftRigidBodyFlags=^TKraftRigidBodyFlags;
368 TKraftRigidBodyFlags=set of TKraftRigidBodyFlag;
369
370 PKraftRigidBodyCollisionGroup=^TKraftRigidBodyCollisionGroup;
371 TKraftRigidBodyCollisionGroup={$ifdef UseMoreCollisionGroups}0..255{$else}0..31{$endif};
372
373 PKraftRigidBodyCollisionGroups=^TKraftRigidBodyCollisionGroup;
374 TKraftRigidBodyCollisionGroups=set of TKraftRigidBodyCollisionGroup;
375
376 EKraftShapeTypeOnlyForStaticRigidBody=class(Exception);
377
378 EKraftCorruptMeshData=class(Exception);
379
380 EKraftDegeneratedConvexHull=class(Exception);
381
382 TKraft=class;
383
384 TKraftContactManager=class;
385
386 TKraftIsland=class;
387
388 TKraftShape=class;
389
390 TKraftRigidBody=class;
391
392 TKraftHighResolutionTimer=class
393 private
394 fFrequency:int64;
395 fFrequencyShift:longint;
396 fFrameInterval:int64;
397 fMillisecondInterval:int64;
398 fTwoMillisecondsInterval:int64;
399 fFourMillisecondsInterval:int64;
400 fQuarterSecondInterval:int64;
401 fHourInterval:int64;
402 public
403 constructor Create(FrameRate:longint=60);
404 destructor Destroy; override;
405 procedure SetFrameRate(FrameRate:longint);
406 function GetTime:int64;
407 function GetEventTime:int64;
408 procedure Sleep(Delay:int64);
409 function ToFixedPointSeconds(Time:int64):int64;
410 function ToFixedPointFrames(Time:int64):int64;
411 function ToFloatSeconds(Time:int64):double;
412 function FromFloatSeconds(Time:double):int64;
413 function ToMilliseconds(Time:int64):int64;
414 function FromMilliseconds(Time:int64):int64;
415 function ToMicroseconds(Time:int64):int64;
416 function FromMicroseconds(Time:int64):int64;
417 function ToNanoseconds(Time:int64):int64;
418 function FromNanoseconds(Time:int64):int64;
419 property SecondInterval:int64 read fFrequency;
420 property Frequency:int64 read fFrequency;
421 property FrequencyShift:longint read fFrequencyShift;
422 property FrameInterval:int64 read fFrameInterval;
423 property MillisecondInterval:int64 read fMillisecondInterval;
424 property TwoMillisecondsInterval:int64 read fTwoMillisecondsInterval;
425 property FourMillisecondsInterval:int64 read fFourMillisecondsInterval;
426 property QuarterSecondInterval:int64 read fQuarterSecondInterval;
427 property HourInterval:int64 read fHourInterval;
428 end;
429
430 PKraftScalar=^TKraftScalar;
431 TKraftScalar={$ifdef UseDouble}double{$else}single{$endif};
432
433 PKraftColor=^TKraftColor;
434 TKraftColor=record
435 r,g,b,a:TKraftScalar;
436 end;
437
438 PKraftAngles=^TKraftAngles;
439 TKraftAngles=record
440 Pitch,Yaw,Roll:TKraftScalar;
441 end;
442
443 PKraftVector2=^TKraftVector2;
444 TKraftVector2=record
445 x,y:TKraftScalar;
446 end;
447
448 PKraftRawVector3=^TKraftRawVector3;
449 TKraftRawVector3=record
450 case byte of
451 0:(x,y,z:TKraftScalar);
452 1:(xyz:array[0..2] of TKraftScalar);
453 end;
454
455 PKraftVector3=^TKraftVector3;
456 TKraftVector3=record
457 case byte of
458 0:(x,y,z{$ifdef SIMD},w{$endif}:TKraftScalar);
459 1:(Pitch,Yaw,Roll:single);
460 2:(xyz:array[0..2] of TKraftScalar);
461 3:(PitchYawRoll:array[0..2] of single);
462 4:(RawVector:TKraftRawVector3);
463 {$ifdef SIMD}
464 5:(xyzw:array[0..3] of TKraftScalar);
465 {$endif}
466 end;
467
468 PKraftVector4=^TKraftVector4;
469 TKraftVector4=record
470 case byte of
471 0:(x,y,z,w:TKraftScalar);
472 1:(xyz:array[0..2] of TKraftScalar);
473 2:(xyzw:array[0..3] of TKraftScalar);
474 end;
475
476 TKraftVector3Array=array of TKraftVector3;
477
478 PKraftVector3s=^TKraftVector3s;
479 TKraftVector3s=array[0..$ff] of TKraftVector3;
480
481 PPKraftVector3s=^TPKraftVector3s;
482 TPKraftVector3s=array[0..$ff] of PKraftVector3;
483
484 PKraftPlane=^TKraftPlane;
485 TKraftPlane=record
486 Normal:TKraftVector3;
487 Distance:TKraftScalar;
488 end;
489
490 PKraftQuaternion=^TKraftQuaternion;
491 TKraftQuaternion=record
492 x,y,z,w:TKraftScalar;
493 end;
494
495 PKraftMatrix2x2=^TKraftMatrix2x2;
496 TKraftMatrix2x2=array[0..1,0..1] of TKraftScalar;
497
498 PKraftMatrix3x3=^TKraftMatrix3x3;
499 TKraftMatrix3x3=array[0..2,0..{$ifdef SIMD}3{$else}2{$endif}] of TKraftScalar;
500
501 PKraftMatrix4x4=^TKraftMatrix4x4;
502 TKraftMatrix4x4=array[0..3,0..3] of TKraftScalar;
503
504 PKraftAABB=^TKraftAABB;
505 TKraftAABB=record
506 case boolean of
507 false:(
508 Min,Max:TKraftVector3;
509 );
510 true:(
511 MinMax:array[0..1] of TKraftVector3;
512 );
513 end;
514
515 PKraftAABBs=^TKraftAABBs;
516 TKraftAABBs=array[0..65535] of TKraftAABB;
517
518 PKraftSphere=^TKraftSphere;
519 TKraftSphere=record
520 Center:TKraftVector3;
521 Radius:TKraftScalar;
522 end;
523
524 PKraftSpheres=^TKraftSpheres;
525 TKraftSpheres=array[0..65535] of TKraftSphere;
526
527 PKraftSegment=^TKraftSegment;
528 TKraftSegment=record
529 Points:array[0..1] of TKraftVector3;
530 end;
531
532 PKraftRelativeSegment=^TKraftRelativeSegment;
533 TKraftRelativeSegment=record
534 Origin:TKraftVector3;
535 Delta:TKraftVector3;
536 end;
537
538 PKraftTriangle=^TKraftTriangle;
539 TKraftTriangle=record
540 Points:array[0..2] of TKraftVector3;
541 Normal:TKraftVector3;
542 end;
543
544 PKraftTimeStep=^TKraftTimeStep;
545 TKraftTimeStep=record
546 DeltaTime:TKraftScalar;
547 InverseDeltaTime:TKraftScalar;
548 DeltaTimeRatio:TKraftScalar;
549 WarmStarting:boolean;
550 end;
551
552 // This class does exist as workaround for FreePascal, which doesn't support TKraftVector3 as published property (but Delphi does it)
553 TKraftVector3Property=class(TPersistent)
554 private
555 fVector:PKraftVector3;
556 function GetX:TKraftScalar;
557 function GetY:TKraftScalar;
558 function GetZ:TKraftScalar;
559 function GetVector:TKraftVector3;
560 procedure SetX(const NewValue:TKraftScalar);
561 procedure SetY(const NewValue:TKraftScalar);
562 procedure SetZ(const NewValue:TKraftScalar);
563 procedure SetVector(const NewVector:TKraftVector3);
564 public
565 constructor Create(AVector:PKraftVector3);
566 destructor Destroy; override;
567 property Vector:TKraftVector3 read GetVector write SetVector;
568 published
569 property x:TKraftScalar read GetX write SetX;
570 property y:TKraftScalar read GetY write SetY;
571 property z:TKraftScalar read GetZ write SetZ;
572 end;
573
574 PKraftDynamicAABBTreeNode=^TKraftDynamicAABBTreeNode;
575 TKraftDynamicAABBTreeNode=record
576 AABB:TKraftAABB;
577 UserData:pointer;
578 Children:array[0..1] of longint;
579 Height:longint;
580 case boolean of
581 false:(
582 Parent:longint;
583 );
584 true:(
585 Next:longint;
586 );
587 end;
588
589 PKraftDynamicAABBTreeNodes=^TKraftDynamicAABBTreeNodes;
590 TKraftDynamicAABBTreeNodes=array[0..0] of TKraftDynamicAABBTreeNode;
591
592 PKraftDynamicAABBTreeLongintArray=^TKraftDynamicAABBTreeLongintArray;
593 TKraftDynamicAABBTreeLongintArray=array[0..65535] of longint;
594
595 TKraftDynamicAABBTree=class
596 private
597 fRoot:longint;
598 fNodes:PKraftDynamicAABBTreeNodes;
599 fNodeCount:longint;
600 fNodeCapacity:longint;
601 fFreeList:longint;
602 fPath:longword;
603 fInsertionCount:longint;
604 fStack:PKraftDynamicAABBTreeLongintArray;
605 fStackCapacity:longint;
606 public
607 constructor Create;
608 destructor Destroy; override;
609 function AllocateNode:longint;
610 procedure FreeNode(NodeID:longint);
611 function Balance(NodeAID:longint):longint;
612 procedure InsertLeaf(Leaf:longint);
613 procedure RemoveLeaf(Leaf:longint);
614 function CreateProxy(const AABB:TKraftAABB;UserData:pointer):longint;
615 procedure DestroyProxy(NodeID:longint);
616 function MoveProxy(NodeID:longint;const AABB:TKraftAABB;const Displacement,BoundsExpansion:TKraftVector3):boolean;
617 procedure Rebalance(Iterations:longint);
618 procedure Rebuild;
619 function ComputeHeight:longint;
620 function GetHeight:longint;
621 function GetAreaRatio:TKraftScalar;
622 function GetMaxBalance:longint;
623 function ValidateStructure:boolean;
624 function ValidateMetrics:boolean;
625 function Validate:boolean;
626 function GetIntersectionProxy(const AABB:TKraftAABB):pointer;
627 property Root:longint read fRoot;
628 property Nodes:PKraftDynamicAABBTreeNodes read fNodes;
629 property NodeCount:longint read fNodeCount;
630 property NodeCapacity:longint read fNodeCapacity;
631 property FreeList:longint read fFreeList;
632 property Path:longword read fPath;
633 property InsertionCount:longint read fInsertionCount;
634 end;
635
636 PKraftSweep=^TKraftSweep;
637 TKraftSweep=record
638 LocalCenter:TKraftVector3; // Center of mass in local space
639 c0,c:TKraftVector3; // Center of mass in world space
640 q0,q:TKraftQuaternion; // Rotation/Orientation
641 Alpha0:TKraftScalar; // Fraction of timestep from [0, 1]; c0, and q0 are at Alpha0
642 end;
643
644 PKraftMassData=^TKraftMassData;
645 TKraftMassData=record
646 Inertia:TKraftMatrix3x3;
647 Center:TKraftVector3;
648 Mass:TKraftScalar;
649 Volume:TKraftScalar;
650 end;
651
652 // 64-bit contact feature ID
653 PKraftContactFeatureID=^TKraftContactFeatureID;
654 TKraftContactFeatureID=record
655 case longint of
656 0:(
657 // when the last bit isn't set => continuous edge numbering at convex hulls for face<->face contacts
658 // when the last bit is set => continuous edge numbering at convex hulls for edge<->edge contacts
659 ElementA:longword;
660 ElementB:longword;
661 );
662 1:(
663 // -1 => feature matching per nearest point search (like for example Bullet does it also)
664 Key:int64;
665 );
666 end;
667
668 PKraftClipVertex=^TKraftClipVertex;
669 TKraftClipVertex=record
670 Position:TKraftVector3;
671 FeatureID:TKraftContactFeatureID;
672 end;
673
674 TKraftClipVertices=array of TKraftClipVertex;
675
676 TKraftClipVertexList=class
677 private
678 fVertices:TKraftClipVertices;
679 fCapacity:longint;
680 fCount:longint;
681 fColor:TKraftColor;
682 public
683 constructor Create;
684 destructor Destroy; override;
685 procedure Clear;
686 procedure Add(const v:TKraftVector3;const fp:TKraftContactFeatureID); overload;
687 procedure Add(const v:TKraftClipVertex); overload;
688 property Vertices:TKraftClipVertices read fVertices write fVertices;
689 property Capacity:longint read fCapacity write fCapacity;
690 property Count:longint read fCount write fCount;
691 property Color:TKraftColor read fColor write fColor;
692 end;
693
694 PKraftRaycastData=^TKraftRaycastData;
695 TKraftRaycastData=record
696 Origin:TKraftVector3;
697 Direction:TKraftVector3;
698 MaxTime:TKraftScalar;
699 TimeOfImpact:TKraftScalar;
700 Point:TKraftVector3;
701 Normal:TKraftVector3;
702 end;
703
704 EKraftQuickHull=class(Exception);
705
706 PKraftQuickHullIntegerArray=^TKraftQuickHullIntegerArray;
707 TKraftQuickHullIntegerArray=array[0..(2147483647 div sizeof(longint))-1] of longint;
708
709 TKraftQuickHullIntegerList=class
710 private
711 fList:PKraftQuickHullIntegerArray;
712 fCountItems:longint;
713 fAllocated:longint;
714 fIsSorted:boolean;
715 function GetItem(Index:longint):longint;
716 procedure SetItem(Index:longint;Value:longint);
717 function GetItemPointer(Index:longint):pointer;
718 public
719 constructor Create;
720 destructor Destroy; override;
721 procedure Clear;
722 function Add(Item:longint):longint;
723 procedure AddSorted(Item:longint);
724 procedure Insert(Index:longint;Item:longint);
725 procedure Delete(Index:longint);
726 function Remove(Item:longint):longint;
727 function Find(Item:longint):longint;
728 function IndexOf(Item:longint):longint;
729 procedure Exchange(Index1,Index2:longint);
730 procedure SetCapacity(NewCapacity:longint);
731 procedure SetCount(NewCount:longint);
732 procedure Sort;
733 property Count:longint read fCountItems;
734 property Capacity:longint read fAllocated write SetCapacity;
735 property Item[Index:longint]:longint read GetItem write SetItem; default;
736 property Items[Index:longint]:longint read GetItem write SetItem;
737 property PItems[Index:longint]:pointer read GetItemPointer;
738 end;
739
740 TKraftQuickHull=class;
741
742 PKraftQuickHullVector3D=^TKraftQuickHullVector3D;
743 TKraftQuickHullVector3D={$ifdef FPC}object{$else}record{$endif}
744 public
745 x:double;
746 y:double;
747 z:double;
748 function Init(const ax:double=0.0;const ay:double=0.0;const az:double=0.0):TKraftQuickHullVector3D;
749 procedure SetValue(i:longint;const v:double);
750 function GetValue(i:longint):double;
751 procedure Add(const v0,v1:TKraftQuickHullVector3D); overload;
752 procedure Add(const v:TKraftQuickHullVector3D); overload;
753 procedure Sub(const v0,v1:TKraftQuickHullVector3D); overload;
754 procedure Sub(const v:TKraftQuickHullVector3D); overload;
755 procedure Scale(const v:TKraftQuickHullVector3D;const s:double); overload;
756 procedure Scale(const s:double); overload;
757 function Length:double;
758 function LengthSquared:double;
759 function Distance(const v:TKraftQuickHullVector3D):double;
760 function DistanceSquared(const v:TKraftQuickHullVector3D):double;
761 procedure Normalize;
762 function Dot(const v:TKraftQuickHullVector3D):double;
763 procedure CrossProduct(const v0,v1:TKraftQuickHullVector3D);
764 procedure SetRandom(Lower,Upper:double);
765 function Equals(const v:TKraftQuickHullVector3D):boolean;
766 end;
767
768 TKraftQuickHullVector3DArray=array of TKraftQuickHullVector3D;
769
770 TKraftQuickHullOutputFace=array of longint;
771
772 TKraftQuickHullOutputFaces=array of TKraftQuickHullOutputFace;
773
774 TKraftQuickHullHalfEdge=class;
775
776 TKraftQuickHullFace=class;
777
778 TKraftQuickHullVertex=class
779 private
780 fInstance:TKraftQuickHull;
781 fPoint:TKraftQuickHullVector3D;
782 fIndex:longint;
783 fPrevious:TKraftQuickHullVertex;
784 fNext:TKraftQuickHullVertex;
785 fFace:TKraftQuickHullFace;
786 fHashNext:TKraftQuickHullVertex;
787 public
788 constructor Create(const AInstance:TKraftQuickHull);
789 destructor Destroy; override;
790 property Instance:TKraftQuickHull read fInstance;
791 property Point:TKraftQuickHullVector3D read fPoint write fPoint;
792 property Index:longint read fIndex write fIndex;
793 property Previous:TKraftQuickHullVertex read fPrevious write fPrevious;
794 property Next:TKraftQuickHullVertex read fNext write fNext;
795 property Face:TKraftQuickHullFace read fFace write fFace;
796 property HashNext:TKraftQuickHullVertex read fHashNext write fHashNext;
797 end;
798
799 PKraftQuickHullThreeVertices=^TKraftQuickHullThreeVertices;
800 TKraftQuickHullThreeVertices=array[0..2] of TKraftQuickHullVertex;
801
802 PKraftQuickHullVertexList=^TKraftQuickHullVertexList;
803 TKraftQuickHullVertexList={$ifdef FPC}object{$else}record{$endif}
804 public
805 Head:TKraftQuickHullVertex;
806 Tail:TKraftQuickHullVertex;
807 procedure Clear;
808 procedure Add(vtx:TKraftQuickHullVertex);
809 procedure AddAll(vtx:TKraftQuickHullVertex);
810 procedure Delete(vtx:TKraftQuickHullVertex); overload;
811 procedure Delete(vtx1,vtx2:TKraftQuickHullVertex); overload;
812 procedure InsertBefore(vtx,Next:TKraftQuickHullVertex);
813 function First:TKraftQuickHullVertex;
814 function IsEmpty:boolean;
815 end;
816
817 PKraftQuickHullFaceList=^TKraftQuickHullFaceList;
818 TKraftQuickHullFaceList={$ifdef FPC}object{$else}record{$endif}
819 public
820 Head:TKraftQuickHullFace;
821 Tail:TKraftQuickHullFace;
822 procedure Clear;
823 procedure Add(vtx:TKraftQuickHullFace);
824 function First:TKraftQuickHullFace;
825 function IsEmpty:boolean;
826 end;
827
828 TKraftQuickHullFace=class
829 private
830 fInstance:TKraftQuickHull;
831 fNext:TKraftQuickHullFace;
832 fhe0:TKraftQuickHullHalfEdge;
833 fNormal:TKraftQuickHullVector3D;
834 fArea:double;
835 fCentroid:TKraftQuickHullVector3D;
836 fPlaneOffset:double;
837 fIndex:longint;
838 fCountVertices:longint;
839 fMark:longint;
840 fOutside:TKraftQuickHullVertex;
841 public
842 constructor Create(const AInstance:TKraftQuickHull);
843 constructor CreatePolygon(const AInstance:TKraftQuickHull;const AVertices:array of TKraftQuickHullVertex;const AIndices:array of longint);
844 constructor CreateTriangle(const AInstance:TKraftQuickHull;const v0,v1,v2:TKraftQuickHullVertex;const AMinArea:double=0.0);
845 destructor Destroy; override;
846 procedure ComputeCentroid(var ACentroid:TKraftQuickHullVector3D);
847 procedure ComputeNormal(var ANormal:TKraftQuickHullVector3D); overload;
848 procedure ComputeNormal(var ANormal:TKraftQuickHullVector3D;const AMinArea:double); overload;
849 procedure ComputeNormalAndCentroid; overload;
850 procedure ComputeNormalAndCentroid(const AMinArea:double); overload;
851 function GetEdge(i:longint):TKraftQuickHullHalfEdge;
852 function GetFirstEdge:TKraftQuickHullHalfEdge;
853 function FindEdge(const vt,vh:TKraftQuickHullVertex):TKraftQuickHullHalfEdge;
854 function DistanceToPlane(const p:TKraftQuickHullVector3D):double;
855 function ConnectHalfEdges(const hedgePrev,hedge:TKraftQuickHullHalfEdge):TKraftQuickHullFace;
856 procedure CheckConsistency;
857 function MergeAdjacentFace(const hedgeAdj:TKraftQuickHullHalfEdge;const Discarded:TList):longint;
858 function AreaSquared(const hedge0,hedge1:TKraftQuickHullHalfEdge):double;
859 procedure Triangulate(var NewFaces:TKraftQuickHullFaceList;const MinArea:double);
860 property Instance:TKraftQuickHull read fInstance;
861 property Next:TKraftQuickHullFace read fNext write fNext;
862 property he0:TKraftQuickHullHalfEdge read fhe0 write fhe0;
863 property Normal:TKraftQuickHullVector3D read fNormal write fNormal;
864 property Area:double read fArea write fArea;
865 property Centroid:TKraftQuickHullVector3D read fCentroid write fCentroid;
866 property PlaneOffset:double read fPlaneOffset write fPlaneOffset;
867 property Index:longint read fIndex write fIndex;
868 property CountVertices:longint read fCountVertices write fCountVertices;
869 property Mark:longint read fMark write fMark;
870 property Outside:TKraftQuickHullVertex read fOutside write fOutside;
871 end;
872
873 TKraftQuickHullHalfEdge=class
874 private
875 fInstance:TKraftQuickHull;
876 fVertex:TKraftQuickHullVertex;
877 fFace:TKraftQuickHullFace;
878 fNext:TKraftQuickHullHalfEdge;
879 fPrevious:TKraftQuickHullHalfEdge;
880 fOpposite:TKraftQuickHullHalfEdge;
881 public
882 constructor Create(const AInstance:TKraftQuickHull;const v:TKraftQuickHullVertex=nil;const f:TKraftQuickHullFace=nil);
883 destructor Destroy; override;
884 procedure SetOpposite(const Edge:TKraftQuickHullHalfEdge);
885 function Head:TKraftQuickHullVertex;
886 function Tail:TKraftQuickHullVertex;
887 function OppositeFace:TKraftQuickHullFace;
888 function Length:double;
889 function LengthSquared:double;
890 property Instance:TKraftQuickHull read fInstance;
891 property Vertex:TKraftQuickHullVertex read fVertex write fVertex;
892 property Face:TKraftQuickHullFace read fFace write fFace;
893 property Next:TKraftQuickHullHalfEdge read fNext write fNext;
894 property Previous:TKraftQuickHullHalfEdge read fPrevious write fPrevious;
895 property Opposite:TKraftQuickHullHalfEdge read fOpposite write fOpposite;
896 end;
897
898 PKraftQuickHullVertexHashTable=^TKraftQuickHullVertexHashTable;
899 TKraftQuickHullVertexHashTable=array[0..KRAFT_QUICKHULL_HASHSIZE-1] of TKraftQuickHullVertex;
900
901 TKraftQuickHull=class
902 private
903 fGarbageCollectedClassInstances:TList;
904 fFindIndex:longint;
905 fPointBuffer:TList;
906 fVertexHashTable:TKraftQuickHullVertexHashTable;
907 fVertexPointIndices:TKraftQuickHullIntegerList;
908 fDiscardedFaces:TList;
909 fMinVertices:TKraftQuickHullThreeVertices;
910 fMaxVertices:TKraftQuickHullThreeVertices;
911 fFaces:TList;
912 fHorizon:TList;
913 fNewFaces:TKraftQuickHullFaceList;
914 fUnclaimed:TKraftQuickHullVertexList;
915 fClaimed:TKraftQuickHullVertexList;
916 fCountVertices:longint;
917 fCountFaces:longint;
918 fCountPoints:longint;
919 fExplicitTolerance:double;
920 fTolerance:double;
921 fCharLength:double;
922 public
923 constructor Create;
924 destructor Destroy; override;
925 procedure Reset;
926 procedure AddPoint(const x,y,z:double);
927 procedure AddPointToFace(const AVertex:TKraftQuickHullVertex;const AFace:TKraftQuickHullFace);
928 procedure RemovePointFromFace(const AVertex:TKraftQuickHullVertex;const AFace:TKraftQuickHullFace);
929 function RemoveAllPointsFromFace(const AFace:TKraftQuickHullFace):TKraftQuickHullVertex;
930 function FindHalfEdge(const Tail,Head:TKraftQuickHullVertex):TKraftQuickHullHalfEdge;
931 procedure Triangulate;
932 procedure ComputeMinAndMax;
933 procedure CreateInitialSimplex;
934 function NextPointToAdd:TKraftQuickHullVertex;
935 procedure DeleteFacePoints(Face,AbsorbingFace:TKraftQuickHullFace);
936 procedure CalculateHorizon(const EyePoint:TKraftQuickHullVector3D;Edge0:TKraftQuickHullHalfEdge;const Face:TKraftQuickHullFace;const Horizon:TList);
937 function AddAdjoiningFace(const EyeVertex:TKraftQuickHullVertex;const he:TKraftQuickHullHalfEdge):TKraftQuickHullHalfEdge;
938 procedure AddNewFaces(const NewFaces:TKraftQuickHullFaceList;const EyeVertex:TKraftQuickHullVertex;const Horizon:TList);
939 function OppFaceDistance(he:TKraftQuickHullHalfEdge):double;
940 function DoAdjacentMerge(const Face:TKraftQuickHullFace;const MergeType:longint):boolean;
941 procedure ResolveUnclaimedPoints(NewFaces:TKraftQuickHullFaceList);
942 procedure AddPointToHull(const EyeVertex:TKraftQuickHullVertex);
943 procedure MarkFaceVertices(const Face:TKraftQuickHullFace;const Mark:longint);
944 procedure ReindexFacesAndVertices;
945 procedure Build(const MaximumVertices:longint=-1);
946 procedure GetFaceIndices(out OutputFace:TKraftQuickHullOutputFace;const Face:TKraftQuickHullFace;const Flags:longint);
947 procedure GetVertices(out OutputVertices:TKraftQuickHullVector3DArray);
948 procedure GetFaces(out OutputFaces:TKraftQuickHullOutputFaces);
949 property GarbageCollectedClassInstances:TList read fGarbageCollectedClassInstances write fGarbageCollectedClassInstances;
950 property FindIndex:longint read fFindIndex write fFindIndex;
951 property PointBuffer:TList read fPointBuffer write fPointBuffer;
952 property VertexHashTable:TKraftQuickHullVertexHashTable read fVertexHashTable write fVertexHashTable;
953 property VertexPointIndices:TKraftQuickHullIntegerList read fVertexPointIndices;
954 property DiscardedFaces:TList read fDiscardedFaces;
955 property MinVertices:TKraftQuickHullThreeVertices read fMinVertices write fMinVertices;
956 property MaxVertices:TKraftQuickHullThreeVertices read fMaxVertices write fMaxVertices;
957 property Faces:TList read fFaces;
958 property Horizon:TList read fHorizon;
959 property NewFaces:TKraftQuickHullFaceList read fNewFaces write fNewFaces;
960 property Unclaimed:TKraftQuickHullVertexList read fUnclaimed write fUnclaimed;
961 property Claimed:TKraftQuickHullVertexList read fClaimed write fClaimed;
962 property CountVertices:longint read fCountVertices write fCountVertices;
963 property CountFaces:longint read fCountFaces write fCountFaces;
964 property CountPoints:longint read fCountPoints write fCountPoints;
965 property ExplicitTolerance:double read fExplicitTolerance write fExplicitTolerance;
966 property Tolerance:double read fTolerance write fTolerance;
967 property CharLength:double read fCharLength write fCharLength;
968 end;
969
970 PKraftConvexHullVertex=^TKraftConvexHullVertex;
971 TKraftConvexHullVertex=record
972 Position:TKraftVector3;
973 CountAdjacencies:longint;
974 Adjacencies:array of longint;
975 end;
976
977 PPKraftConvexHullVertices=^TPKraftConvexHullVertices;
978 TPKraftConvexHullVertices=array[0..65535] of TKraftConvexHullVertex;
979
980 TKraftConvexHullVertices=array of TKraftConvexHullVertex;
981
982 PKraftConvexHullFace=^TKraftConvexHullFace;
983 TKraftConvexHullFace=record
984 Plane:TKraftPlane;
985 Vertices:array of longint;
986 CountVertices:longint;
987 EdgeVertexOffset:longint;
988 end;
989
990 TKraftConvexHullFaces=array of TKraftConvexHullFace;
991
992 PKraftConvexHullEdge=^TKraftConvexHullEdge;
993 TKraftConvexHullEdge=record
994 Vertices:array[0..1] of longint;
995 Faces:array[0..1] of longint;
996 end;
997
998 TKraftConvexHullEdges=array of TKraftConvexHullEdge;
999
1000 TKraftConvexHull=class(TPersistent)
1001 private
1002
1003 fPhysics:TKraft;
1004
1005 fPrevious:TKraftConvexHull;
1006 fNext:TKraftConvexHull;
1007
1008 fVertices:TKraftConvexHullVertices;
1009 fCountVertices:longint;
1010
1011 fFaces:TKraftConvexHullFaces;
1012 fCountFaces:longint;
1013
1014 fEdges:TKraftConvexHullEdges;
1015 fCountEdges:longint;
1016
1017 fSphere:TKraftSphere;
1018
1019 fAABB:TKraftAABB;
1020
1021 fAngularMotionDisc:TKraftScalar;
1022
1023 fMassData:TKraftMassData;
1024
1025 fCentroid:TKraftVector3;
1026
1027 procedure CalculateMassData;
1028
1029 public
1030
1031 constructor Create(const APhysics:TKraft);
1032 destructor Destroy; override;
1033
1034 procedure LoadFromStream(const AStream:TStream);
1035 procedure SaveToStream(const AStream:TStream);
1036
1037 function AddVertex(const AVertex:TKraftVector3):longint;
1038
1039 procedure Load(const AVertices:PKraftVector3;const ACountVertices:longint);
1040
1041 procedure Scale(const WithFactor:TKraftScalar); overload;
1042 procedure Scale(const WithVector:TKraftVector3); overload;
1043
1044 procedure Transform(const WithMatrix:TKraftMatrix3x3); overload;
1045 procedure Transform(const WithMatrix:TKraftMatrix4x4); overload;
1046
1047 procedure Build(const AMaximumCountConvexHullPoints:longint=-1;const AUserDefinedTolerance:double=-1.0);
1048
1049 procedure Update;
1050
1051 procedure Finish;
1052
1053 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
1054
1055 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
1056
1057 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
1058
1059 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
1060
1061 property Physics:TKraft read fPhysics;
1062
1063 property Previous:TKraftConvexHull read fPrevious;
1064 property Next:TKraftConvexHull read fNext;
1065
1066 property Vertices:TKraftConvexHullVertices read fVertices;
1067 property CountVertices:longint read fCountVertices;
1068
1069 property Faces:TKraftConvexHullFaces read fFaces;
1070 property CountFaces:longint read fCountFaces;
1071
1072 property Edges:TKraftConvexHullEdges read fEdges;
1073 property CountEdges:longint read fCountEdges;
1074
1075 property Sphere:TKraftSphere read fSphere;
1076
1077 property AABB:TKraftAABB read fAABB;
1078
1079 property AngularMotionDisc:TKraftScalar read fAngularMotionDisc;
1080
1081 property MassData:TKraftMassData read fMassData;
1082
1083 property Centroid:TKraftVector3 read fCentroid;
1084
1085 end;
1086
1087 PKraftMeshTriangle=^TKraftMeshTriangle;
1088 TKraftMeshTriangle=record
1089 Next:longint;
1090 Vertices:array[0..2] of longint;
1091 Normals:array[0..2] of longint;
1092 Plane:TKraftPlane;
1093 AABB:TKraftAABB;
1094 end;
1095
1096 TKraftMeshTriangles=array of TKraftMeshTriangle;
1097
1098 PKraftMeshNode=^TKraftMeshNode;
1099 TKraftMeshNode=record
1100 Children:array[0..1] of longint;
1101 TriangleIndex:longint;
1102 AABB:TKraftAABB;
1103 end;
1104
1105 TKraftMeshNodes=array of TKraftMeshNode;
1106
1107 PKraftMeshSkipListNode=^TKraftMeshSkipListNode;
1108 TKraftMeshSkipListNode=record
1109 SkipToNodeIndex:longint;
1110 TriangleIndex:longint;
1111 AABB:TKraftAABB;
1112 end;
1113
1114 TKraftMeshSkipListNodes=array of TKraftMeshSkipListNode;
1115
1116 TKraftMesh=class(TPersistent)
1117 private
1118
1119 fPhysics:TKraft;
1120
1121 fPrevious:TKraftMesh;
1122 fNext:TKraftMesh;
1123
1124 fVertices:TKraftVector3Array;
1125 fCountVertices:longint;
1126
1127 fNormals:TKraftVector3Array;
1128 fCountNormals:longint;
1129
1130 fTriangles:TKraftMeshTriangles;
1131 fCountTriangles:longint;
1132
1133 fNodes:TKraftMeshNodes;
1134 fCountNodes:longint;
1135
1136 fSkipListNodes:TKraftMeshSkipListNodes;
1137 fCountSkipListNodes:longint;
1138
1139 fAABB:TKraftAABB;
1140
1141 fDoubleSided:boolean;
1142
1143 procedure CalculateNormals;
1144
1145 public
1146
1147 constructor Create(const APhysics:TKraft);
1148 destructor Destroy; override;
1149
1150 function AddVertex(const AVertex:TKraftVector3):longint;
1151
1152 function AddNormal(const ANormal:TKraftVector3):longint;
1153
1154 function AddTriangle(const AVertexIndex0,AVertexIndex1,AVertexIndex2:longint;const ANormalIndex0:longint=-1;const ANormalIndex1:longint=-1;ANormalIndex2:longint=-1):longint;
1155
1156 procedure Load(const AVertices:PKraftVector3;const ACountVertices:longint;const ANormals:PKraftVector3;const ACountNormals:longint;const AVertexIndices,ANormalIndices:pointer;const ACountIndices:longint); overload;
1157 procedure Load(const ASourceData:pointer;const ASourceSize:longint); overload;
1158
1159 procedure Scale(const WithFactor:TKraftScalar); overload;
1160 procedure Scale(const WithVector:TKraftVector3); overload;
1161
1162 procedure Transform(const WithMatrix:TKraftMatrix3x3); overload;
1163 procedure Transform(const WithMatrix:TKraftMatrix4x4); overload;
1164
1165 procedure Finish;
1166
1167 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
1168
1169 property Physics:TKraft read fPhysics;
1170
1171 property Previous:TKraftMesh read fPrevious;
1172 property Next:TKraftMesh read fNext;
1173
1174 property Vertices:TKraftVector3Array read fVertices;
1175 property CountVertices:longint read fCountVertices;
1176
1177 property Normals:TKraftVector3Array read fNormals;
1178 property CountNormals:longint read fCountNormals;
1179
1180 property Triangles:TKraftMeshTriangles read fTriangles;
1181 property CountTriangles:longint read fCountTriangles;
1182
1183 property Nodes:TKraftMeshNodes read fNodes;
1184 property CountNodes:longint read fCountNodes;
1185
1186 property SkipListNodes:TKraftMeshSkipListNodes read fSkipListNodes;
1187 property CountSkipListNodes:longint read fCountSkipListNodes;
1188
1189 property AABB:TKraftAABB read fAABB;
1190
1191 published
1192
1193 property DoubleSided:boolean read fDoubleSided write fDoubleSided;
1194
1195 end;
1196
1197 PKraftContactPair=^TKraftContactPair;
1198
1199 TKraftShapeOnContactBeginHook=procedure(const ContactPair:PKraftContactPair;const WithShape:TKraftShape) of object;
1200 TKraftShapeOnContactEndHook=procedure(const ContactPair:PKraftContactPair;const WithShape:TKraftShape) of object;
1201 TKraftShapeOnContactStayHook=procedure(const ContactPair:PKraftContactPair;const WithShape:TKraftShape) of object;
1202
1203 TKraftShape=class(TPersistent)
1204 private
1205
1206 fPhysics:TKraft;
1207
1208 fRigidBody:TKraftRigidBody;
1209
1210 fShapeType:TKraftShapeType;
1211
1212 fShapePrevious:TKraftShape;
1213 fShapeNext:TKraftShape;
1214
1215 fFlags:TKraftShapeFlags;
1216
1217 fFriction:TKraftScalar;
1218
1219 fRestitution:TKraftScalar;
1220
1221 fDensity:TKraftScalar;
1222
1223 fUserData:pointer;
1224
1225 fStaticAABBTreeProxy:longint;
1226 fSleepingAABBTreeProxy:longint;
1227 fDynamicAABBTreeProxy:longint;
1228 fKinematicAABBTreeProxy:longint;
1229
1230 fShapeAABB:TKraftAABB;
1231
1232 fShapeSphere:TKraftSphere;
1233
1234 fWorldAABB:TKraftAABB;
1235
1236 fLocalTransform:TKraftMatrix4x4;
1237
1238 fLocalCenterOfMass:TKraftVector3;
1239
1240 fLocalCentroid:TKraftVector3;
1241
1242 fWorldTransform:TKraftMatrix4x4;
1243
1244 fLastWorldTransform:TKraftMatrix4x4;
1245
1246 fInterpolatedWorldTransform:TKraftMatrix4x4;
1247
1248 fMassData:TKraftMassData;
1249
1250 fAngularMotionDisc:TKraftScalar;
1251
1252 fFeatureRadius:TKraftScalar;
1253
1254 fContinuousMinimumRadiusScaleFactor:TKraftScalar;
1255
1256 fOnContactBegin:TKraftShapeOnContactBeginHook;
1257 fOnContactEnd:TKraftShapeOnContactEndHook;
1258 fOnContactStay:TKraftShapeOnContactStayHook;
1259
1260 {$ifdef DebugDraw}
1261 fDrawDisplayList:glUint;
1262 {$endif}
1263
1264 fIsMesh:boolean;
1265
1266 function GetProxyFatWorldAABB:PKraftAABB;
1267
1268 public
1269
1270 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody);
1271 destructor Destroy; override;
1272
1273 procedure UpdateShapeAABB; virtual;
1274
1275 procedure CalculateMassData; virtual;
1276
1277 procedure SynchronizeTransform; virtual;
1278
1279 procedure SynchronizeProxies; virtual;
1280
1281 procedure Finish; virtual;
1282
1283 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; virtual;
1284
1285 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; virtual;
1286
1287 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; virtual;
1288
1289 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; virtual;
1290
1291 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; virtual;
1292
1293 function TestPoint(const p:TKraftVector3):boolean; virtual;
1294
1295 function RayCast(var RayCastData:TKraftRaycastData):boolean; virtual;
1296
1297 procedure StoreWorldTransform; virtual;
1298
1299 procedure InterpolateWorldTransform(const Alpha:TKraftScalar); virtual;
1300
1301 {$ifdef DebugDraw}
1302 procedure Draw(const CameraMatrix:TKraftMatrix4x4); virtual;
1303 {$endif}
1304
1305 property Physics:TKraft read fPhysics;
1306
1307 property RigidBody:TKraftRigidBody read fRigidBody;
1308
1309 property ShapeType:TKraftShapeType read fShapeType;
1310
1311 property ShapePrevious:TKraftShape read fShapePrevious;
1312 property ShapeNext:TKraftShape read fShapeNext;
1313
1314 property UserData:pointer read fUserData write fUserData;
1315
1316 property StaticAABBTreeProxy:longint read fStaticAABBTreeProxy write fStaticAABBTreeProxy;
1317 property SleepingAABBTreeProxy:longint read fSleepingAABBTreeProxy write fSleepingAABBTreeProxy;
1318 property DynamicAABBTreeProxy:longint read fDynamicAABBTreeProxy write fDynamicAABBTreeProxy;
1319 property KinematicAABBTreeProxy:longint read fKinematicAABBTreeProxy write fKinematicAABBTreeProxy;
1320
1321 property ShapeAABB:TKraftAABB read fShapeAABB;
1322
1323 property ShapeSphere:TKraftSphere read fShapeSphere;
1324
1325 property WorldAABB:TKraftAABB read fWorldAABB;
1326
1327 property ProxyFatWorldAABB:PKraftAABB read GetProxyFatWorldAABB;
1328
1329 property LocalTransform:TKraftMatrix4x4 read fLocalTransform write fLocalTransform;
1330
1331 property LocalCenterOfMass:TKraftVector3 read fLocalCenterOfMass write fLocalCenterOfMass;
1332
1333 property LocalCentroid:TKraftVector3 read fLocalCentroid write fLocalCentroid;
1334
1335 property WorldTransform:TKraftMatrix4x4 read fWorldTransform write fWorldTransform;
1336
1337 property LastWorldTransform:TKraftMatrix4x4 read fLastWorldTransform write fLastWorldTransform;
1338
1339 property InterpolatedWorldTransform:TKraftMatrix4x4 read fInterpolatedWorldTransform write fInterpolatedWorldTransform;
1340
1341 property MassData:TKraftMassData read fMassData write fMassData;
1342
1343 property AngularMotionDisc:TKraftScalar read fAngularMotionDisc write fAngularMotionDisc;
1344
1345 property FeatureRadius:TKraftScalar read fFeatureRadius write fFeatureRadius;
1346
1347 property ContinuousMinimumRadiusScaleFactor:TKraftScalar read fContinuousMinimumRadiusScaleFactor write fContinuousMinimumRadiusScaleFactor;
1348
1349 {$ifdef DebugDraw}
1350 property DrawDisplayList:glUint read fDrawDisplayList write fDrawDisplayList;
1351 {$endif}
1352
1353 property IsMesh:boolean read fIsMesh write fIsMesh;
1354
1355 published
1356
1357 property Flags:TKraftShapeFlags read fFlags write fFlags;
1358
1359 property Friction:TKraftScalar read fFriction write fFriction;
1360
1361 property Restitution:TKraftScalar read fRestitution write fRestitution;
1362
1363 property Density:TKraftScalar read fDensity write fDensity;
1364
1365 property OnContactBegin:TKraftShapeOnContactBeginHook read fOnContactBegin write fOnContactBegin;
1366 property OnContactEnd:TKraftShapeOnContactEndHook read fOnContactEnd write fOnContactEnd;
1367 property OnContactStay:TKraftShapeOnContactStayHook read fOnContactStay write fOnContactStay;
1368
1369 end;
1370
1371 TKraftShapes=array of TKraftShape;
1372
1373 TKraftShapeSphere=class(TKraftShape)
1374 private
1375 fRadius:TKraftScalar;
1376 public
1377 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const ARadius:TKraftScalar); reintroduce;
1378 destructor Destroy; override;
1379 procedure UpdateShapeAABB; override;
1380 procedure CalculateMassData; override;
1381 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
1382 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
1383 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
1384 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
1385 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
1386 function TestPoint(const p:TKraftVector3):boolean; override;
1387 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
1388 {$ifdef DebugDraw}
1389 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
1390 {$endif}
1391 property Radius:TKraftScalar read fRadius;
1392 end;
1393
1394 TKraftShapeCapsule=class(TKraftShape)
1395 private
1396 fRadius:TKraftScalar;
1397 fHeight:TKraftScalar;
1398 public
1399 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const ARadius,AHeight:TKraftScalar); reintroduce;
1400 destructor Destroy; override;
1401 procedure UpdateShapeAABB; override;
1402 procedure CalculateMassData; override;
1403 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
1404 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
1405 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
1406 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
1407 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
1408 function TestPoint(const p:TKraftVector3):boolean; override;
1409 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
1410 {$ifdef DebugDraw}
1411 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
1412 {$endif}
1413 property Radius:TKraftScalar read fRadius;
1414 property Height:TKraftScalar read fHeight;
1415 end;
1416
1417 TKraftShapeConvexHull=class(TKraftShape)
1418 private
1419 fConvexHull:TKraftConvexHull;
1420 public
1421 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AConvexHull:TKraftConvexHull); reintroduce; overload;
1422 destructor Destroy; override;
1423 procedure UpdateShapeAABB; override;
1424 procedure CalculateMassData; override;
1425 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
1426 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
1427 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
1428 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
1429 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
1430 function TestPoint(const p:TKraftVector3):boolean; override;
1431 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
1432 {$ifdef DebugDraw}
1433 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
1434 {$endif}
1435 property ConvexHull:TKraftConvexHull read fConvexHull;
1436 end;
1437
1438 TKraftShapeBox=class(TKraftShapeConvexHull)
1439 private
1440 fShapeConvexHull:TKraftConvexHull;
1441 fExtents:TKraftVector3;
1442 public
1443 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AExtents:TKraftVector3); reintroduce;
1444 destructor Destroy; override;
1445 procedure UpdateShapeAABB; override;
1446 procedure CalculateMassData; override;
1447 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
1448 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
1449 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
1450 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
1451 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
1452 function TestPoint(const p:TKraftVector3):boolean; override;
1453 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
1454 {$ifdef DebugDraw}
1455 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
1456 {$endif}
1457 property Extents:TKraftVector3 read fExtents;
1458 end;
1459
1460 TKraftShapePlane=class(TKraftShapeConvexHull)
1461 private
1462 fShapeConvexHull:TKraftConvexHull;
1463 fPlaneVertices:array[0..3] of TKraftVector3;
1464 fPlaneCenter:TKraftVector3;
1465 fPlane:TKraftPlane;
1466 public
1467 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const APlane:TKraftPlane); reintroduce;
1468 destructor Destroy; override;
1469 procedure UpdateShapeAABB; override;
1470 procedure CalculateMassData; override;
1471 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
1472 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
1473 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
1474 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
1475 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
1476 function TestPoint(const p:TKraftVector3):boolean; override;
1477 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
1478 {$ifdef DebugDraw}
1479 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
1480 {$endif}
1481 property Plane:TKraftPlane read fPlane;
1482 end;
1483
1484 TKraftShapeMesh=class(TKraftShape)
1485 private
1486 fMesh:TKraftMesh;
1487 public
1488 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AMesh:TKraftMesh); reintroduce;
1489 destructor Destroy; override;
1490 procedure UpdateShapeAABB; override;
1491 procedure CalculateMassData; override;
1492 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
1493 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
1494 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
1495 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
1496 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
1497 function TestPoint(const p:TKraftVector3):boolean; override;
1498 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
1499 {$ifdef DebugDraw}
1500 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
1501 {$endif}
1502 property Mesh:TKraftMesh read fMesh;
1503 end;
1504
1505 PKraftGJKStateShapes=^TKraftGJKStateShapes;
1506 TKraftGJKStateShapes=array[0..1] of TKraftShape;
1507
1508 PKraftGJKStateTransforms=^TKraftGJKStateTransforms;
1509 TKraftGJKStateTransforms=array[0..1] of PKraftMatrix4x4;
1510
1511 PKraftGJKSimplexVertex=^TKraftGJKSimplexVertex;
1512 TKraftGJKSimplexVertex=record
1513 sA:TKraftVector3;
1514 sB:TKraftVector3;
1515 w:TKraftVector3;
1516 a:TKraftScalar;
1517 iA:longint;
1518 iB:longint;
1519 Dummy:longint;
1520 end;
1521
1522 PKraftGJKSimplexVertices=^TKraftGJKSimplexVertices;
1523 TKraftGJKSimplexVertices=array[0..3] of TKraftGJKSimplexVertex;
1524
1525 PPKraftGJKSimplexVertices=^PKraftGJKSimplexVertices;
1526 TPKraftGJKSimplexVertices=array[0..3] of PKraftGJKSimplexVertex;
1527
1528 PKraftGJKCachedSimplexVertex=^TKraftGJKCachedSimplexVertex;
1529 TKraftGJKCachedSimplexVertex=record
1530 a:TKraftScalar;
1531 iA:longint;
1532 iB:longint;
1533 Dummy:longint;
1534 end;
1535
1536 PKraftGJKCachedSimplexVertices=^TKraftGJKCachedSimplexVertices;
1537 TKraftGJKCachedSimplexVertices=array[0..3] of TKraftGJKCachedSimplexVertex;
1538
1539 PKraftGJKCachedSimplex=^TKraftGJKCachedSimplex;
1540 TKraftGJKCachedSimplex=record
1541 Vertices:TKraftGJKCachedSimplexVertices;
1542 Count:longint;
1543 Metric:TKraftScalar;
1544 end;
1545
1546 PKraftGJKSimplex=^TKraftGJKSimplex;
1547 TKraftGJKSimplex=record
1548 VerticesData:TKraftGJKSimplexVertices;
1549 Vertices:TPKraftGJKSimplexVertices;
1550 Divisor:TKraftScalar;
1551 Count:longint;
1552 end;
1553
1554 PKraftGJKClosestPoints=^TKraftGJKClosestPoints;
1555 TKraftGJKClosestPoints=array[0..1] of TKraftVector3;
1556
1557 PKraftGJK=^TKraftGJK;
1558 TKraftGJK={$ifdef FPC}object{$else}record{$endif}
1559 public
1560 Distance:TKraftScalar;
1561 Iterations:longint;
1562 UseRadii:boolean;
1563 Failed:boolean;
1564 Normal:TKraftVector3;
1565 ClosestPoints:TKraftGJKClosestPoints;
1566 Simplex:TKraftGJKSimplex;
1567 CachedSimplex:PKraftGJKCachedSimplex;
1568 Shapes:TKraftGJKStateShapes;
1569 Transforms:TKraftGJKStateTransforms;
1570 function Run:boolean;
1571 end;
1572
1573 PKraftContact=^TKraftContact;
1574 TKraftContact=record
1575 LocalPoints:array[0..1] of TKraftVector3;
1576 Penetration:TKraftScalar; // Only needed for contact reduction
1577 NormalImpulse:TKraftScalar;
1578 TangentImpulse:array[0..1] of TKraftScalar;
1579 Bias:TKraftScalar;
1580 NormalMass:TKraftScalar;
1581 TangentMass:array[0..1] of TKraftScalar;
1582 FeatureID:TKraftContactFeatureID;
1583 WarmStartState:longword;
1584 end;
1585
1586 PKraftContacts=^TKraftContacts;
1587 TKraftContacts=array[0..65536] of TKraftContact;
1588
1589 PKraftContactFaceQuery=^TKraftContactFaceQuery;
1590 TKraftContactFaceQuery=record
1591 Index:longint;
1592 Separation:TKraftScalar;
1593 end;
1594
1595 PKraftContactEdgeQuery=^TKraftContactEdgeQuery;
1596 TKraftContactEdgeQuery=record
1597 IndexA:longint;
1598 IndexB:longint;
1599 Separation:TKraftScalar;
1600 Normal:TKraftVector3;
1601 end;
1602
1603 PKraftSolverContact=^TKraftSolverContact;
1604 TKraftSolverContact=record
1605 Separation:TKraftScalar;
1606 Point:TKraftVector3;
1607 end;
1608
1609 PKraftSolverContactManifold=^TKraftSolverContactManifold;
1610 TKraftSolverContactManifold=record
1611 CountContacts:longint;
1612 Contacts:array[0..MAX_CONTACTS-1] of TKraftSolverContact;
1613 Points:array[0..1] of TKraftVector3;
1614 Normal:TKraftVector3;
1615 end;
1616
1617 PKraftContactManifoldType=^TKraftContactManifoldType;
1618 TKraftContactManifoldType=(kcmtUnknown,
1619 kcmtImplicit,
1620 kcmtFaceA,
1621 kcmtFaceB,
1622 kcmtEdges,
1623 kcmtImplicitEdge,
1624 kcmtImplicitNormal,
1625 kcmtPersistentImplicit,
1626 kcmtSpeculative);
1627
1628 PKraftContactManifold=^TKraftContactManifold;
1629 TKraftContactManifold=record
1630 ContactManifoldType:TKraftContactManifoldType;
1631 HaveData:boolean;
1632 Persistent:boolean;
1633 CountContacts:longint;
1634 LostSpeculativeBounce:single;
1635 LocalRadius:array[0..1] of TKraftScalar;
1636 LocalNormal:TKraftVector3;
1637 TangentVectors:array[0..1] of TKraftVector3;
1638 Contacts:array[0..MAX_CONTACTS-1] of TKraftContact;
1639 RelativeTransform:TKraftMatrix4x4;
1640 FaceQueryAB:TKraftContactFaceQuery;
1641 FaceQueryBA:TKraftContactFaceQuery;
1642 EdgeQuery:TKraftContactEdgeQuery;
1643 GJKCachedSimplex:TKraftGJKCachedSimplex;
1644 end;
1645
1646 PKraftContactPairEdge=^TKraftContactPairEdge;
1647 TKraftContactPairEdge=record
1648 Previous:PKraftContactPairEdge;
1649 Next:PKraftContactPairEdge;
1650 OtherRigidBody:TKraftRigidBody;
1651 ContactPair:PKraftContactPair;
1652 end;
1653
1654 TKraftMeshContactPair=class;
1655
1656 PKraftContactPairContactManifoldMode=^TKraftContactPairContactManifoldMode;
1657 TKraftContactPairContactManifoldMode=(kcpcmmVelocitySolver,kcpcmmPositionSolver,kcpcmmBaumgarte,kcpcmmTemporalCoherence);
1658
1659 TKraftContactPair={$ifdef FPC}object{$else}record{$endif}
1660 public
1661 Previous:PKraftContactPair;
1662 Next:PKraftContactPair;
1663 HashBucket:longint;
1664 HashPrevious:PKraftContactPair;
1665 HashNext:PKraftContactPair;
1666 Island:TKraftIsland;
1667 Shapes:array[0..1] of TKraftShape;
1668 ElementIndex:longint;
1669 MeshContactPair:TKraftMeshContactPair;
1670 RigidBodies:array[0..1] of TKraftRigidBody;
1671 Edges:array[0..1] of TKraftContactPairEdge;
1672 Friction:TKraftScalar;
1673 Restitution:TKraftScalar;
1674 Manifold:TKraftContactManifold;
1675 Flags:TKraftContactFlags;
1676 TimeOfImpactCount:longint;
1677 TimeOfImpact:TKraftScalar;
1678 procedure GetSolverContactManifold(out SolverContactManifold:TKraftSolverContactManifold;const WorldTransformA,WorldTransformB:TKraftMatrix4x4;const ContactManifoldMode:TKraftContactPairContactManifoldMode);
1679 procedure DetectCollisions(const ContactManager:TKraftContactManager;const TriangleShape:TKraftShape=nil;const ThreadIndex:longint=0;const SpeculativeContacts:boolean=true;const DeltaTime:double=0.0);
1680 end;
1681
1682 TPKraftContactPairs=array of PKraftContactPair;
1683
1684 TKraftContactManagerOnContactBeginHook=procedure(const ContactPair:PKraftContactPair) of object;
1685 TKraftContactManagerOnContactEndHook=procedure(const ContactPair:PKraftContactPair) of object;
1686 TKraftContactManagerOnContactStayHook=procedure(const ContactPair:PKraftContactPair) of object;
1687
1688 PKraftContactIndices=^TKraftContactIndices;
1689 TKraftContactIndices=array[0..MAX_CONTACTS-1] of longint;
1690
1691 TKraftMeshContactPair=class
1692 private
1693
1694 fContactManager:TKraftContactManager;
1695
1696 fPrevious:TKraftMeshContactPair;
1697 fNext:TKraftMeshContactPair;
1698
1699 fHashBucket:longint;
1700 fHashPrevious:TKraftMeshContactPair;
1701 fHashNext:TKraftMeshContactPair;
1702
1703 fIsOnFreeList:boolean;
1704
1705 fFlags:TKraftContactFlags;
1706
1707 fShapeConvex:TKraftShape;
1708 fShapeMesh:TKraftShape;
1709
1710 fRigidBodyConvex:TKraftRigidBody;
1711 fRigidBodyMesh:TKraftRigidBody;
1712
1713 fConvexAABBInMeshLocalSpace:TKraftAABB;
1714
1715 public
1716
1717 constructor Create(const AContactManager:TKraftContactManager);
1718 destructor Destroy; override;
1719 procedure AddToHashTable; {$ifdef caninline}inline;{$endif}
1720 procedure RemoveFromHashTable; {$ifdef caninline}inline;{$endif}
1721 procedure MoveToFreeList;
1722 procedure MoveFromFreeList;
1723 procedure Query;
1724 procedure Update;
1725
1726 end;
1727
1728 PKraftMeshContactPairHashTableBucket=^TKraftMeshContactPairHashTableBucket;
1729 TKraftMeshContactPairHashTableBucket=record
1730 First:TKraftMeshContactPair;
1731 Last:TKraftMeshContactPair;
1732 end;
1733
1734 TKraftMeshContactPairHashTable=array[0..(1 shl 16)-1] of TKraftMeshContactPairHashTableBucket;
1735
1736 PKraftContactPairHashTableBucket=^TKraftContactPairHashTableBucket;
1737 TKraftContactPairHashTableBucket=record
1738 First:PKraftContactPair;
1739 Last:PKraftContactPair;
1740 end;
1741
1742 TKraftContactPairHashTable=array[0..(1 shl 16)-1] of TKraftContactPairHashTableBucket;
1743
1744 TKraftContactManagerOnCanCollide=function(const AShapeA,AShapeB:TKraftShape):boolean of object;
1745
1746 PKraftContactManagerMeshTriangleContactQueueItem=^TKraftContactManagerMeshTriangleContactQueueItem;
1747 TKraftContactManagerMeshTriangleContactQueueItem=record
1748 MeshContactPair:TKraftMeshContactPair;
1749 TriangleIndex:longint;
1750 end;
1751
1752 TKraftContactManagerMeshTriangleContactQueueItems=array of TKraftContactManagerMeshTriangleContactQueueItem;
1753
1754 TKraftContactManager=class
1755 private
1756
1757 fPhysics:TKraft;
1758
1759 fContactPairFirst:PKraftContactPair;
1760 fContactPairLast:PKraftContactPair;
1761
1762 fFreeContactPairs:PKraftContactPair;
1763
1764 fCountContactPairs:longint;
1765
1766 fMeshContactPairFirst:TKraftMeshContactPair;
1767 fMeshContactPairLast:TKraftMeshContactPair;
1768
1769 fMeshContactPairFirstFree:TKraftMeshContactPair;
1770 fMeshContactPairLastFree:TKraftMeshContactPair;
1771
1772 fCountMeshContactPairs:longint;
1773
1774 fOnContactBegin:TKraftContactManagerOnContactBeginHook;
1775 fOnContactEnd:TKraftContactManagerOnContactEndHook;
1776 fOnContactStay:TKraftContactManagerOnContactStayHook;
1777
1778 fOnCanCollide:TKraftContactManagerOnCanCollide;
1779
1780 fClipVertexLists:array[0..MAX_THREADS-1,0..1] of TKraftClipVertexList;
1781
1782 {$ifdef DebugDraw}
1783 fDebugClipVertexLists:array[0..255] of TKraftClipVertexList;
1784 fCountDebugClipVertexLists:longint;
1785 {$endif}
1786
1787 fTemporaryContacts:array[0..MAX_THREADS-1,0..MAX_TEMPORARY_CONTACTS-1] of TKraftContact;
1788 fCountTemporaryContacts:array[0..MAX_THREADS-1] of longint;
1789
1790 fActiveContactPairs:array of PKraftContactPair;
1791 fCountActiveContactPairs:longint;
1792 fCountRemainActiveContactPairsToDo:longint;
1793
1794 fConvexConvexContactPairHashTable:TKraftContactPairHashTable;
1795
1796 fConvexMeshTriangleContactPairHashTable:TKraftContactPairHashTable;
1797
1798 fMeshContactPairHashTable:TKraftMeshContactPairHashTable;
1799
1800 public
1801
1802 constructor Create(const APhysics:TKraft);
1803 destructor Destroy; override;
1804
1805 function HasDuplicateContact(const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AShapeA,AShapeB:TKraftShape;const AElementIndex:longint=-1):boolean;
1806
1807 procedure AddConvexContact(const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AShapeA,AShapeB:TKraftShape;const AElementIndex:longint=-1;const AMeshContactPair:TKraftMeshContactPair=nil);
1808
1809 procedure AddMeshContact(const ARigidBodyConvex,ARigidBodyMesh:TKraftRigidBody;const AShapeConvex,AShapeMesh:TKraftShape);
1810
1811 procedure AddContact(const AShapeA,AShapeB:TKraftShape);
1812
1813 procedure RemoveContact(AContactPair:PKraftContactPair);
1814
1815 procedure RemoveMeshContact(AMeshContactPair:TKraftMeshContactPair);
1816
1817 procedure RemoveContactsFromRigidBody(ARigidBody:TKraftRigidBody);
1818
1819 procedure DoBroadPhase;
1820
1821 procedure DoMidPhase;
1822
1823 procedure ProcessContactPair(const ContactPair:PKraftContactPair;const ThreadIndex:longint=0);
1824
1825 {$ifdef KraftPasMP}
1826 procedure ProcessContactPairParallelForFunction(const Job:PPasMPJob;const ThreadIndex:longint;const Data:pointer;const FromIndex,ToIndex:TPasMPNativeInt);
1827 {$else}
1828 procedure ProcessContactPairJob(const JobIndex,ThreadIndex:longint);
1829 {$endif}
1830
1831 procedure DoNarrowPhase;
1832
1833 {$ifdef DebugDraw}
1834 procedure DebugDraw(const CameraMatrix:TKraftMatrix4x4);
1835 {$endif}
1836
1837 function ReduceContacts(const AInputContacts:PKraftContacts;const ACountInputContacts:longint;const AOutputContacts:PKraftContacts):longint;
1838
1839 function GetMaximizedAreaReducedContactIndices(const AInputContactPositions:PPKraftVector3s;const ACountInputContactPositions:longint;var AOutputContactIndices:TKraftContactIndices):longint;
1840
1841 property ContactPairFirst:PKraftContactPair read fContactPairFirst write fContactPairFirst;
1842 property ContactPairLast:PKraftContactPair read fContactPairLast write fContactPairLast;
1843
1844 property FreeContactPairs:PKraftContactPair read fFreeContactPairs write fFreeContactPairs;
1845
1846 property Physics:TKraft read fPhysics;
1847
1848 property CountContactPairs:longint read fCountContactPairs;
1849
1850 property MeshContactPairFirst:TKraftMeshContactPair read fMeshContactPairFirst;
1851 property MeshContactPairLast:TKraftMeshContactPair read fMeshContactPairLast;
1852
1853 property MeshContactPairFirstFree:TKraftMeshContactPair read fMeshContactPairFirstFree;
1854 property MeshContactPairLastFree:TKraftMeshContactPair read fMeshContactPairLastFree;
1855
1856 property CountMeshContactPairs:longint read fCountMeshContactPairs;
1857
1858 published
1859
1860 property OnContactBegin:TKraftContactManagerOnContactBeginHook read fOnContactBegin write fOnContactBegin;
1861 property OnContactEnd:TKraftContactManagerOnContactEndHook read fOnContactEnd write fOnContactEnd;
1862 property OnContactStay:TKraftContactManagerOnContactStayHook read fOnContactStay write fOnContactStay;
1863
1864 property OnCanCollide:TKraftContactManagerOnCanCollide read fOnCanCollide write fOnCanCollide;
1865
1866 end;
1867
1868 PKraftBroadPhaseContactPair=^TKraftBroadPhaseContactPair;
1869 TKraftBroadPhaseContactPair=array[0..1] of TKraftShape;
1870
1871 TKraftBroadPhaseContactPairs=array of TKraftBroadPhaseContactPair;
1872
1873 TKraftBroadPhase=class
1874 private
1875
1876 fPhysics:TKraft;
1877
1878 fStack:array[0..MAX_THREADS-1] of PKraftDynamicAABBTreeLongintArray;
1879 fStackCapacity:array[0..MAX_THREADS-1] of longint;
1880
1881 fContactPairs:array[0..MAX_THREADS-1] of TKraftBroadPhaseContactPairs;
1882 fCountContactPairs:array[0..MAX_THREADS-1] of longint;
1883
1884 fStaticMoveBuffer:array of longint;
1885 fStaticMoveBufferSize:longint;
1886
1887 fDynamicMoveBuffer:array of longint;
1888 fDynamicMoveBufferSize:longint;
1889
1890 fKinematicMoveBuffer:array of longint;
1891 fKinematicMoveBufferSize:longint;
1892
1893 fAllMoveBufferSize:longint;
1894
1895 procedure AddPair(const ThreadIndex:longint;ShapeA,ShapeB:TKraftShape); {$ifdef caninline}inline;{$endif}
1896
1897 procedure QueryShapeWithTree(const ThreadIndex:longint;const Shape:TKraftShape;const AABBTree:TKraftDynamicAABBTree);
1898
1899 {$ifdef KraftPasMP}
1900 procedure ProcessMoveBufferItemParallelForFunction(const Job:PPasMPJob;const ThreadIndex:longint;const Data:pointer;const FromIndex,ToIndex:TPasMPNativeInt);
1901 {$else}
1902 procedure ProcessMoveBufferItem(const JobIndex,ThreadIndex:longint);
1903 {$endif}
1904
1905
1906 public
1907
1908 constructor Create(const APhysics:TKraft);
1909 destructor Destroy; override;
1910
1911 procedure UpdatePairs; {$ifdef caninline}inline;{$endif}
1912
1913 procedure StaticBufferMove(ProxyID:longint); {$ifdef caninline}inline;{$endif}
1914 procedure StaticBufferClearMove(ProxyID:longint); {$ifdef caninline}inline;{$endif}
1915 procedure DynamicBufferMove(ProxyID:longint); {$ifdef caninline}inline;{$endif}
1916 procedure DynamicBufferClearMove(ProxyID:longint); {$ifdef caninline}inline;{$endif}
1917 procedure KinematicBufferMove(ProxyID:longint); {$ifdef caninline}inline;{$endif}
1918 procedure KinematicBufferClearMove(ProxyID:longint); {$ifdef caninline}inline;{$endif}
1919
1920 end;
1921
1922 TKraftRigidBodyOnDamping=procedure(const RigidBody:TKraftRigidBody;const TimeStep:TKraftTimeStep) of object;
1923
1924 TKraftRigidBodyOnStep=procedure(const RigidBody:TKraftRigidBody;const TimeStep:TKraftTimeStep) of object;
1925
1926 TKraftConstraint=class;
1927
1928 PKraftConstraintEdge=^TKraftConstraintEdge;
1929 TKraftConstraintEdge=record
1930 Previous:PKraftConstraintEdge;
1931 Next:PKraftConstraintEdge;
1932 Constraint:TKraftConstraint;
1933 OtherRigidBody:TKraftRigidBody;
1934 end;
1935
1936 TKraftRigidBodyIslandIndices=array of longint;
1937
1938 TKraftRigidBody=class(TPersistent)
1939 private
1940
1941 fPhysics:TKraft;
1942
1943 fIsland:TKraftIsland;
1944
1945 fIslandIndices:TKraftRigidBodyIslandIndices;
1946
1947 fID:uint64;
1948
1949 fRigidBodyType:TKraftRigidBodyType;
1950
1951 fRigidBodyPrevious:TKraftRigidBody;
1952 fRigidBodyNext:TKraftRigidBody;
1953
1954 fStaticRigidBodyIsOnList:boolean;
1955 fStaticRigidBodyPrevious:TKraftRigidBody;
1956 fStaticRigidBodyNext:TKraftRigidBody;
1957
1958 fDynamicRigidBodyIsOnList:boolean;
1959 fDynamicRigidBodyPrevious:TKraftRigidBody;
1960 fDynamicRigidBodyNext:TKraftRigidBody;
1961
1962 fKinematicRigidBodyIsOnList:boolean;
1963 fKinematicRigidBodyPrevious:TKraftRigidBody;
1964 fKinematicRigidBodyNext:TKraftRigidBody;
1965
1966 fShapeFirst:TKraftShape;
1967 fShapeLast:TKraftShape;
1968
1969 fShapeCount:longint;
1970
1971 fFlags:TKraftRigidBodyFlags;
1972
1973 fWorldDisplacement:TKraftVector3;
1974
1975 fWorldTransform:TKraftMatrix4x4;
1976
1977 fSweep:TKraftSweep;
1978
1979 fGravity:TKraftVector3;
1980
1981 fGravityProperty:TKraftVector3Property;
1982
1983 fLinearFactor:TKraftVector3;
1984
1985 fUserData:pointer;
1986
1987 fTimeOfImpact:TKraftScalar;
1988
1989 fNextOnIslandBuildStack:TKraftRigidBody;
1990 fNextStaticRigidBody:TKraftRigidBody;
1991
1992 fBodyInertiaTensor:TKraftMatrix3x3;
1993 fBodyInverseInertiaTensor:TKraftMatrix3x3;
1994
1995 fWorldInertiaTensor:TKraftMatrix3x3;
1996 fWorldInverseInertiaTensor:TKraftMatrix3x3;
1997
1998 fForcedMass:TKraftScalar;
1999
2000 fMass:TKraftScalar;
2001 fInverseMass:TKraftScalar;
2002
2003 fLinearVelocity:TKraftVector3;
2004 fAngularVelocity:TKraftVector3;
2005
2006 fMaximalLinearVelocity:TKraftScalar;
2007 fMaximalAngularVelocity:TKraftScalar;
2008
2009 fLinearVelocityDamp:TKraftScalar;
2010 fAngularVelocityDamp:TKraftScalar;
2011 fAdditionalDamping:boolean;
2012 fAdditionalDamp:TKraftScalar;
2013 fLinearVelocityAdditionalDamp:TKraftScalar;
2014 fAngularVelocityAdditionalDamp:TKraftScalar;
2015 fLinearVelocityAdditionalDampThresholdSqr:TKraftScalar;
2016 fAngularVelocityAdditionalDampThresholdSqr:TKraftScalar;
2017
2018 fForce:TKraftVector3;
2019 fTorque:TKraftVector3;
2020
2021 fSleepTime:TKraftScalar;
2022
2023 fGravityScale:TKraftScalar;
2024
2025 fEnableGyroscopicForce:boolean;
2026
2027 fMaximalGyroscopicForce:TKraftScalar;
2028
2029 fCollisionGroups:TKraftRigidBodyCollisionGroups;
2030
2031 fCollideWithCollisionGroups:TKraftRigidBodyCollisionGroups;
2032
2033 fCountConstraints:longint;
2034
2035 fConstraintEdgeFirst:PKraftConstraintEdge;
2036 fConstraintEdgeLast:PKraftConstraintEdge;
2037
2038 fContactPairEdgeFirst:PKraftContactPairEdge;
2039 fContactPairEdgeLast:PKraftContactPairEdge;
2040
2041 fOnDamping:TKraftRigidBodyOnDamping;
2042
2043 fOnPreStep:TKraftRigidBodyOnStep;
2044 fOnPostStep:TKraftRigidBodyOnStep;
2045
2046 function GetAngularMomentum:TKraftVector3;
2047 procedure SetAngularMomentum(const NewAngularMomentum:TKraftVector3);
2048
2049 public
2050
2051 constructor Create(const APhysics:TKraft);
2052 destructor Destroy; override;
2053
2054 function SetRigidBodyType(ARigidBodyType:TKraftRigidBodyType):TKraftRigidBody;
2055
2056 function IsStatic:boolean;
2057 function IsDynamic:boolean;
2058 function IsKinematic:boolean;
2059
2060 procedure SynchronizeTransform;
2061
2062 procedure SynchronizeTransformIncludingShapes;
2063
2064 procedure StoreWorldTransform; virtual;
2065
2066 procedure InterpolateWorldTransform(const Alpha:TKraftScalar); virtual;
2067
2068 procedure Advance(Alpha:TKraftScalar);
2069
2070 procedure UpdateWorldInertiaTensor;
2071
2072 procedure Finish;
2073
2074 procedure SynchronizeProxies;
2075
2076 procedure Refilter;
2077
2078 function CanCollideWith(OtherRigidBody:TKraftRigidBody):boolean;
2079
2080 procedure SetToAwake;
2081
2082 procedure SetToSleep;
2083
2084 procedure SetWorldTransformation(const AWorldTransformation:TKraftMatrix4x4);
2085
2086 procedure SetWorldPosition(const AWorldPosition:TKraftVector3);
2087
2088 procedure SetOrientation(const AOrientation:TKraftMatrix3x3); overload;
2089 procedure SetOrientation(const x,y,z:TKraftScalar); overload;
2090 procedure AddOrientation(const x,y,z:TKraftScalar);
2091
2092 procedure LimitVelocities;
2093
2094 procedure ApplyImpulseAtPosition(const Point,Impulse:TKraftVector3);
2095 procedure ApplyImpulseAtRelativePosition(const RelativePosition,Impulse:TKraftVector3);
2096
2097 procedure SetForceAtPosition(const AForce,APosition:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2098 procedure AddForceAtPosition(const AForce,APosition:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2099
2100 procedure SetWorldForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2101 procedure AddWorldForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2102
2103 procedure SetBodyForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2104 procedure AddBodyForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2105
2106 procedure SetWorldTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2107 procedure AddWorldTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2108
2109 procedure SetBodyTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2110 procedure AddBodyTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2111
2112 procedure SetWorldAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2113 procedure AddWorldAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2114
2115 procedure SetBodyAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2116 procedure AddBodyAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2117
2118 procedure SetWorldAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2119 procedure AddWorldAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2120
2121 procedure SetBodyAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2122 procedure AddBodyAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
2123
2124 property Physics:TKraft read fPhysics;
2125
2126 property Island:TKraftIsland read fIsland;
2127
2128 property IslandIndices:TKraftRigidBodyIslandIndices read fIslandIndices;
2129
2130 property ID:uint64 read fID;
2131
2132 property RigidBodyPrevious:TKraftRigidBody read fRigidBodyPrevious;
2133 property RigidBodyNext:TKraftRigidBody read fRigidBodyNext;
2134
2135 property StaticRigidBodyIsOnList:boolean read fStaticRigidBodyIsOnList;
2136 property StaticRigidBodyPrevious:TKraftRigidBody read fStaticRigidBodyPrevious;
2137 property StaticRigidBodyNext:TKraftRigidBody read fStaticRigidBodyNext;
2138
2139 property DynamicRigidBodyIsOnList:boolean read fDynamicRigidBodyIsOnList write fDynamicRigidBodyIsOnList;
2140 property DynamicRigidBodyPrevious:TKraftRigidBody read fDynamicRigidBodyPrevious write fDynamicRigidBodyPrevious;
2141 property DynamicRigidBodyNext:TKraftRigidBody read fDynamicRigidBodyNext write fDynamicRigidBodyNext;
2142
2143 property KinematicRigidBodyIsOnList:boolean read fKinematicRigidBodyIsOnList write fKinematicRigidBodyIsOnList;
2144 property KinematicRigidBodyPrevious:TKraftRigidBody read fKinematicRigidBodyPrevious write fKinematicRigidBodyPrevious;
2145 property KinematicRigidBodyNext:TKraftRigidBody read fKinematicRigidBodyNext write fKinematicRigidBodyNext;
2146
2147 property ShapeFirst:TKraftShape read fShapeFirst write fShapeFirst;
2148 property ShapeLast:TKraftShape read fShapeLast write fShapeLast;
2149
2150 property ShapeCount:longint read fShapeCount write fShapeCount;
2151
2152 property WorldTransform:TKraftMatrix4x4 read fWorldTransform write fWorldTransform;
2153
2154 property UserData:pointer read fUserData write fUserData;
2155
2156 property BodyInertiaTensor:TKraftMatrix3x3 read fBodyInertiaTensor write fBodyInertiaTensor;
2157 property BodyInverseInertiaTensor:TKraftMatrix3x3 read fBodyInverseInertiaTensor write fBodyInverseInertiaTensor;
2158
2159 property WorldInertiaTensor:TKraftMatrix3x3 read fWorldInertiaTensor write fWorldInertiaTensor;
2160 property WorldInverseInertiaTensor:TKraftMatrix3x3 read fWorldInverseInertiaTensor write fWorldInverseInertiaTensor;
2161
2162 property ConstraintEdgeFirst:PKraftConstraintEdge read fConstraintEdgeFirst write fConstraintEdgeFirst;
2163 property ConstraintEdgeLast:PKraftConstraintEdge read fConstraintEdgeLast write fConstraintEdgeLast;
2164
2165 property CountConstraints:longint read fCountConstraints;
2166
2167 property ContactPairEdgeFirst:PKraftContactPairEdge read fContactPairEdgeFirst write fContactPairEdgeFirst;
2168 property ContactPairEdgeLast:PKraftContactPairEdge read fContactPairEdgeLast write fContactPairEdgeLast;
2169
2170 property WorldDisplacement:TKraftVector3 read fWorldDisplacement;
2171
2172 property Sweep:TKraftSweep read fSweep write fSweep;
2173
2174 property SleepTime:TKraftScalar read fSleepTime;
2175
2176 property Mass:TKraftScalar read fMass;
2177 property InverseMass:TKraftScalar read fInverseMass;
2178
2179 property LinearVelocity:TKraftVector3 read fLinearVelocity write fLinearVelocity;
2180 property AngularVelocity:TKraftVector3 read fAngularVelocity write fAngularVelocity;
2181
2182 property AngularMomentum:TKraftVector3 read GetAngularMomentum write SetAngularMomentum;
2183
2184 property Force:TKraftVector3 read fForce write fForce;
2185 property Torque:TKraftVector3 read fTorque write fTorque;
2186
2187 property NextOnIslandBuildStack:TKraftRigidBody read fNextOnIslandBuildStack;
2188 property NextStaticRigidBody:TKraftRigidBody read fNextStaticRigidBody;
2189
2190 published
2191
2192 property RigidBodyType:TKraftRigidBodyType read fRigidBodyType write fRigidBodyType;
2193
2194 property Flags:TKraftRigidBodyFlags read fFlags write fFlags;
2195
2196 property Gravity:TKraftVector3Property read fGravityProperty write fGravityProperty;
2197
2198 property TimeOfImpact:TKraftScalar read fTimeOfImpact write fTimeOfImpact;
2199
2200 property ForcedMass:TKraftScalar read fForcedMass write fForcedMass;
2201
2202 property MaximalLinearVelocity:TKraftScalar read fMaximalLinearVelocity write fMaximalLinearVelocity;
2203 property MaximalAngularVelocity:TKraftScalar read fMaximalAngularVelocity write fMaximalAngularVelocity;
2204
2205 property LinearVelocityDamp:TKraftScalar read fLinearVelocityDamp write fLinearVelocityDamp;
2206 property AngularVelocityDamp:TKraftScalar read fAngularVelocityDamp write fAngularVelocityDamp;
2207 property AdditionalDamping:boolean read fAdditionalDamping write fAdditionalDamping;
2208 property AdditionalDamp:TKraftScalar read fAdditionalDamp write fAdditionalDamp;
2209 property LinearVelocityAdditionalDamp:TKraftScalar read fLinearVelocityAdditionalDamp write fLinearVelocityAdditionalDamp;
2210 property AngularVelocityAdditionalDamp:TKraftScalar read fAngularVelocityAdditionalDamp write fAngularVelocityAdditionalDamp;
2211 property LinearVelocityAdditionalDampThresholdSqr:TKraftScalar read fLinearVelocityAdditionalDampThresholdSqr write fLinearVelocityAdditionalDampThresholdSqr;
2212 property AngularVelocityAdditionalDampThresholdSqr:TKraftScalar read fAngularVelocityAdditionalDampThresholdSqr write fAngularVelocityAdditionalDampThresholdSqr;
2213
2214 property GravityScale:TKraftScalar read fGravityScale write fGravityScale;
2215
2216 property EnableGyroscopicForce:boolean read fEnableGyroscopicForce write fEnableGyroscopicForce;
2217
2218 property MaximalGyroscopicForce:TKraftScalar read fMaximalGyroscopicForce write fMaximalGyroscopicForce;
2219
2220 property CollisionGroups:TKraftRigidBodyCollisionGroups read fCollisionGroups write fCollisionGroups;
2221
2222 property CollideWithCollisionGroups:TKraftRigidBodyCollisionGroups read fCollideWithCollisionGroups write fCollideWithCollisionGroups;
2223
2224 property OnDamping:TKraftRigidBodyOnDamping read fOnDamping write fOnDamping;
2225
2226 property OnPreStep:TKraftRigidBodyOnStep read fOnPreStep write fOnPreStep;
2227 property OnPostStep:TKraftRigidBodyOnStep read fOnPostStep write fOnPostStep;
2228
2229 end;
2230
2231 TKraftRigidBodies=array of TKraftRigidBody;
2232
2233 PKraftSolverVelocity=^TKraftSolverVelocity;
2234 TKraftSolverVelocity=record
2235 LinearVelocity:TKraftVector3;
2236 AngularVelocity:TKraftVector3;
2237 end;
2238
2239 TKraftSolverVelocities=array of TKraftSolverVelocity;
2240
2241 PKraftSolverPosition=^TKraftSolverPosition;
2242 TKraftSolverPosition=record
2243 Position:TKraftVector3;
2244 Orientation:TKraftQuaternion;
2245 end;
2246
2247 TKraftSolverPositions=array of TKraftSolverPosition;
2248
2249 TKraftSolverLinearFactors=array of TKraftVector3;
2250
2251 TKraftConstraintEdges=array[0..1] of TKraftConstraintEdge;
2252
2253 TKraftConstraintRigidBodies=array[0..1] of TKraftRigidBody;
2254
2255 TKraftConstraintLimitState=(kclsInactiveLimit,kclsAtLowerLimit,kclsAtUpperLimit,kclsEqualLimits);
2256
2257 TKraftConstraintOnBreak=procedure(APhysics:TKraft;AConstraint:TKraftConstraint) of object;
2258
2259 TKraftConstraint=class(TPersistent)
2260 private
2261
2262 fPhysics:TKraft;
2263
2264 fPrevious:TKraftConstraint;
2265 fNext:TKraftConstraint;
2266
2267 fUserData:pointer;
2268
2269 fFlags:TKraftConstraintFlags;
2270
2271 fConstraintEdges:TKraftConstraintEdges;
2272
2273 fRigidBodies:TKraftConstraintRigidBodies;
2274
2275 fBreakThresholdForce:TKraftScalar;
2276
2277 fBreakThresholdTorque:TKraftScalar;
2278
2279 fOnBreak:TKraftConstraintOnBreak;
2280
2281 fParent:TKraftConstraint;
2282
2283 fChildren:array of TKraftConstraint;
2284 fCountChildren:longint;
2285
2286 public
2287
2288 constructor Create(const APhysics:TKraft);
2289 destructor Destroy; override;
2290
2291 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); virtual;
2292 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); virtual;
2293 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; virtual;
2294
2295 function GetAnchorA:TKraftVector3; virtual;
2296 function GetAnchorB:TKraftVector3; virtual;
2297
2298 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; virtual;
2299 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; virtual;
2300
2301 property Physics:TKraft read fPhysics;
2302
2303 property Previous:TKraftConstraint read fPrevious;
2304 property Next:TKraftConstraint read fNext;
2305
2306 property UserData:pointer read fUserData write fUserData;
2307
2308 property ConstraintEdges:TKraftConstraintEdges read fConstraintEdges write fConstraintEdges;
2309
2310 property RigidBodies:TKraftConstraintRigidBodies read fRigidBodies write fRigidBodies;
2311
2312 published
2313
2314 property Flags:TKraftConstraintFlags read fFlags write fFlags;
2315
2316 property BreakThresholdForce:TKraftScalar read fBreakThresholdForce write fBreakThresholdForce;
2317
2318 property BreakThresholdTorque:TKraftScalar read fBreakThresholdTorque write fBreakThresholdTorque;
2319
2320 property OnBreak:TKraftConstraintOnBreak read fOnBreak write fOnBreak;
2321
2322 end;
2323
2324 TKraftConstraints=array of TKraftConstraint;
2325
2326 TKraftConstraintJoint=class(TKraftConstraint);
2327
2328 // Constrains a body to a specified world position which can change over time.
2329 TKraftConstraintJointGrab=class(TKraftConstraintJoint)
2330 private
2331 fIslandIndex:longint;
2332 fInverseMass:TKraftScalar;
2333 fSolverVelocity:PKraftSolverVelocity;
2334 fSolverPosition:PKraftSolverPosition;
2335 fSolverLinearFactor:PKraftVector3;
2336 fWorldInverseInertiaTensor:TKraftMatrix3x3;
2337 fRelativePosition:TKraftVector3;
2338 fLocalCenter:TKraftVector3;
2339 fLocalAnchor:TKraftVector3;
2340 fmC:TKraftVector3;
2341 fFrequencyHz:TKraftScalar;
2342 fDampingRatio:TKraftScalar;
2343 fAccumulatedImpulse:TKraftVector3;
2344 fBeta:TKraftScalar;
2345 fGamma:TKraftScalar;
2346 fMass:TKraftScalar;
2347 fEffectiveMass:TKraftMatrix3x3;
2348 fWorldPoint:TKraftVector3;
2349 fMaximalForce:TKraftScalar;
2350 public
2351 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AWorldPoint:TKraftVector3;const AFrequencyHz:TKraftScalar=5.0;const ADampingRatio:TKraftScalar=0.7;const AMaximalForce:TKraftScalar=MAX_SCALAR;const ACollideConnected:boolean=false); reintroduce;
2352 destructor Destroy; override;
2353 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2354 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2355 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2356 function GetAnchor:TKraftVector3; virtual;
2357 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2358 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2359 function GetWorldPoint:TKraftVector3; virtual;
2360 function GetMaximalForce:TKraftScalar; virtual;
2361 procedure SetWorldPoint(AWorldPoint:TKraftVector3); virtual;
2362 procedure SetMaximalForce(AMaximalForce:TKraftScalar); virtual;
2363 end;
2364
2365 // Keeps body at some fixed distance to a world plane.
2366 TKraftConstraintJointWorldPlaneDistance=class(TKraftConstraintJoint)
2367 private
2368 fIslandIndex:longint;
2369 fInverseMass:TKraftScalar;
2370 fSolverVelocity:PKraftSolverVelocity;
2371 fSolverPosition:PKraftSolverPosition;
2372 fSolverLinearFactor:PKraftVector3;
2373 fWorldInverseInertiaTensor:TKraftMatrix3x3;
2374 fRelativePosition:TKraftVector3;
2375 fLocalCenter:TKraftVector3;
2376 fLocalAnchor:TKraftVector3;
2377 fmU:TKraftVector3;
2378 fWorldPoint:TKraftVector3;
2379 fWorldPlane:TKraftPlane;
2380 fWorldDistance:TKraftScalar;
2381 fFrequencyHz:TKraftScalar;
2382 fDampingRatio:TKraftScalar;
2383 fInverseInertiaTensorRatio:TKraftScalar;
2384 fAccumulatedImpulse:TKraftScalar;
2385 fGamma:TKraftScalar;
2386 fBias:TKraftScalar;
2387 fMass:TKraftScalar;
2388 fLimitBehavior:TKraftConstraintLimitBehavior;
2389 fDoubleSidedWorldPlane:boolean;
2390 fSoftConstraint:boolean;
2391 fSkip:boolean;
2392 public
2393 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const ALocalAnchorPoint:TKraftVector3;const AWorldPlane:TKraftPlane;const ADoubleSidedWorldPlane:boolean=true;const AWorldDistance:single=1.0;const ALimitBehavior:TKraftConstraintLimitBehavior=kclbLimitDistance;const AFrequencyHz:TKraftScalar=0.0;const ADampingRatio:TKraftScalar=0.0;const AInverseInertiaTensorRatio:TKraftScalar=1.0;const ACollideConnected:boolean=false); reintroduce;
2394 destructor Destroy; override;
2395 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2396 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2397 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2398 function GetAnchor:TKraftVector3; virtual;
2399 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2400 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2401 function GetWorldPoint:TKraftVector3; virtual;
2402 function GetWorldPlane:TKraftPlane; virtual;
2403 procedure SetWorldPlane(const AWorldPlane:TKraftPlane); virtual;
2404 function GetWorldDistance:TKraftScalar; virtual;
2405 procedure SetWorldDistance(const AWorldDistance:TKraftScalar); virtual;
2406 end;
2407
2408 // Keeps bodies at some fixed distance from each other.
2409 TKraftConstraintJointDistance=class(TKraftConstraintJoint)
2410 private
2411 fIslandIndices:array[0..1] of longint;
2412 fInverseMasses:array[0..1] of TKraftScalar;
2413 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2414 fSolverPositions:array[0..1] of PKraftSolverPosition;
2415 fSolverLinearFactors:array[0..1] of PKraftVector3;
2416 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2417 fRelativePositions:array[0..1] of TKraftVector3;
2418 fLocalCenters:array[0..1] of TKraftVector3;
2419 fLocalAnchors:array[0..1] of TKraftVector3;
2420 fmU:TKraftVector3;
2421 fAnchorDistanceLength:TKraftScalar;
2422 fFrequencyHz:TKraftScalar;
2423 fDampingRatio:TKraftScalar;
2424 fAccumulatedImpulse:TKraftScalar;
2425 fGamma:TKraftScalar;
2426 fBias:TKraftScalar;
2427 fMass:TKraftScalar;
2428 public
2429 constructor Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const ALocalAnchorPointA,ALocalAnchorPointB:TKraftVector3;const AFrequencyHz:TKraftScalar=0.0;const ADampingRatio:TKraftScalar=0.0;const ACollideConnected:boolean=false); reintroduce;
2430 destructor Destroy; override;
2431 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2432 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2433 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2434 function GetAnchorA:TKraftVector3; override;
2435 function GetAnchorB:TKraftVector3; override;
2436 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2437 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2438 end;
2439
2440 // Restricts the maximum distance between two points.
2441 TKraftConstraintJointRope=class(TKraftConstraintJoint)
2442 private
2443 fIslandIndices:array[0..1] of longint;
2444 fInverseMasses:array[0..1] of TKraftScalar;
2445 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2446 fSolverPositions:array[0..1] of PKraftSolverPosition;
2447 fSolverLinearFactors:array[0..1] of PKraftVector3;
2448 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2449 fRelativePositions:array[0..1] of TKraftVector3;
2450 fLocalCenters:array[0..1] of TKraftVector3;
2451 fLocalAnchors:array[0..1] of TKraftVector3;
2452 fMaximalLength:TKraftScalar;
2453 fAccumulatedImpulse:TKraftScalar;
2454 fmU:TKraftVector3;
2455 fCurrentLength:TKraftScalar;
2456 fMass:TKraftScalar;
2457 fBias:TKraftScalar;
2458 fLimitState:TKraftConstraintLimitState;
2459 public
2460 constructor Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const ALocalAnchorPointA,ALocalAnchorPointB:TKraftVector3;const AMaximalLength:TKraftScalar=1.0;const ACollideConnected:boolean=false); reintroduce;
2461 destructor Destroy; override;
2462 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2463 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2464 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2465 function GetAnchorA:TKraftVector3; override;
2466 function GetAnchorB:TKraftVector3; override;
2467 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2468 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2469 property LimitState:TKraftConstraintLimitState read fLimitState;
2470 end;
2471
2472 // Connects two bodies to ground and to each other. As one body goes up, the other goes down.
2473 TKraftConstraintJointPulley=class(TKraftConstraintJoint)
2474 private
2475 fIslandIndices:array[0..1] of longint;
2476 fInverseMasses:array[0..1] of TKraftScalar;
2477 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2478 fSolverPositions:array[0..1] of PKraftSolverPosition;
2479 fSolverLinearFactors:array[0..1] of PKraftVector3;
2480 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2481 fRelativePositions:array[0..1] of TKraftVector3;
2482 fLocalCenters:array[0..1] of TKraftVector3;
2483 fGroundAnchors:array[0..1] of TKraftVector3;
2484 fLocalAnchors:array[0..1] of TKraftVector3;
2485 fmU:array[0..1] of TKraftVector3;
2486 fLengths:array[0..1] of TKraftScalar;
2487 fAccumulatedImpulse:TKraftScalar;
2488 fConstant:TKraftScalar;
2489 fMass:TKraftScalar;
2490 fRatio:TKraftScalar;
2491 fBias:TKraftScalar;
2492 public
2493 constructor Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AWorldGroundAnchorA,AWorldGroundAnchorB,AWorldAnchorPointA,AWorldAnchorPointB:TKraftVector3;const ARatio:TKraftScalar=1.0;const ACollideConnected:boolean=false); reintroduce;
2494 destructor Destroy; override;
2495 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2496 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2497 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2498 function GetAnchorA:TKraftVector3; override;
2499 function GetAnchorB:TKraftVector3; override;
2500 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2501 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2502 function GetCurrentLengthA:TKraftScalar;
2503 function GetCurrentLengthB:TKraftScalar;
2504 end;
2505
2506 // Allows arbitrary rotation between two bodies. This joint has three degrees of freedom.
2507 TKraftConstraintJointBallSocket=class(TKraftConstraintJoint)
2508 private
2509 fIslandIndices:array[0..1] of longint;
2510 fInverseMasses:array[0..1] of TKraftScalar;
2511 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2512 fSolverPositions:array[0..1] of PKraftSolverPosition;
2513 fSolverLinearFactors:array[0..1] of PKraftVector3;
2514 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2515 fRelativePositions:array[0..1] of TKraftVector3;
2516 fLocalCenters:array[0..1] of TKraftVector3;
2517 fLocalAnchors:array[0..1] of TKraftVector3;
2518 fAccumulatedImpulse:TKraftVector3;
2519 fBiasVector:TKraftVector3;
2520 fInverseMassMatrix:TKraftMatrix3x3;
2521 public
2522 constructor Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AWorldAnchorPoint:TKraftVector3;const ACollideConnected:boolean=false); reintroduce; overload;
2523 constructor Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const ALocalAnchorPointA,ALocalAnchorPointB:TKraftVector3;const ACollideConnected:boolean=false); reintroduce; overload;
2524 destructor Destroy; override;
2525 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2526 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2527 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2528 function GetAnchorA:TKraftVector3; override;
2529 function GetAnchorB:TKraftVector3; override;
2530 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2531 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2532 end;
2533
2534 // Forbids any translation or rotation between two bodies.
2535 TKraftConstraintJointFixed=class(TKraftConstraintJoint)
2536 private
2537 fIslandIndices:array[0..1] of longint;
2538 fInverseMasses:array[0..1] of TKraftScalar;
2539 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2540 fSolverPositions:array[0..1] of PKraftSolverPosition;
2541 fSolverLinearFactors:array[0..1] of PKraftVector3;
2542 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2543 fRelativePositions:array[0..1] of TKraftVector3;
2544 fLocalCenters:array[0..1] of TKraftVector3;
2545 fLocalAnchors:array[0..1] of TKraftVector3;
2546 fAccumulatedImpulseTranslation:TKraftVector3;
2547 fAccumulatedImpulseRotation:TKraftVector3;
2548 fBiasTranslation:TKraftVector3;
2549 fBiasRotation:TKraftVector3;
2550 fInverseMassMatrixTranslation:TKraftMatrix3x3;
2551 fInverseMassMatrixRotation:TKraftMatrix3x3;
2552 fInverseInitialOrientationDifference:TKraftQuaternion;
2553 public
2554 constructor Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AWorldAnchorPoint:TKraftVector3;const ACollideConnected:boolean=false); reintroduce;
2555 destructor Destroy; override;
2556 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2557 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2558 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2559 function GetAnchorA:TKraftVector3; override;
2560 function GetAnchorB:TKraftVector3; override;
2561 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2562 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2563 end;
2564
2565 // Allows arbitrary rotation between two bodies around a TKraftScalar axis. This joint has one degree of freedom.
2566 TKraftConstraintJointHinge=class(TKraftConstraintJoint)
2567 private
2568 fIslandIndices:array[0..1] of longint;
2569 fInverseMasses:array[0..1] of TKraftScalar;
2570 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2571 fSolverPositions:array[0..1] of PKraftSolverPosition;
2572 fSolverLinearFactors:array[0..1] of PKraftVector3;
2573 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2574 fRelativePositions:array[0..1] of TKraftVector3;
2575 fLocalCenters:array[0..1] of TKraftVector3;
2576 fLocalAnchors:array[0..1] of TKraftVector3;
2577 fLocalAxes:array[0..1] of TKraftVector3;
2578 fAccumulatedImpulseLowerLimit:TKraftScalar;
2579 fAccumulatedImpulseUpperLimit:TKraftScalar;
2580 fAccumulatedImpulseMotor:TKraftScalar;
2581 fAccumulatedImpulseTranslation:TKraftVector3;
2582 fAccumulatedImpulseRotation:TKraftVector2;
2583 fB2CrossA1:TKraftVector3;
2584 fC2CrossA1:TKraftVector3;
2585 fA1:TKraftVector3;
2586 fBiasTranslation:TKraftVector3;
2587 fBiasRotation:TKraftVector2;
2588 fInverseMassMatrixTranslation:TKraftMatrix3x3;
2589 fInverseMassMatrixRotation:TKraftMatrix2x2;
2590 fInverseMassMatrixLimitMotor:TKraftScalar;
2591 fInverseInitialOrientationDifference:TKraftQuaternion;
2592 fLimitState:boolean;
2593 fMotorState:boolean;
2594 fLowerLimit:TKraftScalar;
2595 fUpperLimit:TKraftScalar;
2596 fBiasLowerLimit:TKraftScalar;
2597 fBiasUpperLimit:TKraftScalar;
2598 fIsLowerLimitViolated:boolean;
2599 fIsUpperLimitViolated:boolean;
2600 fMotorSpeed:TKraftScalar;
2601 fMaximalMotorTorque:TKraftScalar;
2602 function ComputeCurrentHingeAngle(const OrientationA,OrientationB:TKraftQuaternion):TKraftScalar;
2603 public
2604 constructor Create(const APhysics:TKraft;
2605 const ARigidBodyA,ARigidBodyB:TKraftRigidBody;
2606 const AWorldAnchorPoint:TKraftVector3;
2607 const AWorldRotationAxis:TKraftVector3;
2608 const ALimitEnabled:boolean=false;
2609 const AMotorEnabled:boolean=false;
2610 const AMinimumAngleLimit:TKraftScalar=-1.0;
2611 const AMaximumAngleLimit:TKraftScalar=1.0;
2612 const AMotorSpeed:TKraftScalar=0.0;
2613 const AMaximalMotorTorque:TKraftScalar=0.0;
2614 const ACollideConnected:boolean=false); reintroduce;
2615 destructor Destroy; override;
2616 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2617 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2618 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2619 function GetAnchorA:TKraftVector3; override;
2620 function GetAnchorB:TKraftVector3; override;
2621 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2622 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2623 function GetWorldRotationAxis:TKraftVector3; virtual;
2624 procedure SetWorldRotationAxis(AWorldRotationAxis:TKraftVector3); virtual;
2625 function IsLimitEnabled:boolean; virtual;
2626 function IsMotorEnabled:boolean; virtual;
2627 function GetMinimumAngleLimit:TKraftScalar; virtual;
2628 function GetMaximumAngleLimit:TKraftScalar; virtual;
2629 function GetMotorSpeed:TKraftScalar; virtual;
2630 function GetMaximalMotorTorque:TKraftScalar; virtual;
2631 function GetMotorTorque(const DeltaTime:TKraftScalar):TKraftScalar; virtual;
2632 procedure ResetLimits; virtual;
2633 procedure EnableLimit(const ALimitEnabled:boolean); virtual;
2634 procedure EnableMotor(const AMotorEnabled:boolean); virtual;
2635 procedure SetMinimumAngleLimit(const AMinimumAngleLimit:TKraftScalar); virtual;
2636 procedure SetMaximumAngleLimit(const AMaximumAngleLimit:TKraftScalar); virtual;
2637 procedure SetMotorSpeed(const AMotorSpeed:TKraftScalar); virtual;
2638 procedure SetMaximalMotorTorque(const AMaximalMotorTorque:TKraftScalar); virtual;
2639 end;
2640
2641 // Allows relative translation of the bodies along a TKraftScalar direction and no rotation
2642 TKraftConstraintJointSlider=class(TKraftConstraintJoint)
2643 private
2644 fIslandIndices:array[0..1] of longint;
2645 fInverseMasses:array[0..1] of TKraftScalar;
2646 fSolverVelocities:array[0..1] of PKraftSolverVelocity;
2647 fSolverPositions:array[0..1] of PKraftSolverPosition;
2648 fSolverLinearFactors:array[0..1] of PKraftVector3;
2649 fWorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2650 fRelativePositions:array[0..1] of TKraftVector3;
2651 fLocalCenters:array[0..1] of TKraftVector3;
2652 fLocalAnchors:array[0..1] of TKraftVector3;
2653 fAccumulatedImpulseLowerLimit:TKraftScalar;
2654 fAccumulatedImpulseUpperLimit:TKraftScalar;
2655 fAccumulatedImpulseMotor:TKraftScalar;
2656 fAccumulatedImpulseTranslation:TKraftVector2;
2657 fAccumulatedImpulseRotation:TKraftVector3;
2658 fSliderAxisBodyA:TKraftVector3;
2659 fSliderAxisWorld:TKraftVector3;
2660 fN1:TKraftVector3;
2661 fN2:TKraftVector3;
2662 fR2CrossN1:TKraftVector3;
2663 fR2CrossN2:TKraftVector3;
2664 fR2CrossSliderAxis:TKraftVector3;
2665 fR1PlusUCrossN1:TKraftVector3;
2666 fR1PlusUCrossN2:TKraftVector3;
2667 fR1PlusUCrossSliderAxis:TKraftVector3;
2668 fBiasTranslation:TKraftVector2;
2669 fBiasRotation:TKraftVector3;
2670 fInverseMassMatrixTranslationConstraint:TKraftMatrix2x2;
2671 fInverseMassMatrixRotationConstraint:TKraftMatrix3x3;
2672 fInverseMassMatrixLimit:TKraftScalar;
2673 fInverseMassMatrixMotor:TKraftScalar;
2674 fInverseInitialOrientationDifference:TKraftQuaternion;
2675 fLimitState:boolean;
2676 fMotorState:boolean;
2677 fLowerLimit:TKraftScalar;
2678 fUpperLimit:TKraftScalar;
2679 fBiasLowerLimit:TKraftScalar;
2680 fBiasUpperLimit:TKraftScalar;
2681 fIsLowerLimitViolated:boolean;
2682 fIsUpperLimitViolated:boolean;
2683 fMotorSpeed:TKraftScalar;
2684 fMaximalMotorForce:TKraftScalar;
2685 public
2686 constructor Create(const APhysics:TKraft;
2687 const ARigidBodyA,ARigidBodyB:TKraftRigidBody;
2688 const AWorldAnchorPoint:TKraftVector3;
2689 const AWorldSliderAxis:TKraftVector3;
2690 const ALimitEnabled:boolean=false;
2691 const AMotorEnabled:boolean=false;
2692 const AMinimumTranslationLimit:TKraftScalar=-1.0;
2693 const AMaximumTranslationLimit:TKraftScalar=1.0;
2694 const AMotorSpeed:TKraftScalar=0.0;
2695 const AMaximalMotorForce:TKraftScalar=0.0;
2696 const ACollideConnected:boolean=false); reintroduce;
2697 destructor Destroy; override;
2698 procedure InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2699 procedure SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep); override;
2700 function SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean; override;
2701 function GetAnchorA:TKraftVector3; override;
2702 function GetAnchorB:TKraftVector3; override;
2703 function GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2704 function GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3; override;
2705 function IsLimitEnabled:boolean; virtual;
2706 function IsMotorEnabled:boolean; virtual;
2707 function GetMinimumTranslationLimit:TKraftScalar; virtual;
2708 function GetMaximumTranslationLimit:TKraftScalar; virtual;
2709 function GetMotorSpeed:TKraftScalar; virtual;
2710 function GetMaximalMotorForce:TKraftScalar; virtual;
2711 function GetMotorForce(const DeltaTime:TKraftScalar):TKraftScalar; virtual;
2712 function GetTranslation:TKraftScalar; virtual;
2713 procedure ResetLimits; virtual;
2714 procedure EnableLimit(const ALimitEnabled:boolean); virtual;
2715 procedure EnableMotor(const AMotorEnabled:boolean); virtual;
2716 procedure SetMinimumTranslationLimit(const AMinimumTranslationLimit:TKraftScalar); virtual;
2717 procedure SetMaximumTranslationLimit(const AMaximumTranslationLimit:TKraftScalar); virtual;
2718 procedure SetMotorSpeed(const AMotorSpeed:TKraftScalar); virtual;
2719 procedure SetMaximalMotorForce(const AMaximalMotorForce:TKraftScalar); virtual;
2720 end;
2721
2722 PKraftSolverVelocityStateContactPoint=^TKraftSolverVelocityStateContactPoint;
2723 TKraftSolverVelocityStateContactPoint=record
2724 RelativePositions:array[0..1] of TKraftVector3; // Vectors from center of mass to contact position
2725 Penetration:TKraftScalar; // Depth of penetration from collision
2726 NormalImpulse:TKraftScalar; // Accumulated normal impulse
2727 TangentImpulse:array[0..1] of TKraftScalar; // Accumulated friction impulse
2728 BaumgarteBias:TKraftScalar; // Baumgarte bias
2729 Bias:TKraftScalar; // Restitution + baumgarte
2730 NormalMass:TKraftScalar; // Normal constraint mass
2731 TangentMass:array[0..1] of TKraftScalar; // Tangent constraint mass
2732 end;
2733
2734 PKraftSolverVelocityState=^TKraftSolverVelocityState;
2735 TKraftSolverVelocityState=record
2736 Points:array[0..MAX_CONTACTS-1] of TKraftSolverVelocityStateContactPoint;
2737 Normal:TKraftVector3;
2738 Centers:array[0..1] of TKraftVector3;
2739 LostSpeculativeBounce:single;
2740 SpeculativeVelocity:single;
2741 WorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2742 NormalMass:TKraftScalar;
2743 TangentMass:array[0..1] of TKraftScalar;
2744 InverseMasses:array[0..1] of TKraftScalar;
2745 Restitution:TKraftScalar;
2746 Friction:TKraftScalar;
2747 Indices:array[0..1] of longint;
2748 CountPoints:longint;
2749 end;
2750
2751 TKraftSolverVelocityStates=array of TKraftSolverVelocityState;
2752
2753 PKraftSolverPositionState=^TKraftSolverPositionState;
2754 TKraftSolverPositionState=record
2755 LocalPoints:array[0..MAX_CONTACTS-1] of TKraftVector3;
2756 LocalNormal:TKraftVector3;
2757 LocalCenters:array[0..1] of TKraftVector3;
2758 WorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2759 InverseMasses:array[0..1] of TKraftScalar;
2760 Indices:array[0..1] of longint;
2761 CountPoints:longint;
2762 end;
2763
2764 TKraftSolverPositionStates=array of TKraftSolverPositionState;
2765
2766 PKraftSolverSpeculativeContactState=^TKraftSolverSpeculativeContactState;
2767 TKraftSolverSpeculativeContactState=record
2768 Points:array[0..1] of TKraftVector3;
2769 Normal:TKraftVector3;
2770 Centers:array[0..1] of TKraftVector3;
2771 LocalCenters:array[0..1] of TKraftVector3;
2772 RelativePositions:array[0..1] of TKraftVector3;
2773 WorldInverseInertiaTensors:array[0..1] of TKraftMatrix3x3;
2774 Separation:single;
2775 RestitutionBias:single;
2776 LostSpeculativeBounce:single;
2777 SpeculativeVelocity:single;
2778 NormalImpulse:single;
2779 TangentImpulse:array[0..1] of single;
2780 NormalMass:single;
2781 TangentMass:array[0..1] of single;
2782 InverseMasses:array[0..1] of single;
2783 Restitution:single;
2784 Friction:single;
2785 Indices:array[0..1] of longint;
2786 end;
2787
2788 TKraftSolverSpeculativeContactStates=array of TKraftSolverSpeculativeContactState;
2789
2790 TKraftSolver=class
2791 private
2792
2793 fPhysics:TKraft;
2794
2795 fIsland:TKraftIsland;
2796
2797 fVelocities:TKraftSolverVelocities;
2798 fCountVelocities:longint;
2799
2800 fPositions:TKraftSolverPositions;
2801 fCountPositions:longint;
2802
2803 fLinearFactors:TKraftSolverLinearFactors;
2804 fCountLinearFactors:longint;
2805
2806 fVelocityStates:TKraftSolverVelocityStates;
2807 fCountVelocityStates:longint;
2808
2809 fPositionStates:TKraftSolverPositionStates;
2810 fCountPositionStates:longint;
2811
2812 fSpeculativeContactStates:TKraftSolverSpeculativeContactStates;
2813 fCountSpeculativeContactStates:longint;
2814
2815 fCountContacts:longint;
2816
2817 fCountSpeculativeContacts:longint;
2818
2819 fDeltaTime:TKraftScalar;
2820
2821 fDeltaTimeRatio:TKraftScalar;
2822
2823 fEnableFriction:boolean;
2824
2825 fPositionCorrectionMode:TKraftPositionCorrectionMode;
2826
2827 public
2828
2829 constructor Create(const APhysics:TKraft;const AIsland:TKraftIsland);
2830 destructor Destroy; override;
2831
2832 procedure Store;
2833
2834 procedure Initialize(const TimeStep:TKraftTimeStep);
2835
2836 procedure InitializeConstraints;
2837
2838 procedure WarmStart;
2839
2840 procedure SolveVelocityConstraints;
2841
2842 function SolvePositionConstraints:boolean;
2843
2844 function SolveTimeOfImpactConstraints(IndexA,IndexB:longint):boolean;
2845
2846 procedure SolveSpeculativeContactConstraints;
2847
2848 procedure StoreImpulses;
2849
2850 property Physics:TKraft read fPhysics;
2851
2852 property Island:TKraftIsland read fIsland;
2853
2854 property Velocities:TKraftSolverVelocities read fVelocities;
2855 property CountVelocities:longint read fCountVelocities;
2856
2857 property Positions:TKraftSolverPositions read fPositions;
2858 property CountPositions:longint read fCountPositions;
2859
2860 property LinearFactors:TKraftSolverLinearFactors read fLinearFactors;
2861 property CountLinearFactors:longint read fCountLinearFactors;
2862
2863 property VelocityStates:TKraftSolverVelocityStates read fVelocityStates;
2864 property CountVelocityStates:longint read fCountVelocityStates;
2865
2866 property PositionStates:TKraftSolverPositionStates read fPositionStates;
2867 property CountPositionStates:longint read fCountPositionStates;
2868
2869 property SpeculativeContactStates:TKraftSolverSpeculativeContactStates read fSpeculativeContactStates;
2870 property CountSpeculativeContactStates:longint read fCountSpeculativeContactStates;
2871
2872 property CountContacts:longint read fCountContacts;
2873
2874 property CountSpeculativeContacts:longint read fCountSpeculativeContacts;
2875
2876 property DeltaTime:TKraftScalar read fDeltaTime;
2877
2878 property DeltaTimeRatio:TKraftScalar read fDeltaTimeRatio;
2879
2880 property EnableFriction:boolean read fEnableFriction;
2881
2882 property PositionCorrectionMode:TKraftPositionCorrectionMode read fPositionCorrectionMode;
2883
2884 end;
2885
2886 TKraftIsland=class
2887 private
2888
2889 fPhysics:TKraft;
2890
2891 fIslandIndex:longint;
2892
2893 fRigidBodies:TKraftRigidBodies;
2894 fCountRigidBodies:longint;
2895
2896 fConstraints:TKraftConstraints;
2897 fCountConstraints:longint;
2898
2899 fContactPairs:TPKraftContactPairs;
2900 fCountContactPairs:longint;
2901
2902 fStaticContactPairs:TPKraftContactPairs;
2903 fCountStaticContactPairs:longint;
2904
2905 fSpeculativeContactPairs:TPKraftContactPairs;
2906 fCountSpeculativeContactPairs:longint;
2907
2908 fSolver:TKraftSolver;
2909
2910 public
2911
2912 constructor Create(const APhysics:TKraft;const AIndex:longint);
2913 destructor Destroy; override;
2914 procedure Clear;
2915 function AddRigidBody(RigidBody:TKraftRigidBody):longint;
2916 procedure AddConstraint(Constraint:TKraftConstraint);
2917 procedure AddContactPair(ContactPair:PKraftContactPair);
2918 procedure MergeContactPairs;
2919 procedure Solve(const TimeStep:TKraftTimeStep);
2920 procedure SolveTimeOfImpact(const TimeStep:TKraftTimeStep;const IndexA,IndexB:longint);
2921
2922 property Physics:TKraft read fPhysics;
2923
2924 property IslandIndex:longint read fIslandIndex;
2925
2926 property RigidBodies:TKraftRigidBodies read fRigidBodies;
2927 property CountRigidBodies:longint read fCountRigidBodies;
2928
2929 property Constraints:TKraftConstraints read fConstraints;
2930 property CountConstraints:longint read fCountConstraints;
2931
2932 property ContactPairs:TPKraftContactPairs read fContactPairs;
2933 property CountContactPairs:longint read fCountContactPairs;
2934
2935 property StaticContactPairs:TPKraftContactPairs read fStaticContactPairs;
2936 property CountStaticContactPairs:longint read fCountStaticContactPairs;
2937
2938 property SpeculativeContactPairs:TPKraftContactPairs read fSpeculativeContactPairs;
2939 property CountSpeculativeContactPairs:longint read fCountSpeculativeContactPairs;
2940
2941 property Solver:TKraftSolver read fSolver;
2942
2943 end;
2944
2945 TKraftIslands=array of TKraftIsland;
2946
2947 {$ifndef KraftPasMP}
2948 TKraftJobManager=class;
2949
2950 TKraftJobManagerOnProcessJob=procedure(const JobIndex,ThreadIndex:longint) of object;
2951
2952 TKraftJobThread=class(TThread)
2953 private
2954 fPhysics:TKraft;
2955 fJobManager:TKraftJobManager;
2956 fThreadNumber:longint;
2957 fEvent:TEvent;
2958 fDoneEvent:TEvent;
2959 protected
2960 procedure Execute; override;
2961 public
2962 constructor Create(const APhysics:TKraft;const AJobManager:TKraftJobManager;const AThreadNumber:longint);
2963 destructor Destroy; override;
2964 property Physics:TKraft read fPhysics;
2965 property JobManager:TKraftJobManager read fJobManager;
2966 property ThreadNumber:longint read fThreadNumber;
2967 property Event:TEvent read fEvent;
2968 property DoneEvent:TEvent read fDoneEvent;
2969 end;
2970
2971 TKraftJobThreads=array of TKraftJobThread;
2972
2973 TKraftJobManager=class
2974 private
2975 fPhysics:TKraft;
2976 fThreads:TKraftJobThreads;
2977 fCountThreads:longint;
2978 fCountAliveThreads:longint;
2979 fThreadsTerminated:boolean;
2980 fOnProcessJob:TKraftJobManagerOnProcessJob;
2981 fCountRemainJobs:longint;
2982 fGranularity:longint;
2983 public
2984 constructor Create(const APhysics:TKraft);
2985 destructor Destroy; override;
2986 procedure WakeUp;
2987 procedure WaitFor;
2988 procedure ProcessJobs;
2989 property Physics:TKraft read fPhysics;
2990 property Threads:TKraftJobThreads read fThreads;
2991 property CountThreads:longint read fCountThreads;
2992 property CountAliveThreads:longint read fCountAliveThreads write fCountAliveThreads;
2993 property ThreadsTerminated:boolean read fThreadsTerminated write fThreadsTerminated;
2994 property OnProcessJob:TKraftJobManagerOnProcessJob read fOnProcessJob write fOnProcessJob;
2995 property CountRemainJobs:longint read fCountRemainJobs write fCountRemainJobs;
2996 property Granularity:longint read fGranularity write fGranularity;
2997 end;
2998 {$endif}
2999
3000 TKraftOnPushSphereShapeContactHook=procedure(const WithShape:TKraftShape) of object;
3001
3002 TKraft=class(TPersistent)
3003 private
3004
3005 {$ifdef KraftPasMP}
3006 fPasMP:TPasMP;
3007 {$endif}
3008
3009 fSingleThreaded:boolean;
3010
3011 fHighResolutionTimer:TKraftHighResolutionTimer;
3012
3013 fBroadPhaseTime:int64;
3014 fMidPhaseTime:int64;
3015 fNarrowPhaseTime:int64;
3016 fSolverTime:int64;
3017 fContinuousTime:int64;
3018 fTotalTime:int64;
3019
3020 fNewShapes:boolean;
3021
3022 fConvexHullFirst:TKraftConvexHull;
3023 fConvexHullLast:TKraftConvexHull;
3024
3025 fMeshFirst:TKraftMesh;
3026 fMeshLast:TKraftMesh;
3027
3028 fConstraintFirst:TKraftConstraint;
3029 fConstraintLast:TKraftConstraint;
3030
3031 fCountRigidBodies:longint;
3032 fRigidBodyIDCounter:uint64;
3033
3034 fRigidBodyFirst:TKraftRigidBody;
3035 fRigidBodyLast:TKraftRigidBody;
3036
3037 fStaticRigidBodyCount:longint;
3038
3039 fStaticRigidBodyFirst:TKraftRigidBody;
3040 fStaticRigidBodyLast:TKraftRigidBody;
3041
3042 fDynamicRigidBodyCount:longint;
3043
3044 fDynamicRigidBodyFirst:TKraftRigidBody;
3045 fDynamicRigidBodyLast:TKraftRigidBody;
3046
3047 fKinematicRigidBodyCount:longint;
3048
3049 fKinematicRigidBodyFirst:TKraftRigidBody;
3050 fKinematicRigidBodyLast:TKraftRigidBody;
3051
3052 fStaticAABBTree:TKraftDynamicAABBTree;
3053 fSleepingAABBTree:TKraftDynamicAABBTree;
3054 fDynamicAABBTree:TKraftDynamicAABBTree;
3055 fKinematicAABBTree:TKraftDynamicAABBTree;
3056
3057 fIslands:TKraftIslands;
3058 fCountIslands:longint;
3059
3060 fBroadPhase:TKraftBroadPhase;
3061
3062 fContactManager:TKraftContactManager;
3063
3064 fWorldFrequency:TKraftScalar;
3065
3066 fWorldDeltaTime:TKraftScalar;
3067
3068 fWorldInverseDeltaTime:TKraftScalar;
3069
3070 fLastInverseDeltaTime:TKraftScalar;
3071
3072 fAllowSleep:boolean;
3073
3074 fAllowedPenetration:TKraftScalar;
3075
3076 fGravity:TKraftVector3;
3077
3078 fGravityProperty:TKraftVector3Property;
3079
3080 fMaximalLinearVelocity:TKraftScalar;
3081 fLinearVelocityThreshold:TKraftScalar;
3082
3083 fMaximalAngularVelocity:TKraftScalar;
3084 fAngularVelocityThreshold:TKraftScalar;
3085
3086 fSleepTimeThreshold:TKraftScalar;
3087
3088 fVelocityThreshold:TKraftScalar;
3089
3090 fContactBaumgarte:TKraftScalar;
3091
3092 fConstraintBaumgarte:TKraftScalar;
3093
3094 fTimeOfImpactBaumgarte:TKraftScalar;
3095
3096 fPenetrationSlop:TKraftScalar;
3097
3098 fLinearSlop:TKraftScalar;
3099
3100 fAngularSlop:TKraftScalar;
3101
3102 fMaximalLinearCorrection:TKraftScalar;
3103
3104 fMaximalAngularCorrection:TKraftScalar;
3105
3106 fWarmStarting:boolean;
3107
3108 fContinuousMode:TKraftContinuousMode;
3109
3110 fContinuousAgainstDynamics:boolean;
3111
3112 fTimeOfImpactAlgorithm:TKraftTimeOfImpactAlgorithm;
3113
3114 fMaximalSubSteps:longint;
3115
3116 fContactPositionCorrectionMode:TKraftPositionCorrectionMode;
3117
3118 fConstraintPositionCorrectionMode:TKraftPositionCorrectionMode;
3119
3120 fVelocityIterations:longint;
3121
3122 fPositionIterations:longint;
3123
3124 fSpeculativeIterations:longint;
3125
3126 fTimeOfImpactIterations:longint;
3127
3128 fPerturbationIterations:longint;
3129
3130 fPersistentContactManifold:boolean;
3131
3132 fAlwaysPerturbating:boolean;
3133
3134 fEnableFriction:boolean;
3135
3136 fLinearVelocityRK4Integration:boolean;
3137
3138 fAngularVelocityRK4Integration:boolean;
3139
3140 fContactBreakingThreshold:TKraftScalar;
3141
3142 fCountThreads:longint;
3143
3144 {$ifndef KraftPasMP}
3145 fJobManager:TKraftJobManager;
3146 {$endif}
3147
3148 fIsSolving:boolean;
3149 fTriangleShapes:TKraftShapes;
3150
3151 fJobTimeStep:TKraftTimeStep;
3152
3153 procedure Integrate(var Position:TKraftVector3;var Orientation:TKraftQuaternion;const LinearVelocity,AngularVelocity:TKraftVector3;const DeltaTime:TKraftScalar);
3154
3155 procedure BuildIslands;
3156 {$ifdef KraftPasMP}
3157 procedure ProcessSolveIslandParallelForFunction(const Job:PPasMPJob;const ThreadIndex:longint;const Data:pointer;const FromIndex,ToIndex:TPasMPNativeInt);
3158 {$else}
3159 procedure ProcessSolveIslandJob(const JobIndex,ThreadIndex:longint);
3160 {$endif}
3161 procedure SolveIslands(const TimeStep:TKraftTimeStep);
3162
3163 function GetConservativeAdvancementTimeOfImpact(const ShapeA:TKraftShape;const SweepA:TKraftSweep;const ShapeB:TKraftShape;const ShapeBTriangleIndex:longint;const SweepB:TKraftSweep;const TimeStep:TKraftTimeStep;const ThreadIndex:longint;var Beta:TKraftScalar):boolean;
3164
3165 function GetBilateralAdvancementTimeOfImpact(const ShapeA:TKraftShape;const SweepA:TKraftSweep;const ShapeB:TKraftShape;const ShapeBTriangleIndex:longint;const SweepB:TKraftSweep;const TimeStep:TKraftTimeStep;const ThreadIndex:longint;var Beta:TKraftScalar):boolean;
3166
3167 function GetTimeOfImpact(const ShapeA:TKraftShape;const SweepA:TKraftSweep;const ShapeB:TKraftShape;const ShapeBTriangleIndex:longint;const SweepB:TKraftSweep;const TimeStep:TKraftTimeStep;const ThreadIndex:longint;var Beta:TKraftScalar):boolean;
3168
3169 procedure Solve(const TimeStep:TKraftTimeStep);
3170
3171 procedure SolveContinuousTimeOfImpactSubSteps(const TimeStep:TKraftTimeStep);
3172
3173 procedure SolveContinuousMotionClamping(const TimeStep:TKraftTimeStep);
3174
3175 protected
3176
3177 property IsSolving:boolean read fIsSolving;
3178 property TriangleShapes:TKraftShapes read fTriangleShapes;
3179 property JobTimeStep:TKraftTimeStep read fJobTimeStep;
3180
3181 public
3182
3183 {$ifdef KraftPasMP}
3184 constructor Create(const APasMP:TPasMP);
3185 {$else}
3186 constructor Create(const ACountThreads:longint=-1);
3187 {$endif}
3188 destructor Destroy; override;
3189
3190 procedure SetFrequency(const AFrequency:TKraftScalar);
3191
3192 procedure StoreWorldTransforms;
3193
3194 procedure InterpolateWorldTransforms(const Alpha:TKraftScalar);
3195
3196 procedure Step(const ADeltaTime:TKraftScalar=0);
3197
3198 function TestPoint(const Point:TKraftVector3):TKraftShape;
3199
3200 function RayCast(const Origin,Direction:TKraftVector3;const MaxTime:TKraftScalar;var Shape:TKraftShape;var Time:TKraftScalar;var Point,Normal:TKraftVector3;const CollisionGroups:TKraftRigidBodyCollisionGroups=[low(TKraftRigidBodyCollisionGroup)..high(TKraftRigidBodyCollisionGroup)]):boolean;
3201
3202 function PushSphere(var Center:TKraftVector3;const Radius:TKraftScalar;const CollisionGroups:TKraftRigidBodyCollisionGroups=[low(TKraftRigidBodyCollisionGroup)..high(TKraftRigidBodyCollisionGroup)];const TryIterations:longint=4;const OnPushSphereShapeContactHook:TKraftOnPushSphereShapeContactHook=nil):boolean;
3203
3204 function GetDistance(const ShapeA,ShapeB:TKraftShape):TKraftScalar;
3205
3206 property HighResolutionTimer:TKraftHighResolutionTimer read fHighResolutionTimer;
3207
3208 property BroadPhaseTime:int64 read fBroadPhaseTime;
3209 property MidPhaseTime:int64 read fMidPhaseTime;
3210 property NarrowPhaseTime:int64 read fNarrowPhaseTime;
3211 property SolverTime:int64 read fSolverTime;
3212 property ContinuousTime:int64 read fContinuousTime;
3213 property TotalTime:int64 read fTotalTime;
3214
3215 property NewShapes:boolean read fNewShapes;
3216
3217 property ConvexHullFirst:TKraftConvexHull read fConvexHullFirst;
3218 property ConvexHullLast:TKraftConvexHull read fConvexHullLast;
3219
3220 property MeshFirst:TKraftMesh read fMeshFirst;
3221 property MeshLast:TKraftMesh read fMeshLast;
3222
3223 property ConstraintFirst:TKraftConstraint read fConstraintFirst;
3224 property ConstraintLast:TKraftConstraint read fConstraintLast;
3225
3226 property CountRigidBodies:longint read fCountRigidBodies;
3227 property RigidBodyIDCounter:uint64 read fRigidBodyIDCounter;
3228
3229 property RigidBodyFirst:TKraftRigidBody read fRigidBodyFirst;
3230 property RigidBodyLast:TKraftRigidBody read fRigidBodyLast;
3231
3232 property StaticRigidBodyCount:longint read fStaticRigidBodyCount;
3233
3234 property StaticRigidBodyFirst:TKraftRigidBody read fStaticRigidBodyFirst;
3235 property StaticRigidBodyLast:TKraftRigidBody read fStaticRigidBodyLast;
3236
3237 property DynamicRigidBodyCount:longint read fDynamicRigidBodyCount;
3238
3239 property DynamicRigidBodyFirst:TKraftRigidBody read fDynamicRigidBodyFirst;
3240 property DynamicRigidBodyLast:TKraftRigidBody read fDynamicRigidBodyLast;
3241
3242 property KinematicRigidBodyCount:longint read fKinematicRigidBodyCount;
3243
3244 property KinematicRigidBodyFirst:TKraftRigidBody read fKinematicRigidBodyFirst;
3245 property KinematicRigidBodyLast:TKraftRigidBody read fKinematicRigidBodyLast;
3246
3247 property StaticAABBTree:TKraftDynamicAABBTree read fStaticAABBTree;
3248 property SleepingAABBTree:TKraftDynamicAABBTree read fSleepingAABBTree;
3249 property DynamicAABBTree:TKraftDynamicAABBTree read fDynamicAABBTree;
3250 property KinematicAABBTree:TKraftDynamicAABBTree read fKinematicAABBTree;
3251
3252 property Islands:TKraftIslands read fIslands;
3253 property CountIslands:longint read fCountIslands;
3254
3255 property BroadPhase:TKraftBroadPhase read fBroadPhase;
3256
3257 property ContactManager:TKraftContactManager read fContactManager;
3258
3259 property WorldDeltaTime:TKraftScalar read fWorldDeltaTime;
3260
3261 property WorldInverseDeltaTime:TKraftScalar read fWorldInverseDeltaTime;
3262
3263 property LastInverseDeltaTime:TKraftScalar read fLastInverseDeltaTime;
3264
3265 property CountThreads:longint read fCountThreads;
3266
3267 {$ifndef KraftPasMP}
3268 property JobManager:TKraftJobManager read fJobManager;
3269 {$endif}
3270
3271 published
3272
3273 property SingleThreaded:boolean read fSingleThreaded write fSingleThreaded;
3274
3275 property WorldFrequency:TKraftScalar read fWorldFrequency write SetFrequency;
3276
3277 property AllowSleep:boolean read fAllowSleep write fAllowSleep;
3278
3279 property AllowedPenetration:TKraftScalar read fAllowedPenetration write fAllowedPenetration;
3280
3281 property Gravity:TKraftVector3Property read fGravityProperty;
3282
3283 property MaximalLinearVelocity:TKraftScalar read fMaximalLinearVelocity write fMaximalLinearVelocity;
3284 property LinearVelocityThreshold:TKraftScalar read fLinearVelocityThreshold write fLinearVelocityThreshold;
3285
3286 property MaximalAngularVelocity:TKraftScalar read fMaximalAngularVelocity write fMaximalAngularVelocity;
3287 property AngularVelocityThreshold:TKraftScalar read fAngularVelocityThreshold write fAngularVelocityThreshold;
3288
3289 property SleepTimeThreshold:TKraftScalar read fSleepTimeThreshold write fSleepTimeThreshold;
3290
3291 property VelocityThreshold:TKraftScalar read fVelocityThreshold write fVelocityThreshold;
3292
3293 property ContactBaumgarte:TKraftScalar read fContactBaumgarte write fContactBaumgarte;
3294
3295 property ConstraintBaumgarte:TKraftScalar read fConstraintBaumgarte write fConstraintBaumgarte;
3296
3297 property TimeOfImpactBaumgarte:TKraftScalar read fTimeOfImpactBaumgarte write fTimeOfImpactBaumgarte;
3298
3299 property PenetrationSlop:TKraftScalar read fPenetrationSlop write fPenetrationSlop;
3300
3301 property LinearSlop:TKraftScalar read fLinearSlop write fLinearSlop;
3302
3303 property AngularSlop:TKraftScalar read fAngularSlop write fAngularSlop;
3304
3305 property MaximalLinearCorrection:TKraftScalar read fMaximalLinearCorrection write fMaximalLinearCorrection;
3306
3307 property MaximalAngularCorrection:TKraftScalar read fMaximalAngularCorrection write fMaximalAngularCorrection;
3308
3309 property WarmStarting:boolean read fWarmStarting write fWarmStarting;
3310
3311 property ContinuousMode:TKraftContinuousMode read fContinuousMode write fContinuousMode;
3312
3313 property ContinuousAgainstDynamics:boolean read fContinuousAgainstDynamics write fContinuousAgainstDynamics;
3314
3315 property TimeOfImpactAlgorithm:TKraftTimeOfImpactAlgorithm read fTimeOfImpactAlgorithm write fTimeOfImpactAlgorithm;
3316
3317 property MaximalSubSteps:longint read fMaximalSubSteps write fMaximalSubSteps;
3318
3319 property ContactPositionCorrectionMode:TKraftPositionCorrectionMode read fContactPositionCorrectionMode write fContactPositionCorrectionMode;
3320
3321 property ConstraintPositionCorrectionMode:TKraftPositionCorrectionMode read fConstraintPositionCorrectionMode write fConstraintPositionCorrectionMode;
3322
3323 property VelocityIterations:longint read fVelocityIterations write fVelocityIterations;
3324
3325 property PositionIterations:longint read fPositionIterations write fPositionIterations;
3326
3327 property SpeculativeIterations:longint read fSpeculativeIterations write fSpeculativeIterations;
3328
3329 property TimeOfImpactIterations:longint read fTimeOfImpactIterations write fTimeOfImpactIterations;
3330
3331 property PerturbationIterations:longint read fPerturbationIterations write fPerturbationIterations;
3332
3333 property PersistentContactManifold:boolean read fPersistentContactManifold write fPersistentContactManifold;
3334
3335 property AlwaysPerturbating:boolean read fAlwaysPerturbating write fAlwaysPerturbating;
3336
3337 property EnableFriction:boolean read fEnableFriction write fEnableFriction;
3338
3339 property LinearVelocityRK4Integration:boolean read fLinearVelocityRK4Integration write fLinearVelocityRK4Integration;
3340
3341 property AngularVelocityRK4Integration:boolean read fAngularVelocityRK4Integration write fAngularVelocityRK4Integration;
3342
3343 property ContactBreakingThreshold:TKraftScalar read fContactBreakingThreshold write fContactBreakingThreshold;
3344
3345 end;
3346
3347 const Vector2Origin:TKraftVector2=(x:0.0;y:0.0);
3348 Vector2XAxis:TKraftVector2=(x:1.0;y:0.0);
3349 Vector2YAxis:TKraftVector2=(x:0.0;y:1.0);
3350 Vector2ZAxis:TKraftVector2=(x:0.0;y:0.0);
3351
3352 {$ifdef SIMD}
3353 Vector3Origin:TKraftVector3=(x:0.0;y:0.0;z:0.0;w:0.0);
3354 Vector3XAxis:TKraftVector3=(x:1.0;y:0.0;z:0.0;w:0.0);
3355 Vector3YAxis:TKraftVector3=(x:0.0;y:1.0;z:0.0;w:0.0);
3356 Vector3ZAxis:TKraftVector3=(x:0.0;y:0.0;z:1.0;w:0.0);
3357 Vector3All:TKraftVector3=(x:1.0;y:1.0;z:1.0;w:0.0);
3358 {$else}
3359 Vector3Origin:TKraftVector3=(x:0.0;y:0.0;z:0.0);
3360 Vector3XAxis:TKraftVector3=(x:1.0;y:0.0;z:0.0);
3361 Vector3YAxis:TKraftVector3=(x:0.0;y:1.0;z:0.0);
3362 Vector3ZAxis:TKraftVector3=(x:0.0;y:0.0;z:1.0);
3363 Vector3All:TKraftVector3=(x:1.0;y:1.0;z:1.0);
3364 {$endif}
3365
3366 Vector4Origin:TKraftVector4=(x:0.0;y:0.0;z:0.0;w:1.0);
3367 Vector4XAxis:TKraftVector4=(x:1.0;y:0.0;z:0.0;w:1.0);
3368 Vector4YAxis:TKraftVector4=(x:0.0;y:1.0;z:0.0;w:1.0);
3369 Vector4ZAxis:TKraftVector4=(x:0.0;y:0.0;z:1.0;w:1.0);
3370
3371 Matrix2x2Identity:TKraftMatrix2x2=((1.0,0.0),(0.0,1.0));
3372 Matrix2x2Null:TKraftMatrix2x2=((0.0,0.0),(0.0,0.0));
3373
3374 {$ifdef SIMD}
3375 Matrix3x3Identity:TKraftMatrix3x3=((1.0,0.0,0.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,1.0,0.0));
3376 Matrix3x3Null:TKraftMatrix3x3=((0.0,0.0,0.0,0.0),(0.0,0.0,0.0,0.0),(0.0,0.0,0.0,0.0));
3377 {$else}
3378 Matrix3x3Identity:TKraftMatrix3x3=((1.0,0.0,0.0),(0.0,1.0,0.0),(0.0,0.0,1.0));
3379 Matrix3x3Null:TKraftMatrix3x3=((0.0,0.0,0.0),(0.0,0.0,0.0),(0.0,0.0,0.0));
3380 {$endif}
3381
3382 Matrix4x4Identity:TKraftMatrix4x4=((1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,0.0,0,1.0));
3383 Matrix4x4RightToLeftHanded:TKraftMatrix4x4=((1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,0.0,0,1.0));
3384 Matrix4x4Flip:TKraftMatrix4x4=((0.0,0.0,-1.0,0.0),(-1.0,0.0,0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0,1.0));
3385 Matrix4x4InverseFlip:TKraftMatrix4x4=((0.0,-1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(-1.0,0.0,0,0.0),(0.0,0.0,0,1.0));
3386 Matrix4x4FlipYZ:TKraftMatrix4x4=((1.0,0.0,0,0.0),(0.0,0.0,1.0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,0,1.0));
3387 Matrix4x4InverseFlipYZ:TKraftMatrix4x4=((1.0,0.0,0,0.0),(0.0,0.0,-1.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0,1.0));
3388 Matrix4x4Null:TKraftMatrix4x4=((0.0,0.0,0,0.0),(0.0,0.0,0,0.0),(0.0,0.0,0,0.0),(0.0,0.0,0,0.0));
3389 Matrix4x4NormalizedSpace:TKraftMatrix4x4=((2.0,0.0,0,0.0),(0.0,2.0,0.0,0.0),(0.0,0.0,2.0,0.0),(-1.0,-1.0,-1.0,1.0));
3390
3391 QuaternionIdentity:TKraftQuaternion=(x:0.0;y:0.0;z:0.0;w:1.0);
3392
3393 function Vector2(x,y:TKraftScalar):TKraftVector2; {$ifdef caninline}inline;{$endif}
3394 function Vector3(x,y,z:TKraftScalar):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3395 function Vector3(const v:TKraftVector4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3396 function Matrix3x3(const m:TKraftMatrix4x4):TKraftMatrix3x3; overload; {$ifdef caninline}inline;{$endif}
3397 function Plane(Normal:TKraftVector3;Distance:TKraftScalar):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
3398 function Quaternion(w,x,y,z:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
3399
3400 function Vector2Compare(const v1,v2:TKraftVector2):boolean; {$ifdef caninline}inline;{$endif}
3401 function Vector2CompareEx(const v1,v2:TKraftVector2;const Threshold:TKraftScalar=EPSILON):boolean; {$ifdef caninline}inline;{$endif}
3402 function Vector2Add(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3403 function Vector2Sub(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3404 function Vector2Avg(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3405 function Vector2ScalarMul(const v:TKraftVector2;s:TKraftScalar):TKraftVector2; {$ifdef caninline}inline;{$endif}
3406 function Vector2Dot(const v1,v2:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
3407 function Vector2Neg(const v:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3408 procedure Vector2Scale(var v:TKraftVector2;s:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
3409 procedure Vector2Scale(var v:TKraftVector2;sx,sy:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
3410 function Vector2Mul(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3411 function Vector2Length(const v:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
3412 function Vector2Dist(const v1,v2:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
3413 function Vector2LengthSquared(const v:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
3414 function Vector2Angle(const v1,v2,v3:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
3415 procedure Vector2Normalize(var v:TKraftVector2); {$ifdef caninline}inline;{$endif}
3416 function Vector2Norm(const v:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3417 procedure Vector2Rotate(var v:TKraftVector2;a:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
3418 procedure Vector2Rotate(var v:TKraftVector2;const Center:TKraftVector2;a:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
3419 procedure Vector2MatrixMul(var v:TKraftVector2;const m:TKraftMatrix2x2); {$ifdef caninline}inline;{$endif}
3420 function Vector2TermMatrixMul(const v:TKraftVector2;const m:TKraftMatrix2x2):TKraftVector2; {$ifdef caninline}inline;{$endif}
3421 function Vector2Lerp(const v1,v2:TKraftVector2;w:TKraftScalar):TKraftVector2; {$ifdef caninline}inline;{$endif}
3422
3423 {$ifdef SIMD}
3424 function Vector3Flip(const v:TKraftVector3):TKraftVector3;
3425 function Vector3Abs(const v:TKraftVector3):TKraftVector3;
3426 function Vector3Compare(const v1,v2:TKraftVector3):boolean;
3427 function Vector3CompareEx(const v1,v2:TKraftVector3;const Threshold:TKraftScalar=EPSILON):boolean;
3428 procedure Vector3DirectAdd(var v1:TKraftVector3;const v2:TKraftVector3);
3429 procedure Vector3DirectSub(var v1:TKraftVector3;const v2:TKraftVector3);
3430 function Vector3Add(const v1,v2:TKraftVector3):TKraftVector3;
3431 function Vector3Sub(const v1,v2:TKraftVector3):TKraftVector3;
3432 function Vector3Avg(const v1,v2:TKraftVector3):TKraftVector3; overload;
3433 function Vector3Avg(const v1,v2,v3:TKraftVector3):TKraftVector3; overload;
3434 function Vector3Avg(const va:PKraftVector3s;Count:longint):TKraftVector3; overload;
3435 function Vector3ScalarMul(const v:TKraftVector3;const s:TKraftScalar):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3436 function Vector3Dot(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3437 function Vector3Cos(const v1,v2:TKraftVector3):TKraftScalar;
3438 function Vector3GetOneUnitOrthogonalVector(const v:TKraftVector3):TKraftVector3;
3439 function Vector3Cross(const v1,v2:TKraftVector3):TKraftVector3;
3440 function Vector3Neg(const v:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3441 procedure Vector3Scale(var v:TKraftVector3;const sx,sy,sz:TKraftScalar); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3442 procedure Vector3Scale(var v:TKraftVector3;const s:TKraftScalar); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3443 function Vector3Mul(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3444 function Vector3Length(const v:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3445 function Vector3Dist(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3446 function Vector3LengthSquared(const v:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3447 function Vector3DistSquared(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3448 function Vector3Angle(const v1,v2,v3:TKraftVector3):TKraftScalar;
3449 function Vector3LengthNormalize(var v:TKraftVector3):TKraftScalar;
3450 procedure Vector3Normalize(var v:TKraftVector3);
3451 procedure Vector3NormalizeEx(var v:TKraftVector3);
3452 function Vector3SafeNorm(const v:TKraftVector3):TKraftVector3;
3453 function Vector3Norm(const v:TKraftVector3):TKraftVector3;
3454 function Vector3NormEx(const v:TKraftVector3):TKraftVector3;
3455 procedure Vector3RotateX(var v:TKraftVector3;a:TKraftScalar);
3456 procedure Vector3RotateY(var v:TKraftVector3;a:TKraftScalar);
3457 procedure Vector3RotateZ(var v:TKraftVector3;a:TKraftScalar);
3458 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix3x3); overload;
3459 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3460 procedure Vector3MatrixMulBasis(var v:TKraftVector3;const m:TKraftMatrix4x4); overload;
3461 procedure Vector3MatrixMulInverted(var v:TKraftVector3;const m:TKraftMatrix4x4); overload;
3462 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload;
3463 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3464 function Vector3TermMatrixMulInverse(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload;
3465 function Vector3TermMatrixMulInverted(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
3466 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload;
3467 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
3468 function Vector3TermMatrixMulTransposedBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
3469 function Vector3TermMatrixMulBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
3470 function Vector3TermMatrixMulHomogen(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3;
3471 function Vector3Lerp(const v1,v2:TKraftVector3;w:TKraftScalar):TKraftVector3;
3472 function Vector3Perpendicular(v:TKraftVector3):TKraftVector3;
3473 function Vector3TermQuaternionRotate(const v:TKraftVector3;const q:TKraftQuaternion):TKraftVector3;
3474 function Vector3ProjectToBounds(const v:TKraftVector3;const MinVector,MaxVector:TKraftVector3):TKraftScalar;
3475 {$else}
3476 function Vector3Flip(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3477 function Vector3Abs(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3478 function Vector3Compare(const v1,v2:TKraftVector3):boolean; {$ifdef caninline}inline;{$endif}
3479 function Vector3CompareEx(const v1,v2:TKraftVector3;const Threshold:TKraftScalar=EPSILON):boolean; {$ifdef caninline}inline;{$endif}
3480 function Vector3DirectAdd(var v1:TKraftVector3;const v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3481 function Vector3DirectSub(var v1:TKraftVector3;const v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3482 function Vector3Add(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3483 function Vector3Sub(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3484 function Vector3Avg(const v1,v2:TKraftVector3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3485 function Vector3Avg(const v1,v2,v3:TKraftVector3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3486 function Vector3Avg(const va:PKraftVector3s;Count:longint):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3487 function Vector3ScalarMul(const v:TKraftVector3;const s:TKraftScalar):TKraftVector3; {$ifdef caninline}inline;{$endif}
3488 function Vector3Dot(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3489 function Vector3Cos(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3490 function Vector3GetOneUnitOrthogonalVector(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3491 function Vector3Cross(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3492 function Vector3Neg(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3493 procedure Vector3Scale(var v:TKraftVector3;const sx,sy,sz:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
3494 procedure Vector3Scale(var v:TKraftVector3;const s:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
3495 function Vector3Mul(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3496 function Vector3Length(const v:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3497 function Vector3Dist(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3498 function Vector3LengthSquared(const v:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3499 function Vector3DistSquared(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3500 function Vector3Angle(const v1,v2,v3:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3501 function Vector3LengthNormalize(var v:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3502 procedure Vector3Normalize(var v:TKraftVector3); {$ifdef caninline}inline;{$endif}
3503 procedure Vector3NormalizeEx(var v:TKraftVector3); {$ifdef caninline}inline;{$endif}
3504 function Vector3SafeNorm(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3505 function Vector3Norm(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3506 function Vector3NormEx(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3507 procedure Vector3RotateX(var v:TKraftVector3;a:TKraftScalar); {$ifdef caninline}inline;{$endif}
3508 procedure Vector3RotateY(var v:TKraftVector3;a:TKraftScalar); {$ifdef caninline}inline;{$endif}
3509 procedure Vector3RotateZ(var v:TKraftVector3;a:TKraftScalar); {$ifdef caninline}inline;{$endif}
3510 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix3x3); overload; {$ifdef caninline}inline;{$endif}
3511 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3512 procedure Vector3MatrixMulBasis(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef caninline}inline;{$endif}
3513 procedure Vector3MatrixMulInverted(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef caninline}inline;{$endif}
3514 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3515 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef CPU386ASMForSinglePrecision}assembler;{$endif}
3516 function Vector3TermMatrixMulInverse(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3517 function Vector3TermMatrixMulInverted(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3518 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3519 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3520 function Vector3TermMatrixMulTransposedBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3521 function Vector3TermMatrixMulBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
3522 function Vector3TermMatrixMulHomogen(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; {$ifdef caninline}inline;{$endif}
3523 function Vector3Lerp(const v1,v2:TKraftVector3;w:TKraftScalar):TKraftVector3; {$ifdef caninline}inline;{$endif}
3524 function Vector3Perpendicular(v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
3525 function Vector3TermQuaternionRotate(const v:TKraftVector3;const q:TKraftQuaternion):TKraftVector3; {$ifdef caninline}inline;{$endif}
3526 function Vector3ProjectToBounds(const v:TKraftVector3;const MinVector,MaxVector:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3527 {$endif}
3528
3529 function Vector4Compare(const v1,v2:TKraftVector4):boolean;
3530 function Vector4CompareEx(const v1,v2:TKraftVector4;const Threshold:TKraftScalar=EPSILON):boolean;
3531 function Vector4Add(const v1,v2:TKraftVector4):TKraftVector4;
3532 function Vector4Sub(const v1,v2:TKraftVector4):TKraftVector4;
3533 function Vector4ScalarMul(const v:TKraftVector4;s:TKraftScalar):TKraftVector4;
3534 function Vector4Dot(const v1,v2:TKraftVector4):TKraftScalar;
3535 function Vector4Cross(const v1,v2:TKraftVector4):TKraftVector4;
3536 function Vector4Neg(const v:TKraftVector4):TKraftVector4;
3537 procedure Vector4Scale(var v:TKraftVector4;sx,sy,sz:TKraftScalar); overload;
3538 procedure Vector4Scale(var v:TKraftVector4;s:TKraftScalar); overload;
3539 function Vector4Mul(const v1,v2:TKraftVector4):TKraftVector4;
3540 function Vector4Length(const v:TKraftVector4):TKraftScalar;
3541 function Vector4Dist(const v1,v2:TKraftVector4):TKraftScalar;
3542 function Vector4LengthSquared(const v:TKraftVector4):TKraftScalar;
3543 function Vector4DistSquared(const v1,v2:TKraftVector4):TKraftScalar;
3544 function Vector4Angle(const v1,v2,v3:TKraftVector4):TKraftScalar;
3545 procedure Vector4Normalize(var v:TKraftVector4);
3546 function Vector4Norm(const v:TKraftVector4):TKraftVector4;
3547 procedure Vector4RotateX(var v:TKraftVector4;a:TKraftScalar);
3548 procedure Vector4RotateY(var v:TKraftVector4;a:TKraftScalar);
3549 procedure Vector4RotateZ(var v:TKraftVector4;a:TKraftScalar);
3550 procedure Vector4MatrixMul(var v:TKraftVector4;const m:TKraftMatrix4x4); {$ifdef CPU386ASMForSinglePrecision}register;{$endif}
3551 function Vector4TermMatrixMul(const v:TKraftVector4;const m:TKraftMatrix4x4):TKraftVector4; {$ifdef CPU386ASMForSinglePrecision}register;{$endif}
3552 function Vector4TermMatrixMulHomogen(const v:TKraftVector4;const m:TKraftMatrix4x4):TKraftVector4;
3553 procedure Vector4Rotate(var v:TKraftVector4;const Axis:TKraftVector4;a:TKraftScalar);
3554 function Vector4Lerp(const v1,v2:TKraftVector4;w:TKraftScalar):TKraftVector4;
3555
3556 function Matrix2x2Inverse(var mr:TKraftMatrix2x2;const ma:TKraftMatrix2x2):boolean;
3557 function Matrix2x2TermInverse(const m:TKraftMatrix2x2):TKraftMatrix2x2;
3558
3559 function Matrix3x3RotateX(Angle:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3560 function Matrix3x3RotateY(Angle:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3561 function Matrix3x3RotateZ(Angle:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3562 function Matrix3x3Rotate(Angle:TKraftScalar;Axis:TKraftVector3):TKraftMatrix3x3; overload;
3563 function Matrix3x3Scale(sx,sy,sz:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3564 procedure Matrix3x3Add(var m1:TKraftMatrix3x3;const m2:TKraftMatrix3x3); {$ifdef caninline}inline;{$endif}
3565 procedure Matrix3x3Sub(var m1:TKraftMatrix3x3;const m2:TKraftMatrix3x3); {$ifdef caninline}inline;{$endif}
3566 procedure Matrix3x3Mul(var m1:TKraftMatrix3x3;const m2:TKraftMatrix3x3);
3567 function Matrix3x3TermAdd(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3568 function Matrix3x3TermSub(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3569 function Matrix3x3TermMul(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3;
3570 function Matrix3x3TermMulTranspose(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3;
3571 procedure Matrix3x3ScalarMul(var m:TKraftMatrix3x3;s:TKraftScalar); {$ifdef caninline}inline;{$endif}
3572 function Matrix3x3TermScalarMul(const m:TKraftMatrix3x3;s:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3573 procedure Matrix3x3Transpose(var m:TKraftMatrix3x3); {$ifdef caninline}inline;{$endif}
3574 function Matrix3x3TermTranspose(const m:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3575 function Matrix3x3Determinant(const m:TKraftMatrix3x3):TKraftScalar; {$ifdef caninline}inline;{$endif}
3576 function Matrix3x3EulerAngles(const m:TKraftMatrix3x3):TKraftVector3;
3577 procedure Matrix3x3SetColumn(var m:TKraftMatrix3x3;const c:longint;const v:TKraftVector3); {$ifdef caninline}inline;{$endif}
3578 function Matrix3x3GetColumn(const m:TKraftMatrix3x3;const c:longint):TKraftVector3; {$ifdef caninline}inline;{$endif}
3579 procedure Matrix3x3SetRow(var m:TKraftMatrix3x3;const r:longint;const v:TKraftVector3); {$ifdef caninline}inline;{$endif}
3580 function Matrix3x3GetRow(const m:TKraftMatrix3x3;const r:longint):TKraftVector3; {$ifdef caninline}inline;{$endif}
3581 function Matrix3x3Compare(const m1,m2:TKraftMatrix3x3):boolean;
3582 function Matrix3x3Inverse(var mr:TKraftMatrix3x3;const ma:TKraftMatrix3x3):boolean;
3583 function Matrix3x3TermInverse(const m:TKraftMatrix3x3):TKraftMatrix3x3;
3584 procedure Matrix3x3OrthoNormalize(var m:TKraftMatrix3x3);
3585 function Matrix3x3Slerp(const a,b:TKraftMatrix3x3;x:TKraftScalar):TKraftMatrix3x3;
3586 function Matrix3x3FromToRotation(const FromDirection,ToDirection:TKraftVector3):TKraftMatrix3x3;
3587 function Matrix3x3Construct(const Forwards,Up:TKraftVector3):TKraftMatrix3x3;
3588 function Matrix3x3OuterProduct(const u,v:TKraftVector3):TKraftMatrix3x3;
3589
3590 function Matrix4x4Set(m:TKraftMatrix3x3):TKraftMatrix4x4;
3591 function Matrix4x4Rotation(m:TKraftMatrix4x4):TKraftMatrix4x4;
3592 function Matrix4x4RotateX(Angle:TKraftScalar):TKraftMatrix4x4;
3593 function Matrix4x4RotateY(Angle:TKraftScalar):TKraftMatrix4x4;
3594 function Matrix4x4RotateZ(Angle:TKraftScalar):TKraftMatrix4x4;
3595 function Matrix4x4Rotate(Angle:TKraftScalar;Axis:TKraftVector3):TKraftMatrix4x4; overload;
3596 function Matrix4x4Translate(x,y,z:TKraftScalar):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
3597 function Matrix4x4Translate(const v:TKraftVector3):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
3598 function Matrix4x4Translate(const v:TKraftVector4):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
3599 procedure Matrix4x4Translate(var m:TKraftMatrix4x4;const v:TKraftVector3); overload; {$ifdef caninline}inline;{$endif}
3600 procedure Matrix4x4Translate(var m:TKraftMatrix4x4;const v:TKraftVector4); overload; {$ifdef caninline}inline;{$endif}
3601 function Matrix4x4Scale(sx,sy,sz:TKraftScalar):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
3602 function Matrix4x4Scale(const s:TKraftVector3):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
3603 procedure Matrix4x4Add(var m1:TKraftMatrix4x4;const m2:TKraftMatrix4x4); {$ifdef caninline}inline;{$endif}
3604 procedure Matrix4x4Sub(var m1:TKraftMatrix4x4;const m2:TKraftMatrix4x4); {$ifdef caninline}inline;{$endif}
3605 procedure Matrix4x4Mul(var m1:TKraftMatrix4x4;const m2:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}register;{$endif}
3606 procedure Matrix4x4Mul(var mr:TKraftMatrix4x4;const m1,m2:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}register;{$endif}
3607 function Matrix4x4TermAdd(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
3608 function Matrix4x4TermSub(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
3609 function Matrix4x4TermMul(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef CPU386ASMForSinglePrecision}register;{$endif}
3610 function Matrix4x4TermMulInverted(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
3611 function Matrix4x4TermMulSimpleInverted(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
3612 function Matrix4x4TermMulTranspose(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4;
3613 function Matrix4x4Lerp(const a,b:TKraftMatrix4x4;x:TKraftScalar):TKraftMatrix4x4;
3614 function Matrix4x4Slerp(const a,b:TKraftMatrix4x4;x:TKraftScalar):TKraftMatrix4x4;
3615 procedure Matrix4x4ScalarMul(var m:TKraftMatrix4x4;s:TKraftScalar); {$ifdef caninline}inline;{$endif}
3616 procedure Matrix4x4Transpose(var m:TKraftMatrix4x4);
3617 function Matrix4x4TermTranspose(const m:TKraftMatrix4x4):TKraftMatrix4x4;
3618 function Matrix4x4Determinant(const m:TKraftMatrix4x4):TKraftScalar;
3619 procedure Matrix4x4SetColumn(var m:TKraftMatrix4x4;const c:longint;const v:TKraftVector4); {$ifdef caninline}inline;{$endif}
3620 function Matrix4x4GetColumn(const m:TKraftMatrix4x4;const c:longint):TKraftVector4; {$ifdef caninline}inline;{$endif}
3621 procedure Matrix4x4SetRow(var m:TKraftMatrix4x4;const r:longint;const v:TKraftVector4); {$ifdef caninline}inline;{$endif}
3622 function Matrix4x4GetRow(const m:TKraftMatrix4x4;const r:longint):TKraftVector4; {$ifdef caninline}inline;{$endif}
3623 function Matrix4x4Compare(const m1,m2:TKraftMatrix4x4):boolean;
3624 function Matrix4x4LengthSquared(const m:TKraftMatrix4x4):TKraftScalar;
3625 function Matrix4x4Length(const m:TKraftMatrix4x4):TKraftScalar;
3626 function Matrix4x4DifferenceSquared(const m1,m2:TKraftMatrix4x4):TKraftScalar;
3627 function Matrix4x4Difference(const m1,m2:TKraftMatrix4x4):TKraftScalar;
3628 procedure Matrix4x4Reflect(var mr:TKraftMatrix4x4;Plane:TKraftPlane);
3629 function Matrix4x4TermReflect(Plane:TKraftPlane):TKraftMatrix4x4;
3630 function Matrix4x4SimpleInverse(var mr:TKraftMatrix4x4;const ma:TKraftMatrix4x4):boolean; {$ifdef caninline}inline;{$endif}
3631 function Matrix4x4TermSimpleInverse(const ma:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
3632 function Matrix4x4Inverse(var mr:TKraftMatrix4x4;const ma:TKraftMatrix4x4):boolean;
3633 function Matrix4x4TermInverse(const ma:TKraftMatrix4x4):TKraftMatrix4x4;
3634 function Matrix4x4InverseOld(var mr:TKraftMatrix4x4;const ma:TKraftMatrix4x4):boolean;
3635 function Matrix4x4TermInverseOld(const ma:TKraftMatrix4x4):TKraftMatrix4x4;
3636 function Matrix4x4GetSubMatrix3x3(const m:TKraftMatrix4x4;i,j:longint):TKraftMatrix3x3;
3637 function Matrix4x4Frustum(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3638 function Matrix4x4Ortho(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3639 function Matrix4x4OrthoLH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3640 function Matrix4x4OrthoRH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3641 function Matrix4x4OrthoOffCenterLH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3642 function Matrix4x4OrthoOffCenterRH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3643 function Matrix4x4Perspective(fovy,Aspect,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
3644 function Matrix4x4LookAt(const Eye,Center,Up:TKraftVector3):TKraftMatrix4x4;
3645 function Matrix4x4Fill(const Eye,RightVector,UpVector,ForwardVector:TKraftVector3):TKraftMatrix4x4;
3646 function Matrix4x4ConstructX(const xAxis:TKraftVector3):TKraftMatrix4x4;
3647 function Matrix4x4ConstructY(const yAxis:TKraftVector3):TKraftMatrix4x4;
3648 function Matrix4x4ConstructZ(const zAxis:TKraftVector3):TKraftMatrix4x4;
3649 function Matrix4x4ProjectionMatrixClip(const ProjectionMatrix:TKraftMatrix4x4;const ClipPlane:TKraftPlane):TKraftMatrix4x4;
3650
3651 procedure PlaneNormalize(var Plane:TKraftPlane); {$ifdef caninline}inline;{$endif}
3652 function PlaneMatrixMul(const Plane:TKraftPlane;const Matrix:TKraftMatrix4x4):TKraftPlane;
3653 function PlaneTransform(const Plane:TKraftPlane;const Matrix:TKraftMatrix4x4):TKraftPlane; overload;
3654 function PlaneTransform(const Plane:TKraftPlane;const Matrix,NormalMatrix:TKraftMatrix4x4):TKraftPlane; overload;
3655 function PlaneFastTransform(const Plane:TKraftPlane;const Matrix:TKraftMatrix4x4):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
3656 function PlaneVectorDistance(const Plane:TKraftPlane;const Point:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
3657 function PlaneVectorDistance(const Plane:TKraftPlane;const Point:TKraftVector4):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
3658 function PlaneFromPoints(const p1,p2,p3:TKraftVector3):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
3659 function PlaneFromPoints(const p1,p2,p3:TKraftVector4):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
3660
3661 function QuaternionNormal(const AQuaternion:TKraftQuaternion):TKraftScalar;
3662 function QuaternionLengthSquared(const AQuaternion:TKraftQuaternion):TKraftScalar;
3663 procedure QuaternionNormalize(var AQuaternion:TKraftQuaternion);
3664 function QuaternionTermNormalize(const AQuaternion:TKraftQuaternion):TKraftQuaternion;
3665 function QuaternionNeg(const AQuaternion:TKraftQuaternion):TKraftQuaternion;
3666 function QuaternionConjugate(const AQuaternion:TKraftQuaternion):TKraftQuaternion;
3667 function QuaternionInverse(const AQuaternion:TKraftQuaternion):TKraftQuaternion;
3668 function QuaternionAdd(const q1,q2:TKraftQuaternion):TKraftQuaternion;
3669 function QuaternionSub(const q1,q2:TKraftQuaternion):TKraftQuaternion;
3670 function QuaternionScalarMul(const q:TKraftQuaternion;const s:TKraftScalar):TKraftQuaternion;
3671 function QuaternionMul(const q1,q2:TKraftQuaternion):TKraftQuaternion;
3672 function QuaternionRotateAroundAxis(const q1,q2:TKraftQuaternion):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
3673 function QuaternionFromAxisAngle(const Axis:TKraftVector3;Angle:TKraftScalar):TKraftQuaternion; overload; {$ifdef caninline}inline;{$endif}
3674 function QuaternionFromSpherical(const Latitude,Longitude:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
3675 procedure QuaternionToSpherical(const q:TKraftQuaternion;var Latitude,Longitude:TKraftScalar);
3676 function QuaternionFromAngles(const Pitch,Yaw,Roll:TKraftScalar):TKraftQuaternion; overload; {$ifdef caninline}inline;{$endif}
3677 function QuaternionFromAngles(const Angles:TKraftAngles):TKraftQuaternion; overload; {$ifdef caninline}inline;{$endif}
3678 function QuaternionFromMatrix3x3(const AMatrix:TKraftMatrix3x3):TKraftQuaternion;
3679 function QuaternionToMatrix3x3(AQuaternion:TKraftQuaternion):TKraftMatrix3x3;
3680 function QuaternionFromTangentSpaceMatrix3x3(AMatrix:TKraftMatrix3x3):TKraftQuaternion;
3681 function QuaternionToTangentSpaceMatrix3x3(AQuaternion:TKraftQuaternion):TKraftMatrix3x3;
3682 function QuaternionFromMatrix4x4(const AMatrix:TKraftMatrix4x4):TKraftQuaternion;
3683 function QuaternionToMatrix4x4(AQuaternion:TKraftQuaternion):TKraftMatrix4x4;
3684 function QuaternionToEuler(const AQuaternion:TKraftQuaternion):TKraftVector3; {$ifdef caninline}inline;{$endif}
3685 procedure QuaternionToAxisAngle(AQuaternion:TKraftQuaternion;var Axis:TKraftVector3;var Angle:TKraftScalar); {$ifdef caninline}inline;{$endif}
3686 function QuaternionGenerator(AQuaternion:TKraftQuaternion):TKraftVector3; {$ifdef caninline}inline;{$endif}
3687 function QuaternionLerp(const q1,q2:TKraftQuaternion;const t:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
3688 function QuaternionNlerp(const q1,q2:TKraftQuaternion;const t:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
3689 function QuaternionSlerp(const q1,q2:TKraftQuaternion;const t:TKraftScalar):TKraftQuaternion;
3690 function QuaternionIntegrate(const q:TKraftQuaternion;const Omega:TKraftVector3;const DeltaTime:TKraftScalar):TKraftQuaternion;
3691 function QuaternionSpin(const q:TKraftQuaternion;const Omega:TKraftVector3;const DeltaTime:TKraftScalar):TKraftQuaternion; overload;
3692 procedure QuaternionDirectSpin(var q:TKraftQuaternion;const Omega:TKraftVector3;const DeltaTime:TKraftScalar); overload;
3693 function QuaternionFromToRotation(const FromDirection,ToDirection:TKraftVector3):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
3694
3695 function InertiaTensorTransform(const Inertia,Transform:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3696 function InertiaTensorParallelAxisTheorem(const Center:TKraftVector3;const Mass:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
3697
3698 implementation
3699
3700 const daabbtNULLNODE=-1;
3701
3702 AABB_EXTENSION=0.1;
3703
3704 AABB_MULTIPLIER=2.0;
3705
3706 AABB_MAX_EXPANSION=128.0;
3707
3708 AABBExtensionVector:TKraftVector3=(x:AABB_EXTENSION;y:AABB_EXTENSION;z:AABB_EXTENSION);
3709
3710 pi2=pi*2.0;
3711
3712 {$ifdef cpu386}
3713 {%H-}MMXExt:boolean=false;
3714 {%H-}SSEExt:boolean=false;
3715 {%H-}SSE2Ext:boolean=false;
3716 {%H-}SSE3Ext:boolean=false;
3717 {$endif}
3718
3719 {$ifdef fpc}
3720 {$undef OldDelphi}
3721 {$else}
3722 {$ifdef conditionalexpressions}
3723 {$if CompilerVersion>=23.0}
3724 {$undef OldDelphi}
3725 type qword=uint64;
3726 ptruint=NativeUInt;
3727 ptrint=NativeInt;
3728 {$else}
3729 {$define OldDelphi}
3730 {$ifend}
3731 {$else}
3732 {$define OldDelphi}
3733 {$endif}
3734 {$endif}
3735 {$ifdef OldDelphi}
3736 type qword=int64;
3737 {$ifdef cpu64}
3738 ptruint=qword;
3739 ptrint=int64;
3740 {$else}
3741 ptruint=longword;
3742 ptrint=longint;
3743 {$endif}
3744 {$endif}
3745
3746 {$if defined(fpc) and (defined(cpu386) or defined(cpux64) or defined(cpuamd64))}
3747 // For to avoid "Fatal: Internal error 200604201" at the FreePascal compiler, when >= -O2 is used
3748 function Sign(const aValue:single):longint;
3749 begin
3750 if aValue<0.0 then begin
3751 result:=-1;
3752 end else if aValue>0.0 then begin
3753 result:=1;
3754 end else begin
3755 result:=0;
3756 end;
3757 end;
3758 {$ifend}
3759
3760 type TUInt128=packed record
3761 {$ifdef BIG_ENDIAN}
3762 case byte of
3763 0:(
3764 Hi,Lo:qword;
3765 );
3766 1:(
3767 Q3,Q2,Q1,Q0:longword;
3768 );
3769 {$else}
3770 case byte of
3771 0:(
3772 Lo,Hi:qword;
3773 );
3774 1:(
3775 Q0,Q1,Q2,Q3:longword;
3776 );
3777 {$endif}
3778 end;
3779
3780 function AddWithCarry(const a,b:longword;var Carry:longword):longword; {$ifdef caninline}inline;{$endif}
3781 var r:qword;
3782 begin
3783 r:=qword(a)+qword(b)+qword(Carry);
3784 Carry:=(r shr 32) and 1;
3785 result:=r and $ffffffff;
3786 end;
3787
3788 function MultiplyWithCarry(const a,b:longword;var Carry:longword):longword; {$ifdef caninline}inline;{$endif}
3789 var r:qword;
3790 begin
3791 r:=(qword(a)*qword(b))+qword(Carry);
3792 Carry:=r shr 32;
3793 result:=r and $ffffffff;
3794 end;
3795
3796 function DivideWithRemainder(const a,b:longword;var Remainder:longword):longword; {$ifdef caninline}inline;{$endif}
3797 var r:qword;
3798 begin
3799 r:=(qword(Remainder) shl 32) or a;
3800 Remainder:=r mod b;
3801 result:=r div b;
3802 end;
3803
3804 procedure UInt64ToUInt128(var Dest:TUInt128;const x:qword); {$ifdef caninline}inline;{$endif}
3805 begin
3806 Dest.Hi:=0;
3807 Dest.Lo:=x;
3808 end;
3809
3810 procedure UInt128Add(var Dest:TUInt128;const x,y:TUInt128); {$ifdef caninline}inline;{$endif}
3811 var a,b,c,d:qword;
3812 begin
3813 a:=x.Hi shr 32;
3814 b:=x.Hi and $ffffffff;
3815 c:=x.Lo shr 32;
3816 d:=x.Lo and $ffffffff;
3817 inc(d,y.Lo and $ffffffff);
3818 inc(c,(y.Lo shr 32)+(d shr 32));
3819 inc(b,(y.Hi and $ffffffff)+(c shr 32));
3820 inc(a,(y.Hi shr 32)+(b shr 32));
3821 Dest.Hi:=((a and $ffffffff) shl 32) or (b and $ffffffff);
3822 Dest.Lo:=((c and $ffffffff) shl 32) or (d and $ffffffff);
3823 end;
3824
3825 procedure UInt128Mul(var Dest:TUInt128;const x,y:TUInt128); {$ifdef caninline}inline;{$endif}
3826 var c,xw,yw,dw:array[0..15] of longword;
3827 i,j,k:longint;
3828 v:longword;
3829 begin
3830 for i:=0 to 15 do begin
3831 c[i]:=0;
3832 end;
3833 xw[7]:=(x.Lo shr 0) and $ffff;
3834 xw[6]:=(x.Lo shr 16) and $ffff;
3835 xw[5]:=(x.Lo shr 32) and $ffff;
3836 xw[4]:=(x.Lo shr 48) and $ffff;
3837 xw[3]:=(x.Hi shr 0) and $ffff;
3838 xw[2]:=(x.Hi shr 16) and $ffff;
3839 xw[1]:=(x.Hi shr 32) and $ffff;
3840 xw[0]:=(x.Hi shr 48) and $ffff;
3841 yw[7]:=(y.Lo shr 0) and $ffff;
3842 yw[6]:=(y.Lo shr 16) and $ffff;
3843 yw[5]:=(y.Lo shr 32) and $ffff;
3844 yw[4]:=(y.Lo shr 48) and $ffff;
3845 yw[3]:=(y.Hi shr 0) and $ffff;
3846 yw[2]:=(y.Hi shr 16) and $ffff;
3847 yw[1]:=(y.Hi shr 32) and $ffff;
3848 yw[0]:=(y.Hi shr 48) and $ffff;
3849 for i:=0 to 7 do begin
3850 for j:=0 to 7 do begin
3851 v:=xw[i]*yw[j];
3852 k:=i+j;
3853 inc(c[k],v shr 16);
3854 inc(c[k+1],v and $ffff);
3855 end;
3856 end;
3857 for i:=15 downto 1 do begin
3858 inc(c[i-1],c[i] shr 16);
3859 c[i]:=c[i] and $ffff;
3860 end;
3861 for i:=0 to 7 do begin
3862 dw[i]:=c[8+i];
3863 end;
3864 Dest.Hi:=(qword(dw[0] and $ffff) shl 48) or (qword(dw[1] and $ffff) shl 32) or (qword(dw[2] and $ffff) shl 16) or (qword(dw[3] and $ffff) shl 0);
3865 Dest.Lo:=(qword(dw[4] and $ffff) shl 48) or (qword(dw[5] and $ffff) shl 32) or (qword(dw[6] and $ffff) shl 16) or (qword(dw[7] and $ffff) shl 0);
3866 end;
3867
3868 procedure UInt128Div64(var Dest:TUInt128;const Dividend:TUInt128;Divisor:qword); {$ifdef caninline}inline;{$endif}
3869 var Quotient:TUInt128;
3870 Remainder:qword;
3871 Bit:longint;
3872 begin
3873 Quotient:=Dividend;
3874 Remainder:=0;
3875 for Bit:=1 to 128 do begin
3876 Remainder:=(Remainder shl 1) or (ord((Quotient.Hi and $8000000000000000)<>0) and 1);
3877 Quotient.Hi:=(Quotient.Hi shl 1) or (Quotient.Lo shr 63);
3878 Quotient.Lo:=Quotient.Lo shl 1;
3879 if (longword(Remainder shr 32)>longword(Divisor shr 32)) or
3880 ((longword(Remainder shr 32)=longword(Divisor shr 32)) and (longword(Remainder and $ffffffff)>=longword(Divisor and $ffffffff))) then begin
3881 dec(Remainder,Divisor);
3882 Quotient.Lo:=Quotient.Lo or 1;
3883 end;
3884 end;
3885 Dest:=Quotient;
3886 end;
3887
3888 procedure UInt128Mul64(var Dest:TUInt128;u,v:qword); {$ifdef caninline}inline;{$endif}
3889 var u0,u1,v0,v1,k,t,w0,w1,w2:qword;
3890 begin
3891 u1:=u shr 32;
3892 u0:=u and qword($ffffffff);
3893 v1:=v shr 32;
3894 v0:=v and qword($ffffffff);
3895 t:=u0*v0;
3896 w0:=t and qword($ffffffff);
3897 k:=t shr 32;
3898 t:=(u1*v0)+k;
3899 w1:=t and qword($ffffffff);
3900 w2:=t shr 32;
3901 t:=(u0*v1)+w1;
3902 k:=t shr 32;
3903 Dest.Lo:=(t shl 32)+w0;
3904 Dest.Hi:=((u1*v1)+w2)+k;
3905 end;
3906
3907 function RoundUpToPowerOfTwo(x:longword):longword; {$ifdef caninline}inline;{$endif}
3908 begin
3909 dec(x);
3910 x:=x or (x shr 1);
3911 x:=x or (x shr 2);
3912 x:=x or (x shr 4);
3913 x:=x or (x shr 8);
3914 x:=x or (x shr 16);
3915 result:=x+1;
3916 end;
3917
3918 function SIMDGetFlags:longword; {$ifdef cpu386}assembler;
3919 asm
3920 stmxcsr dword ptr result
3921 end;
3922 {$else}
3923 begin
3924 result:=0;
3925 end;
3926 {$endif}
3927
3928 procedure SIMDSetFlags(const Flags:longword); {$ifdef cpu386}register; assembler;
3929 var Temp:longword;
3930 asm
3931 mov dword ptr Temp,eax
3932 ldmxcsr dword ptr Temp
3933 end;
3934 {$else}
3935 begin
3936 end;
3937 {$endif}
3938
3939 procedure SIMDSetOurFlags;
3940 {$ifdef cpu386}
3941 // Flush to Zero=Bit 15
3942 // Underflow exception mask=Bit 11
3943 // Denormals are zeros=Bit 6
3944 // Denormal exception mask=Bit 8
3945 // $8840(ftz+uem+daz+dem) and $8940(ftz+uem+daz)
3946 const DenormalsAreZero=1 shl 6;
3947 InvalidOperationExceptionMask=1 shl 7;
3948 DenormalExceptionMask=1 shl 8;
3949 DivodeByZeroExceptionMask=1 shl 9;
3950 OverflowExceptionMask=1 shl 10;
3951 UnderflowExceptionMask=1 shl 11;
3952 PrecisionMask=1 shl 12;
3953 FlushToZero=1 shl 15;
3954 SIMDFlags=InvalidOperationExceptionMask or DenormalExceptionMask or DivodeByZeroExceptionMask or OverflowExceptionMask or UnderflowExceptionMask or PrecisionMask or FlushToZero or DenormalsAreZero;
3955 RoundToNearest=longword(longword($ffffffff) and not ((1 shl 13) or (1 shl 14)));
3956 var SIMDCtrl:longword;
3957 begin
3958 if SSEExt then begin
3959 asm
3960 push eax
3961 stmxcsr dword ptr SIMDCtrl
3962 mov eax,dword ptr SIMDCtrl
3963 or eax,SIMDFlags
3964 and eax,RoundToNearest
3965 mov dword ptr SIMDCtrl,eax
3966 ldmxcsr dword ptr SIMDCtrl
3967 pop eax
3968 end;
3969 end;
3970 end;
3971 {$else}
3972 begin
3973 end;
3974 {$endif}
3975
3976 procedure CheckCPU;
3977 {$ifdef cpu386}
3978 var Features,FeaturesExt:longword;
3979 {$endif}
3980 begin
3981 {$ifdef cpu386}
3982 Features:=0;
3983 FeaturesExt:=0;
3984 asm
3985 pushad
3986
3987 // Check for CPUID opcode
3988 pushfd
3989 pop eax
3990 mov edx,eax
3991 xor eax,$200000
3992 push eax
3993 popfd
3994 pushfd
3995 pop eax
3996 xor eax,edx
3997 jz @NoCPUID
3998 // Get cpu features per CPUID opcode
3999 mov eax,1
4000 cpuid
4001 mov dword ptr FeaturesExt,ecx
4002 mov dword ptr Features,edx
4003 @NoCPUID:
4004 popad
4005 end;
4006 MMXExt:=(Features and $00800000)<>0;
4007 SSEExt:=(Features and $02000000)<>0;
4008 SSE2Ext:=(Features and $04000000)<>0;
4009 SSE3Ext:=(FeaturesExt and $00000001)<>0;
4010 {$else}
4011 {MMXExt:=false;
4012 SSEExt:=false;
4013 SSE2Ext:=false;
4014 SSE3Ext:=false;{}
4015 {$endif}
4016 end;
4017
4018 function Vector2(x,y:TKraftScalar):TKraftVector2; {$ifdef caninline}inline;{$endif}
4019 begin
4020 result.x:=x;
4021 result.y:=y;
4022 end;
4023
4024 function Vector3(x,y,z:TKraftScalar):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
4025 begin
4026 result.x:=x;
4027 result.y:=y;
4028 result.z:=z;
4029 end;
4030
4031 function Vector3(const v:TKraftVector4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
4032 begin
4033 result.x:=v.x;
4034 result.y:=v.y;
4035 result.z:=v.z;
4036 end;
4037
4038 function Matrix3x3(const m:TKraftMatrix4x4):TKraftMatrix3x3; overload; {$ifdef caninline}inline;{$endif}
4039 begin
4040 result[0,0]:=m[0,0];
4041 result[0,1]:=m[0,1];
4042 result[0,2]:=m[0,2];
4043 {$ifdef SIMD}
4044 result[0,3]:=0.0;
4045 {$endif}
4046 result[1,0]:=m[1,0];
4047 result[1,1]:=m[1,1];
4048 result[1,2]:=m[1,2];
4049 {$ifdef SIMD}
4050 result[1,3]:=0.0;
4051 {$endif}
4052 result[2,0]:=m[2,0];
4053 result[2,1]:=m[2,1];
4054 result[2,2]:=m[2,2];
4055 {$ifdef SIMD}
4056 result[2,3]:=0.0;
4057 {$endif}
4058 end;
4059
4060 function Plane(Normal:TKraftVector3;Distance:TKraftScalar):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
4061 begin
4062 result.Normal:=Normal;
4063 result.Distance:=Distance;
4064 end;
4065
4066 function Quaternion(w,x,y,z:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
4067 begin
4068 result.w:=w;
4069 result.x:=x;
4070 result.y:=y;
4071 result.z:=z;
4072 end;
4073
4074 function Vector2Compare(const v1,v2:TKraftVector2):boolean; {$ifdef caninline}inline;{$endif}
4075 begin
4076 result:=(abs(v1.x-v2.x)<EPSILON) and (abs(v1.y-v2.y)<EPSILON);
4077 end;
4078
4079 function Vector2CompareEx(const v1,v2:TKraftVector2;const Threshold:TKraftScalar=EPSILON):boolean; {$ifdef caninline}inline;{$endif}
4080 begin
4081 result:=(abs(v1.x-v2.x)<Threshold) and (abs(v1.y-v2.y)<Threshold);
4082 end;
4083
4084 function Vector2Add(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4085 begin
4086 result.x:=v1.x+v2.x;
4087 result.y:=v1.y+v2.y;
4088 end;
4089
4090 function Vector2Sub(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4091 begin
4092 result.x:=v1.x-v2.x;
4093 result.y:=v1.y-v2.y;
4094 end;
4095
4096 function Vector2Avg(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4097 begin
4098 result.x:=(v1.x+v2.x)*0.5;
4099 result.y:=(v1.y+v2.y)*0.5;
4100 end;
4101
4102 function Vector2ScalarMul(const v:TKraftVector2;s:TKraftScalar):TKraftVector2; {$ifdef caninline}inline;{$endif}
4103 begin
4104 result.x:=v.x*s;
4105 result.y:=v.y*s;
4106 end;
4107
4108 function Vector2Dot(const v1,v2:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
4109 begin
4110 result:=(v1.x*v2.x)+(v1.y*v2.y);
4111 end;
4112
4113 function Vector2Neg(const v:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4114 begin
4115 result.x:=-v.x;
4116 result.y:=-v.y;
4117 end;
4118
4119 procedure Vector2Scale(var v:TKraftVector2;sx,sy:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
4120 begin
4121 v.x:=v.x*sx;
4122 v.y:=v.y*sy;
4123 end;
4124
4125 procedure Vector2Scale(var v:TKraftVector2;s:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
4126 begin
4127 v.x:=v.x*s;
4128 v.y:=v.y*s;
4129 end;
4130
4131 function Vector2Mul(const v1,v2:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4132 begin
4133 result.x:=v1.x*v2.x;
4134 result.y:=v1.y*v2.y;
4135 end;
4136
4137 function Vector2Length(const v:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
4138 begin
4139 result:=sqrt(sqr(v.x)+sqr(v.y));
4140 end;
4141
4142 function Vector2Dist(const v1,v2:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
4143 begin
4144 result:=Vector2Length(Vector2Sub(v2,v1));
4145 end;
4146
4147 function Vector2LengthSquared(const v:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
4148 begin
4149 result:=sqr(v.x)+sqr(v.y);
4150 end;
4151
4152 function Vector2Angle(const v1,v2,v3:TKraftVector2):TKraftScalar; {$ifdef caninline}inline;{$endif}
4153 var A1,A2:TKraftVector2;
4154 L1,L2:TKraftScalar;
4155 begin
4156 A1:=Vector2Sub(v1,v2);
4157 A2:=Vector2Sub(v3,v2);
4158 L1:=Vector2Length(A1);
4159 L2:=Vector2Length(A2);
4160 if (L1=0) or (L2=0) then begin
4161 result:=0;
4162 end else begin
4163 result:=ArcCos(Vector2Dot(A1,A2)/(L1*L2));
4164 end;
4165 end;
4166
4167 procedure Vector2Normalize(var v:TKraftVector2); {$ifdef caninline}inline;{$endif}
4168 var L:TKraftScalar;
4169 begin
4170 L:=Vector2Length(v);
4171 if L<>0.0 then begin
4172 Vector2Scale(v,1/L);
4173 end else begin
4174 v:=Vector2Origin;
4175 end;
4176 end;
4177
4178 function Vector2Norm(const v:TKraftVector2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4179 var L:TKraftScalar;
4180 begin
4181 L:=Vector2Length(v);
4182 if L<>0.0 then begin
4183 result:=Vector2ScalarMul(v,1/L);
4184 end else begin
4185 result:=Vector2Origin;
4186 end;
4187 end;
4188
4189 procedure Vector2Rotate(var v:TKraftVector2;a:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
4190 var r:TKraftVector2;
4191 begin
4192 r.x:=(v.x*cos(a))-(v.y*sin(a));
4193 r.y:=(v.y*cos(a))+(v.x*sin(a));
4194 v:=r;
4195 end;
4196
4197 procedure Vector2Rotate(var v:TKraftVector2;const Center:TKraftVector2;a:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
4198 var V0,r:TKraftVector2;
4199 begin
4200 V0:=Vector2Sub(v,Center);
4201 r.x:=(V0.x*cos(a))-(V0.y*sin(a));
4202 r.y:=(V0.y*cos(a))+(V0.x*sin(a));
4203 v:=Vector2Add(r,Center);
4204 end;
4205
4206 procedure Vector2MatrixMul(var v:TKraftVector2;const m:TKraftMatrix2x2); {$ifdef caninline}inline;{$endif}
4207 var t:TKraftVector2;
4208 begin
4209 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y);
4210 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y);
4211 v:=t;
4212 end;
4213
4214 function Vector2TermMatrixMul(const v:TKraftVector2;const m:TKraftMatrix2x2):TKraftVector2; {$ifdef caninline}inline;{$endif}
4215 begin
4216 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y);
4217 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y);
4218 end;
4219
4220 function Vector2Lerp(const v1,v2:TKraftVector2;w:TKraftScalar):TKraftVector2; {$ifdef caninline}inline;{$endif}
4221 var iw:TKraftScalar;
4222 begin
4223 if w<0.0 then begin
4224 result:=v1;
4225 end else if w>1.0 then begin
4226 result:=v2;
4227 end else begin
4228 iw:=1.0-w;
4229 result.x:=(iw*v1.x)+(w*v2.x);
4230 result.y:=(iw*v1.y)+(w*v2.y);
4231 end;
4232 end;
4233
4234 {$ifdef SIMD}
4235 function Vector3Flip(const v:TKraftVector3):TKraftVector3;
4236 begin
4237 result.x:=v.x;
4238 result.y:=v.z;
4239 result.z:=-v.y;
4240 end;
4241
4242 const Vector3Mask:array[0..3] of longword=($ffffffff,$ffffffff,$ffffffff,$00000000);
4243
4244 function Vector3Abs(const v:TKraftVector3):TKraftVector3;
4245 begin
4246 result.x:=abs(v.x);
4247 result.y:=abs(v.y);
4248 result.z:=abs(v.z);
4249 end;
4250
4251 function Vector3Compare(const v1,v2:TKraftVector3):boolean;
4252 begin
4253 result:=(abs(v1.x-v2.x)<EPSILON) and (abs(v1.y-v2.y)<EPSILON) and (abs(v1.z-v2.z)<EPSILON);
4254 end;
4255
4256 function Vector3CompareEx(const v1,v2:TKraftVector3;const Threshold:TKraftScalar=EPSILON):boolean;
4257 begin
4258 result:=(abs(v1.x-v2.x)<Threshold) and (abs(v1.y-v2.y)<Threshold) and (abs(v1.z-v2.z)<Threshold);
4259 end;
4260
4261 procedure Vector3DirectAdd(var v1:TKraftVector3;const v2:TKraftVector3); {$ifdef CPU386ASMForSinglePrecision}assembler;
4262 asm
4263 movups xmm0,dqword ptr [v1]
4264 movups xmm1,dqword ptr [v2]
4265 addps xmm0,xmm1
4266 movups dqword ptr [v1],xmm0
4267 end;
4268 {$else}
4269 begin
4270 v1.x:=v1.x+v2.x;
4271 v1.y:=v1.y+v2.y;
4272 v1.z:=v1.z+v2.z;
4273 end;
4274 {$endif}
4275
4276 procedure Vector3DirectSub(var v1:TKraftVector3;const v2:TKraftVector3); {$ifdef CPU386ASMForSinglePrecision}assembler;
4277 asm
4278 movups xmm0,dqword ptr [v1]
4279 movups xmm1,dqword ptr [v2]
4280 subps xmm0,xmm1
4281 movups dqword ptr [v1],xmm0
4282 end;
4283 {$else}
4284 begin
4285 v1.x:=v1.x-v2.x;
4286 v1.y:=v1.y-v2.y;
4287 v1.z:=v1.z-v2.z;
4288 end;
4289 {$endif}
4290
4291 function Vector3Add(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4292 asm
4293 movups xmm0,dqword ptr [v1]
4294 movups xmm1,dqword ptr [v2]
4295 addps xmm0,xmm1
4296 movups dqword ptr [result],xmm0
4297 end;
4298 {$else}
4299 begin
4300 result.x:=v1.x+v2.x;
4301 result.y:=v1.y+v2.y;
4302 result.z:=v1.z+v2.z;
4303 end;
4304 {$endif}
4305
4306 function Vector3Sub(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4307 asm
4308 movups xmm0,dqword ptr [v1]
4309 movups xmm1,dqword ptr [v2]
4310 subps xmm0,xmm1
4311 movups dqword ptr [result],xmm0
4312 end;
4313 {$else}
4314 begin
4315 result.x:=v1.x-v2.x;
4316 result.y:=v1.y-v2.y;
4317 result.z:=v1.z-v2.z;
4318 end;
4319 {$endif}
4320
4321 function Vector3Avg(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4322 const Half:TKraftVector3=(x:0.5;y:0.5;z:0.5;w:0.0);
4323 asm
4324 movups xmm0,dqword ptr [v1]
4325 movups xmm1,dqword ptr [v2]
4326 movups xmm2,dqword ptr [Half]
4327 addps xmm0,xmm1
4328 mulps xmm0,xmm2
4329 movups dqword ptr [result],xmm0
4330 end;
4331 {$else}
4332 begin
4333 result.x:=(v1.x+v2.x)*0.5;
4334 result.y:=(v1.y+v2.y)*0.5;
4335 result.z:=(v1.z+v2.z)*0.5;
4336 end;
4337 {$endif}
4338
4339 function Vector3Avg(const v1,v2,v3:TKraftVector3):TKraftVector3;
4340 begin
4341 result.x:=(v1.x+v2.x+v3.x)/3.0;
4342 result.y:=(v1.y+v2.y+v3.y)/3.0;
4343 result.z:=(v1.z+v2.z+v3.z)/3.0;
4344 end;
4345
4346 function Vector3Avg(const va:PKraftVector3s;Count:longint):TKraftVector3;
4347 var i:longint;
4348 begin
4349 result.x:=0.0;
4350 result.y:=0.0;
4351 result.z:=0.0;
4352 if Count>0 then begin
4353 for i:=0 to Count-1 do begin
4354 result.x:=result.x+va^[i].x;
4355 result.y:=result.y+va^[i].y;
4356 result.z:=result.z+va^[i].z;
4357 end;
4358 result.x:=result.x/Count;
4359 result.y:=result.y/Count;
4360 result.z:=result.z/Count;
4361 end;
4362 end;
4363
4364 function Vector3ScalarMul(const v:TKraftVector3;const s:TKraftScalar):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4365 asm
4366 movups xmm0,dqword ptr [v]
4367 movss xmm1,dword ptr [s]
4368 shufps xmm1,xmm1,$00
4369 mulps xmm0,xmm1
4370 movups dqword ptr [result],xmm0
4371 end;
4372 {$else}
4373 begin
4374 result.x:=v.x*s;
4375 result.y:=v.y*s;
4376 result.z:=v.z*s;
4377 end;
4378 {$endif}
4379
4380 function Vector3Dot(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
4381 asm
4382 movups xmm0,dqword ptr [v1]
4383 movups xmm1,dqword ptr [v2]
4384 mulps xmm0,xmm1 // xmm0 = ?, z1*z2, y1*y2, x1*x2
4385 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z1*z2
4386 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z1*z2 + x1*x2
4387 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y1*y2
4388 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z1*z2 + y1*y2 + x1*x2
4389 movss dword ptr [result],xmm1
4390 end;
4391 {$else}
4392 begin
4393 result:=(v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z);
4394 end;
4395 {$endif}
4396
4397 function Vector3Cos(const v1,v2:TKraftVector3):TKraftScalar;
4398 var d:extended;
4399 begin
4400 d:=sqrt(Vector3LengthSquared(v1)*Vector3LengthSquared(v2));
4401 if d<>0.0 then begin
4402 result:=((v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z))/d; //result:=Vector3Dot(v1,v2)/d;
4403 end else begin
4404 result:=0.9;
4405 end
4406 end;
4407
4408 function Vector3GetOneUnitOrthogonalVector(const v:TKraftVector3):TKraftVector3;
4409 var MinimumAxis:longint;
4410 l:TKraftScalar;
4411 begin
4412 if abs(v.x)<abs(v.y) then begin
4413 if abs(v.x)<abs(v.z) then begin
4414 MinimumAxis:=0;
4415 end else begin
4416 MinimumAxis:=2;
4417 end;
4418 end else begin
4419 if abs(v.y)<abs(v.z) then begin
4420 MinimumAxis:=1;
4421 end else begin
4422 MinimumAxis:=2;
4423 end;
4424 end;
4425 case MinimumAxis of
4426 0:begin
4427 l:=sqrt(sqr(v.y)+sqr(v.z));
4428 result.x:=0.0;
4429 result.y:=-(v.z/l);
4430 result.z:=v.y/l;
4431 end;
4432 1:begin
4433 l:=sqrt(sqr(v.x)+sqr(v.z));
4434 result.x:=-(v.z/l);
4435 result.y:=0.0;
4436 result.z:=v.x/l;
4437 end;
4438 else begin
4439 l:=sqrt(sqr(v.x)+sqr(v.y));
4440 result.x:=-(v.y/l);
4441 result.y:=v.x/l;
4442 result.z:=0.0;
4443 end;
4444 end;
4445 result.w:=0.0;
4446 end;
4447
4448 function Vector3Cross(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4449 asm
4450 {$ifdef SSEVector3CrossOtherVariant}
4451 movups xmm0,dqword ptr [v1]
4452 movups xmm2,dqword ptr [v2]
4453 movaps xmm1,xmm0
4454 movaps xmm3,xmm2
4455 shufps xmm0,xmm0,$c9
4456 shufps xmm1,xmm1,$d2
4457 shufps xmm2,xmm2,$d2
4458 shufps xmm3,xmm3,$c9
4459 mulps xmm0,xmm2
4460 mulps xmm1,xmm3
4461 subps xmm0,xmm1
4462 movups dqword ptr [result],xmm0
4463 {$else}
4464 movups xmm0,dqword ptr [v1]
4465 movups xmm1,dqword ptr [v2]
4466 movaps xmm2,xmm0
4467 movaps xmm3,xmm1
4468 shufps xmm0,xmm0,$12
4469 shufps xmm1,xmm1,$09
4470 shufps xmm2,xmm2,$09
4471 shufps xmm3,xmm3,$12
4472 mulps xmm0,xmm1
4473 mulps xmm2,xmm3
4474 subps xmm2,xmm0
4475 movups dqword ptr [result],xmm2
4476 {$endif}
4477 end;
4478 {$else}
4479 begin
4480 result.x:=(v1.y*v2.z)-(v1.z*v2.y);
4481 result.y:=(v1.z*v2.x)-(v1.x*v2.z);
4482 result.z:=(v1.x*v2.y)-(v1.y*v2.x);
4483 end;
4484 {$endif}
4485
4486 function Vector3Neg(const v:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4487 asm
4488 xorps xmm0,xmm0
4489 movups xmm1,dqword ptr [v]
4490 subps xmm0,xmm1
4491 movups dqword ptr [result],xmm0
4492 end;
4493 {$else}
4494 begin
4495 result.x:=-v.x;
4496 result.y:=-v.y;
4497 result.z:=-v.z;
4498 end;
4499 {$endif}
4500
4501 procedure Vector3Scale(var v:TKraftVector3;const sx,sy,sz:TKraftScalar); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
4502 asm
4503 movss xmm0,dword ptr [v+0]
4504 movss xmm1,dword ptr [v+4]
4505 movss xmm2,dword ptr [v+8]
4506 mulss xmm0,dword ptr [sx]
4507 mulss xmm1,dword ptr [sy]
4508 mulss xmm2,dword ptr [sz]
4509 movss dword ptr [v+0],xmm0
4510 movss dword ptr [v+4],xmm1
4511 movss dword ptr [v+8],xmm2
4512 end;
4513 {$else}
4514 begin
4515 v.x:=v.x*sx;
4516 v.y:=v.y*sy;
4517 v.z:=v.z*sz;
4518 end;
4519 {$endif}
4520
4521 procedure Vector3Scale(var v:TKraftVector3;const s:TKraftScalar); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
4522 asm
4523 movups xmm0,dqword ptr [v]
4524 movss xmm1,dword ptr [s]
4525 shufps xmm1,xmm1,$00
4526 mulps xmm0,xmm1
4527 movups dqword ptr [v],xmm0
4528 end;
4529 {$else}
4530 begin
4531 v.x:=v.x*s;
4532 v.y:=v.y*s;
4533 v.z:=v.z*s;
4534 end;
4535 {$endif}
4536
4537 function Vector3Mul(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4538 asm
4539 movups xmm0,dqword ptr [v1]
4540 movups xmm1,dqword ptr [v2]
4541 mulps xmm0,xmm1
4542 movups dqword ptr [result],xmm0
4543 end;
4544 {$else}
4545 begin
4546 result.x:=v1.x*v2.x;
4547 result.y:=v1.y*v2.y;
4548 result.z:=v1.z*v2.z;
4549 end;
4550 {$endif}
4551
4552 function Vector3Length(const v:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
4553 asm
4554 movups xmm0,dqword ptr [v]
4555 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4556 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4557 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4558 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4559 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4560 sqrtss xmm0,xmm1
4561 movss dword ptr [result],xmm0
4562 end;
4563 {$else}
4564 begin
4565 result:=sqrt(sqr(v.x)+sqr(v.y)+sqr(v.z));
4566 end;
4567 {$endif}
4568
4569 function Vector3Dist(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
4570 asm
4571 movups xmm0,dqword ptr [v1]
4572 movups xmm1,dqword ptr [v2]
4573 subps xmm0,xmm1
4574 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4575 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4576 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4577 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4578 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4579 sqrtss xmm0,xmm1
4580 movss dword ptr [result],xmm0
4581 end;
4582 {$else}
4583 begin
4584 result:=sqrt(sqr(v2.x-v1.x)+sqr(v2.y-v1.y)+sqr(v2.z-v1.z));
4585 end;
4586 {$endif}
4587
4588 function Vector3LengthSquared(const v:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
4589 asm
4590 movups xmm0,dqword ptr [v]
4591 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4592 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4593 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4594 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4595 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4596 movss dword ptr [result],xmm1
4597 end;
4598 {$else}
4599 begin
4600 result:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4601 end;
4602 {$endif}
4603
4604 function Vector3DistSquared(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
4605 asm
4606 movups xmm0,dqword ptr [v1]
4607 movups xmm1,dqword ptr [v2]
4608 subps xmm0,xmm1
4609 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4610 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4611 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4612 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4613 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4614 movss dword ptr [result],xmm1
4615 end;
4616 {$else}
4617 begin
4618 result:=sqr(v2.x-v1.x)+sqr(v2.y-v1.y)+sqr(v2.z-v1.z);
4619 end;
4620 {$endif}
4621
4622 function Vector3Angle(const v1,v2,v3:TKraftVector3):TKraftScalar;
4623 var A1,A2:TKraftVector3;
4624 L1,L2:TKraftScalar;
4625 begin
4626 A1:=Vector3Sub(v1,v2);
4627 A2:=Vector3Sub(v3,v2);
4628 L1:=Vector3Length(A1);
4629 L2:=Vector3Length(A2);
4630 if (L1=0) or (L2=0) then begin
4631 result:=0;
4632 end else begin
4633 result:=ArcCos(Vector3Dot(A1,A2)/(L1*L2));
4634 end;
4635 end;
4636
4637 function Vector3LengthNormalize(var v:TKraftVector3):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
4638 asm
4639 movups xmm0,dqword ptr [v]
4640 movaps xmm1,xmm0
4641 subps xmm1,xmm0
4642 cmpps xmm1,xmm0,7
4643 andps xmm0,xmm1
4644 movaps xmm2,xmm0
4645 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4646 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4647 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4648 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4649 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4650 sqrtss xmm0,xmm1
4651 movss dword ptr [result],xmm0
4652 shufps xmm0,xmm0,$00
4653 divps xmm2,xmm0
4654 movaps xmm1,xmm2
4655 subps xmm1,xmm2
4656 cmpps xmm1,xmm2,7
4657 andps xmm2,xmm1
4658 movups dqword ptr [v],xmm2
4659 end;
4660 {$else}
4661 var l:TKraftScalar;
4662 begin
4663 result:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4664 if result>0.0 then begin
4665 result:=sqrt(result);
4666 l:=1.0/result;
4667 v.x:=v.x*l;
4668 v.y:=v.y*l;
4669 v.z:=v.z*l;
4670 end else begin
4671 result:=0.0;
4672 v.x:=0.0;
4673 v.y:=0.0;
4674 v.z:=0.0;
4675 end;
4676 end;
4677 {$endif}
4678
4679 procedure Vector3Normalize(var v:TKraftVector3); {$ifdef CPU386ASMForSinglePrecision}assembler;
4680 asm
4681 movups xmm0,dqword ptr [v]
4682 movaps xmm2,xmm0
4683 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4684 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4685 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4686 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4687 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4688 rsqrtss xmm0,xmm1
4689 shufps xmm0,xmm0,$00
4690 mulps xmm2,xmm0
4691 movaps xmm1,xmm2
4692 subps xmm1,xmm2
4693 cmpps xmm1,xmm2,7
4694 andps xmm2,xmm1
4695 movups dqword ptr [v],xmm2
4696 end;
4697 {$else}
4698 var l:TKraftScalar;
4699 begin
4700 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4701 if l>0.0 then begin
4702 l:=1.0/sqrt(l);
4703 v.x:=v.x*l;
4704 v.y:=v.y*l;
4705 v.z:=v.z*l;
4706 end else begin
4707 v.x:=0.0;
4708 v.y:=0.0;
4709 v.z:=0.0;
4710 end;
4711 end;
4712 {$endif}
4713
4714 procedure Vector3NormalizeEx(var v:TKraftVector3); {$ifdef CPU386ASMForSinglePrecision}assembler;
4715 asm
4716 movups xmm0,dqword ptr [v]
4717 movaps xmm2,xmm0
4718 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4719 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4720 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4721 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4722 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4723 sqrtss xmm0,xmm1
4724 shufps xmm0,xmm0,$00
4725 divps xmm2,xmm0
4726 movaps xmm1,xmm2
4727 subps xmm1,xmm2
4728 cmpps xmm1,xmm2,7
4729 andps xmm2,xmm1
4730 movups dqword ptr [v],xmm2
4731 end;
4732 {$else}
4733 var l:TKraftScalar;
4734 begin
4735 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4736 if l>0.0 then begin
4737 l:=sqrt(l);
4738 v.x:=v.x/l;
4739 v.y:=v.y/l;
4740 v.z:=v.z/l;
4741 end else begin
4742 v.x:=0.0;
4743 v.y:=0.0;
4744 v.z:=0.0;
4745 end;
4746 end;
4747 {$endif}
4748
4749 function Vector3SafeNorm(const v:TKraftVector3):TKraftVector3;
4750 var l:TKraftScalar;
4751 begin
4752 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4753 if l>0.0 then begin
4754 l:=1.0/sqrt(l);
4755 result.x:=v.x*l;
4756 result.y:=v.y*l;
4757 result.z:=v.z*l;
4758 end else begin
4759 result.x:=1.0;
4760 result.y:=0.0;
4761 result.z:=0.0;
4762 end;
4763 end;
4764
4765 function Vector3Norm(const v:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4766 asm
4767 movups xmm0,dqword ptr [v]
4768 movaps xmm2,xmm0
4769 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4770 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4771 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4772 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4773 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4774 rsqrtss xmm0,xmm1
4775 shufps xmm0,xmm0,$00
4776 mulps xmm2,xmm0
4777 movaps xmm1,xmm2
4778 subps xmm1,xmm2
4779 cmpps xmm1,xmm2,7
4780 andps xmm2,xmm1
4781 movups dqword ptr [result],xmm2
4782 end;
4783 {$else}
4784 var l:TKraftScalar;
4785 begin
4786 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4787 if l>0.0 then begin
4788 l:=1.0/sqrt(l);
4789 result.x:=v.x*l;
4790 result.y:=v.y*l;
4791 result.z:=v.z*l;
4792 end else begin
4793 result.x:=0.0;
4794 result.y:=0.0;
4795 result.z:=0.0;
4796 end;
4797 end;
4798 {$endif}
4799
4800 function Vector3NormEx(const v:TKraftVector3):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
4801 asm
4802 movups xmm0,dqword ptr [v]
4803 movaps xmm2,xmm0
4804 mulps xmm0,xmm0 // xmm0 = ?, z*z, y*y, x*x
4805 movhlps xmm1,xmm0 // xmm1 = ?, ?, ?, z*z
4806 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + x*x
4807 shufps xmm0,xmm0,$55 // xmm0 = ?, ?, ?, y*y
4808 addss xmm1,xmm0 // xmm1 = ?, ?, ?, z*z + y*y + x*x
4809 sqrtss xmm0,xmm1
4810 shufps xmm0,xmm0,$00
4811 divps xmm2,xmm0
4812 movaps xmm1,xmm2
4813 subps xmm1,xmm2
4814 cmpps xmm1,xmm2,7
4815 andps xmm2,xmm1
4816 movups dqword ptr [result],xmm2
4817 end;
4818 {$else}
4819 var l:TKraftScalar;
4820 begin
4821 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
4822 if l>0.0 then begin
4823 l:=sqrt(l);
4824 result.x:=v.x/l;
4825 result.y:=v.y/l;
4826 result.z:=v.z/l;
4827 end else begin
4828 result.x:=0.0;
4829 result.y:=0.0;
4830 result.z:=0.0;
4831 end;
4832 end;
4833 {$endif}
4834
4835 procedure Vector3RotateX(var v:TKraftVector3;a:TKraftScalar);
4836 var t:TKraftVector3;
4837 begin
4838 t.x:=v.x;
4839 t.y:=(v.y*cos(a))-(v.z*sin(a));
4840 t.z:=(v.y*sin(a))+(v.z*cos(a));
4841 v:=t;
4842 end;
4843
4844 procedure Vector3RotateY(var v:TKraftVector3;a:TKraftScalar);
4845 var t:TKraftVector3;
4846 begin
4847 t.x:=(v.x*cos(a))+(v.z*sin(a));
4848 t.y:=v.y;
4849 t.z:=(v.z*cos(a))-(v.x*sin(a));
4850 v:=t;
4851 end;
4852
4853 procedure Vector3RotateZ(var v:TKraftVector3;a:TKraftScalar);
4854 var t:TKraftVector3;
4855 begin
4856 t.x:=(v.x*cos(a))-(v.y*sin(a));
4857 t.y:=(v.x*sin(a))+(v.y*cos(a));
4858 t.z:=v.z;
4859 v:=t;
4860 end;
4861
4862 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix3x3); overload;
4863 var t:TKraftVector3;
4864 begin
4865 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
4866 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
4867 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
4868 v:=t;
4869 end;
4870
4871 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
4872 const cOne:array[0..3] of TKraftScalar=(0.0,0.0,0.0,1.0);
4873 asm
4874 movups xmm0,dqword ptr [v] // d c b a
4875 movups xmm1,dqword ptr [Vector3Mask]
4876 movups xmm2,dqword ptr [cOne]
4877 andps xmm0,xmm1
4878 addps xmm0,xmm2
4879 movaps xmm1,xmm0 // d c b a
4880 movaps xmm2,xmm0 // d c b a
4881 movaps xmm3,xmm0 // d c b a
4882 shufps xmm0,xmm0,$00 // a a a a 00000000b
4883 shufps xmm1,xmm1,$55 // b b b b 01010101b
4884 shufps xmm2,xmm2,$aa // c c c c 10101010b
4885 shufps xmm3,xmm3,$ff // d d d d 11111111b
4886 movups xmm4,dqword ptr [m+0]
4887 movups xmm5,dqword ptr [m+16]
4888 movups xmm6,dqword ptr [m+32]
4889 movups xmm7,dqword ptr [m+48]
4890 mulps xmm0,xmm4
4891 mulps xmm1,xmm5
4892 mulps xmm2,xmm6
4893 mulps xmm3,xmm7
4894 addps xmm0,xmm1
4895 addps xmm2,xmm3
4896 addps xmm0,xmm2
4897 movups dqword ptr [v],xmm0
4898 end;
4899 {$else}
4900 var t:TKraftVector3;
4901 begin
4902 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
4903 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
4904 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
4905 v:=t;
4906 end;
4907 {$endif}
4908
4909 procedure Vector3MatrixMulBasis(var v:TKraftVector3;const m:TKraftMatrix4x4); overload;
4910 var t:TKraftVector3;
4911 begin
4912 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
4913 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
4914 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
4915 v:=t;
4916 end;
4917
4918 procedure Vector3MatrixMulInverted(var v:TKraftVector3;const m:TKraftMatrix4x4); overload;
4919 var p,t:TKraftVector3;
4920 begin
4921 p.x:=v.x-m[3,0];
4922 p.y:=v.y-m[3,1];
4923 p.z:=v.z-m[3,2];
4924 t.x:=(m[0,0]*p.x)+(m[0,1]*p.y)+(m[0,2]*p.z);
4925 t.y:=(m[1,0]*p.x)+(m[1,1]*p.y)+(m[1,2]*p.z);
4926 t.z:=(m[2,0]*p.x)+(m[2,1]*p.y)+(m[2,2]*p.z);
4927 v:=t;
4928 end;
4929
4930 (*
4931 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
4932 const Mask:array[0..3] of longword=($ffffffff,$ffffffff,$ffffffff,$00000000);
4933 asm
4934 movups xmm6,dqword ptr [Mask]
4935 movups xmm0,dqword ptr [v] // d c b a
4936 movaps xmm1,xmm0 // d c b a
4937 movaps xmm2,xmm0 // d c b a
4938 shufps xmm0,xmm0,$00 // a a a a 00000000b
4939 shufps xmm1,xmm1,$55 // b b b b 01010101b
4940 shufps xmm2,xmm2,$aa // c c c c 10101010b
4941 movups xmm3,dqword ptr [m+0]
4942 movups xmm4,dqword ptr [m+12]
4943 andps xmm3,xmm6
4944 andps xmm4,xmm6
4945 movss xmm5,dword ptr [m+24]
4946 movss xmm6,dword ptr [m+28]
4947 movlhps xmm5,xmm6
4948 movss xmm6,dword ptr [m+32]
4949 shufps xmm5,xmm6,$88
4950 mulps xmm0,xmm3
4951 mulps xmm1,xmm4
4952 mulps xmm2,xmm5
4953 addps xmm0,xmm1
4954 addps xmm0,xmm2
4955 movups dqword ptr [result],xmm0
4956 end;
4957 {$else}
4958 begin
4959 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
4960 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
4961 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
4962 end;
4963 {$endif}
4964 (**)
4965
4966 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
4967 const cOne:array[0..3] of TKraftScalar=(0.0,0.0,0.0,1.0);
4968 asm
4969 movups xmm0,dqword ptr [v] // d c b a
4970 movaps xmm1,xmm0 // d c b a
4971 movaps xmm2,xmm0 // d c b a
4972 shufps xmm0,xmm0,$00 // a a a a 00000000b
4973 shufps xmm1,xmm1,$55 // b b b b 01010101b
4974 shufps xmm2,xmm2,$aa // c c c c 10101010b
4975 movups xmm3,dqword ptr [m+0]
4976 movups xmm4,dqword ptr [m+16]
4977 movups xmm5,dqword ptr [m+32]
4978 mulps xmm0,xmm3
4979 mulps xmm1,xmm4
4980 mulps xmm2,xmm5
4981 addps xmm0,xmm1
4982 addps xmm0,xmm2
4983 movups dqword ptr [result],xmm0
4984 end;
4985 {$else}
4986 begin
4987 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
4988 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
4989 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
4990 end;
4991 {$endif}
4992
4993 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
4994 const cOne:array[0..3] of TKraftScalar=(0.0,0.0,0.0,1.0);
4995 asm
4996 movups xmm0,dqword ptr [v] // d c b a
4997 movups xmm1,dqword ptr [Vector3Mask]
4998 movups xmm2,dqword ptr [cOne]
4999 andps xmm0,xmm1
5000 addps xmm0,xmm2
5001 movaps xmm1,xmm0 // d c b a
5002 movaps xmm2,xmm0 // d c b a
5003 movaps xmm3,xmm0 // d c b a
5004 shufps xmm0,xmm0,$00 // a a a a 00000000b
5005 shufps xmm1,xmm1,$55 // b b b b 01010101b
5006 shufps xmm2,xmm2,$aa // c c c c 10101010b
5007 shufps xmm3,xmm3,$ff // d d d d 11111111b
5008 movups xmm4,dqword ptr [m+0]
5009 movups xmm5,dqword ptr [m+16]
5010 movups xmm6,dqword ptr [m+32]
5011 movups xmm7,dqword ptr [m+48]
5012 mulps xmm0,xmm4
5013 mulps xmm1,xmm5
5014 mulps xmm2,xmm6
5015 mulps xmm3,xmm7
5016 addps xmm0,xmm1
5017 addps xmm2,xmm3
5018 addps xmm0,xmm2
5019 movups dqword ptr [result],xmm0
5020 end;
5021 {$else}
5022 begin
5023 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
5024 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
5025 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
5026 end;
5027 {$endif}
5028
5029 function Vector3TermMatrixMulInverse(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload;
5030 var Determinant:TKraftScalar;
5031 begin
5032 Determinant:=((m[0,0]*((m[1,1]*m[2,2])-(m[2,1]*m[1,2])))-
5033 (m[0,1]*((m[1,0]*m[2,2])-(m[2,0]*m[1,2]))))+
5034 (m[0,2]*((m[1,0]*m[2,1])-(m[2,0]*m[1,1])));
5035 if Determinant<>0.0 then begin
5036 Determinant:=1.0/Determinant;
5037 end;
5038 result.x:=((v.x*((m[1,1]*m[2,2])-(m[1,2]*m[2,1])))+(v.y*((m[1,2]*m[2,0])-(m[1,0]*m[2,2])))+(v.z*((m[1,0]*m[2,1])-(m[1,1]*m[2,0]))))*Determinant;
5039 result.y:=((m[0,0]*((v.y*m[2,2])-(v.z*m[2,1])))+(m[0,1]*((v.z*m[2,0])-(v.x*m[2,2])))+(m[0,2]*((v.x*m[2,1])-(v.y*m[2,0]))))*Determinant;
5040 result.z:=((m[0,0]*((m[1,1]*v.z)-(m[1,2]*v.y)))+(m[0,1]*((m[1,2]*v.x)-(m[1,0]*v.z)))+(m[0,2]*((m[1,0]*v.y)-(m[1,1]*v.x))))*Determinant;
5041 end;
5042
5043 function Vector3TermMatrixMulInverted(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
5044 var p:TKraftVector3;
5045 begin
5046 p.x:=v.x-m[3,0];
5047 p.y:=v.y-m[3,1];
5048 p.z:=v.z-m[3,2];
5049 result.x:=(m[0,0]*p.x)+(m[0,1]*p.y)+(m[0,2]*p.z);
5050 result.y:=(m[1,0]*p.x)+(m[1,1]*p.y)+(m[1,2]*p.z);
5051 result.z:=(m[2,0]*p.x)+(m[2,1]*p.y)+(m[2,2]*p.z);
5052 end;
5053
5054 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload;
5055 begin
5056 result.x:=(m[0,0]*v.x)+(m[0,1]*v.y)+(m[0,2]*v.z);
5057 result.y:=(m[1,0]*v.x)+(m[1,1]*v.y)+(m[1,2]*v.z);
5058 result.z:=(m[2,0]*v.x)+(m[2,1]*v.y)+(m[2,2]*v.z);
5059 end;
5060
5061 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
5062 begin
5063 result.x:=(m[0,0]*v.x)+(m[0,1]*v.y)+(m[0,2]*v.z)+m[0,3];
5064 result.y:=(m[1,0]*v.x)+(m[1,1]*v.y)+(m[1,2]*v.z)+m[1,3];
5065 result.z:=(m[2,0]*v.x)+(m[2,1]*v.y)+(m[2,2]*v.z)+m[2,3];
5066 end;
5067
5068 function Vector3TermMatrixMulTransposedBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
5069 begin
5070 result.x:=(m[0,0]*v.x)+(m[0,1]*v.y)+(m[0,2]*v.z);
5071 result.y:=(m[1,0]*v.x)+(m[1,1]*v.y)+(m[1,2]*v.z);
5072 result.z:=(m[2,0]*v.x)+(m[2,1]*v.y)+(m[2,2]*v.z);
5073 end;
5074
5075 function Vector3TermMatrixMulHomogen(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3;
5076 var result_w:TKraftScalar;
5077 begin
5078 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
5079 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
5080 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
5081 result_w:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+m[3,3];
5082 result.x:=result.x/result_w;
5083 result.y:=result.y/result_w;
5084 result.z:=result.z/result_w;
5085 end;
5086
5087 function Vector3TermMatrixMulBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef CPU386ASMForSinglePrecision}assembler;
5088 const Mask:array[0..3] of longword=($ffffffff,$ffffffff,$ffffffff,$00000000);
5089 asm
5090 movups xmm0,dqword ptr [v] // d c b a
5091 movaps xmm1,xmm0 // d c b a
5092 movaps xmm2,xmm0 // d c b a
5093 shufps xmm0,xmm0,$00 // a a a a 00000000b
5094 shufps xmm1,xmm1,$55 // b b b b 01010101b
5095 shufps xmm2,xmm2,$aa // c c c c 10101010b
5096 movups xmm3,dqword ptr [m+0]
5097 movups xmm4,dqword ptr [m+16]
5098 movups xmm5,dqword ptr [m+32]
5099 movups xmm6,dqword ptr [Mask]
5100 andps xmm3,xmm6
5101 andps xmm4,xmm6
5102 andps xmm5,xmm6
5103 mulps xmm0,xmm3
5104 mulps xmm1,xmm4
5105 mulps xmm2,xmm5
5106 addps xmm0,xmm1
5107 addps xmm0,xmm2
5108 movups dqword ptr [result],xmm0
5109 end;
5110 {$else}
5111 begin
5112 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
5113 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
5114 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
5115 end;
5116 {$endif}
5117
5118 function Vector3Lerp(const v1,v2:TKraftVector3;w:TKraftScalar):TKraftVector3;
5119 var iw:TKraftScalar;
5120 begin
5121 if w<0.0 then begin
5122 result:=v1;
5123 end else if w>1.0 then begin
5124 result:=v2;
5125 end else begin
5126 iw:=1.0-w;
5127 result.x:=(iw*v1.x)+(w*v2.x);
5128 result.y:=(iw*v1.y)+(w*v2.y);
5129 result.z:=(iw*v1.z)+(w*v2.z);
5130 end;
5131 end;
5132
5133 function Vector3Perpendicular(v:TKraftVector3):TKraftVector3;
5134 var p:TKraftVector3;
5135 begin
5136 Vector3NormalizeEx(v);
5137 p.x:=abs(v.x);
5138 p.y:=abs(v.y);
5139 p.z:=abs(v.z);
5140 if (p.x<=p.y) and (p.x<=p.z) then begin
5141 p:=Vector3XAxis;
5142 end else if (p.y<=p.x) and (p.y<=p.z) then begin
5143 p:=Vector3YAxis;
5144 end else begin
5145 p:=Vector3ZAxis;
5146 end;
5147 result:=Vector3NormEx(Vector3Sub(p,Vector3ScalarMul(v,Vector3Dot(v,p))));
5148 end;
5149
5150 function Vector3TermQuaternionRotate(const v:TKraftVector3;const q:TKraftQuaternion):TKraftVector3; {$ifdef CPU386ASMForSinglePrecision}assembler;
5151 const Mask:array[0..3] of longword=($ffffffff,$ffffffff,$ffffffff,$00000000);
5152 var t,qv:TKraftVector3;
5153 asm
5154
5155 movups xmm4,dqword ptr [q] // xmm4 = q.xyzw
5156
5157 movups xmm5,dqword ptr [v] // xmm5 = v.xyz?
5158
5159 movaps xmm6,xmm4
5160 shufps xmm6,xmm6,$ff // xmm6 = q.wwww
5161
5162 movups xmm7,dqword ptr [Mask] // xmm7 = Mask
5163
5164 andps xmm4,xmm7 // xmm4 = q.xyz0
5165
5166 andps xmm5,xmm7 // xmm5 = v.xyz0
5167
5168 // t:=Vector3ScalarMul(Vector3Cross(qv,v),2.0);
5169 movaps xmm0,xmm4 // xmm4 = qv
5170 movaps xmm1,xmm5 // xmm5 = v
5171 movaps xmm2,xmm4 // xmm4 = qv
5172 movaps xmm3,xmm5 // xmm5 = v
5173 shufps xmm0,xmm0,$12
5174 shufps xmm1,xmm1,$09
5175 shufps xmm2,xmm2,$09
5176 shufps xmm3,xmm3,$12
5177 mulps xmm0,xmm1
5178 mulps xmm2,xmm3
5179 subps xmm2,xmm0
5180 addps xmm2,xmm2
5181
5182 // xmm6 = Vector3Add(v,Vector3ScalarMul(t,q.w))
5183 mulps xmm6,xmm2 // xmm6 = q.wwww, xmm2 = t
5184 addps xmm6,xmm5 // xmm5 = v
5185
5186 // Vector3Cross(qv,t)
5187 movaps xmm1,xmm4 // xmm4 = qv
5188 movaps xmm3,xmm2 // xmm2 = t
5189 shufps xmm4,xmm4,$12
5190 shufps xmm2,xmm2,$09
5191 shufps xmm1,xmm1,$09
5192 shufps xmm3,xmm3,$12
5193 mulps xmm4,xmm2
5194 mulps xmm1,xmm3
5195 subps xmm1,xmm4
5196
5197 // result:=Vector3Add(Vector3Add(v,Vector3ScalarMul(t,q.w)),Vector3Cross(qv,t));
5198 addps xmm1,xmm6
5199
5200 movups dqword ptr [result],xmm1
5201
5202 end;
5203 {$else}
5204 var t,qv:TKraftVector3;
5205 begin
5206 // t = 2 * cross(q.xyz, v)
5207 // v' = v + q.w * t + cross(q.xyz, t)
5208 qv.x:=q.x;
5209 qv.y:=q.y;
5210 qv.z:=q.z;
5211 qv.w:=0.0;
5212 t:=Vector3ScalarMul(Vector3Cross(qv,v),2.0);
5213 result:=Vector3Add(Vector3Add(v,Vector3ScalarMul(t,q.w)),Vector3Cross(qv,t));
5214 end;
5215 {$endif}
5216
5217 function Vector3ProjectToBounds(const v:TKraftVector3;const MinVector,MaxVector:TKraftVector3):TKraftScalar;
5218 begin
5219 if v.x<0.0 then begin
5220 result:=v.x*MaxVector.x;
5221 end else begin
5222 result:=v.x*MinVector.x;
5223 end;
5224 if v.y<0.0 then begin
5225 result:=result+(v.y*MaxVector.y);
5226 end else begin
5227 result:=result+(v.y*MinVector.y);
5228 end;
5229 if v.z<0.0 then begin
5230 result:=result+(v.z*MaxVector.z);
5231 end else begin
5232 result:=result+(v.z*MinVector.z);
5233 end;
5234 end;
5235 {$else}
5236 function Vector3Flip(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5237 begin
5238 result.x:=v.x;
5239 result.y:=v.z;
5240 result.z:=-v.y;
5241 end;
5242
5243 function Vector3Abs(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5244 begin
5245 result.x:=abs(v.x);
5246 result.y:=abs(v.y);
5247 result.z:=abs(v.z);
5248 end;
5249
5250 function Vector3Compare(const v1,v2:TKraftVector3):boolean; {$ifdef caninline}inline;{$endif}
5251 begin
5252 result:=(abs(v1.x-v2.x)<EPSILON) and (abs(v1.y-v2.y)<EPSILON) and (abs(v1.z-v2.z)<EPSILON);
5253 end;
5254
5255 function Vector3CompareEx(const v1,v2:TKraftVector3;const Threshold:TKraftScalar=EPSILON):boolean; {$ifdef caninline}inline;{$endif}
5256 begin
5257 result:=(abs(v1.x-v2.x)<Threshold) and (abs(v1.y-v2.y)<Threshold) and (abs(v1.z-v2.z)<Threshold);
5258 end;
5259
5260 function Vector3DirectAdd(var v1:TKraftVector3;const v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5261 begin
5262 v1.x:=v1.x+v2.x;
5263 v1.y:=v1.y+v2.y;
5264 v1.z:=v1.z+v2.z;
5265 end;
5266
5267 function Vector3DirectSub(var v1:TKraftVector3;const v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5268 begin
5269 v1.x:=v1.x-v2.x;
5270 v1.y:=v1.y-v2.y;
5271 v1.z:=v1.z-v2.z;
5272 end;
5273
5274 function Vector3Add(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5275 begin
5276 result.x:=v1.x+v2.x;
5277 result.y:=v1.y+v2.y;
5278 result.z:=v1.z+v2.z;
5279 end;
5280
5281 function Vector3Sub(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5282 begin
5283 result.x:=v1.x-v2.x;
5284 result.y:=v1.y-v2.y;
5285 result.z:=v1.z-v2.z;
5286 end;
5287
5288 function Vector3Avg(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5289 begin
5290 result.x:=(v1.x+v2.x)*0.5;
5291 result.y:=(v1.y+v2.y)*0.5;
5292 result.z:=(v1.z+v2.z)*0.5;
5293 end;
5294
5295 function Vector3Avg(const v1,v2,v3:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5296 begin
5297 result.x:=(v1.x+v2.x+v3.x)/3.0;
5298 result.y:=(v1.y+v2.y+v3.y)/3.0;
5299 result.z:=(v1.z+v2.z+v3.z)/3.0;
5300 end;
5301
5302 function Vector3Avg(const va:PKraftVector3s;Count:longint):TKraftVector3; {$ifdef caninline}inline;{$endif}
5303 var i:longint;
5304 begin
5305 result.x:=0.0;
5306 result.y:=0.0;
5307 result.z:=0.0;
5308 if Count>0 then begin
5309 for i:=0 to Count-1 do begin
5310 result.x:=result.x+va^[i].x;
5311 result.y:=result.y+va^[i].y;
5312 result.z:=result.z+va^[i].z;
5313 end;
5314 result.x:=result.x/Count;
5315 result.y:=result.y/Count;
5316 result.z:=result.z/Count;
5317 end;
5318 end;
5319
5320 function Vector3ScalarMul(const v:TKraftVector3;const s:TKraftScalar):TKraftVector3; {$ifdef caninline}inline;{$endif}
5321 begin
5322 result.x:=v.x*s;
5323 result.y:=v.y*s;
5324 result.z:=v.z*s;
5325 end;
5326
5327 function Vector3Dot(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5328 begin
5329 result:=(v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z);
5330 end;
5331
5332 function Vector3Cos(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5333 var d:extended;
5334 begin
5335 d:=SQRT(Vector3LengthSquared(v1)*Vector3LengthSquared(v2));
5336 if d<>0.0 then begin
5337 result:=((v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z))/d; //result:=Vector3Dot(v1,v2)/d;
5338 end else begin
5339 result:=0.0;
5340 end
5341 end;
5342
5343 function Vector3GetOneUnitOrthogonalVector(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5344 var MinimumAxis:longint;
5345 l:TKraftScalar;
5346 begin
5347 if abs(v.x)<abs(v.y) then begin
5348 if abs(v.x)<abs(v.z) then begin
5349 MinimumAxis:=0;
5350 end else begin
5351 MinimumAxis:=2;
5352 end;
5353 end else begin
5354 if abs(v.y)<abs(v.z) then begin
5355 MinimumAxis:=1;
5356 end else begin
5357 MinimumAxis:=2;
5358 end;
5359 end;
5360 case MinimumAxis of
5361 0:begin
5362 l:=sqrt(sqr(v.y)+sqr(v.z));
5363 result.x:=0.0;
5364 result.y:=-(v.z/l);
5365 result.z:=v.y/l;
5366 end;
5367 1:begin
5368 l:=sqrt(sqr(v.x)+sqr(v.z));
5369 result.x:=-(v.z/l);
5370 result.y:=0.0;
5371 result.z:=v.x/l;
5372 end;
5373 else begin
5374 l:=sqrt(sqr(v.x)+sqr(v.y));
5375 result.x:=-(v.y/l);
5376 result.y:=v.x/l;
5377 result.z:=0.0;
5378 end;
5379 end;
5380 end;
5381
5382 function Vector3Cross(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5383 begin
5384 result.x:=(v1.y*v2.z)-(v1.z*v2.y);
5385 result.y:=(v1.z*v2.x)-(v1.x*v2.z);
5386 result.z:=(v1.x*v2.y)-(v1.y*v2.x);
5387 end;
5388
5389 function Vector3Neg(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5390 begin
5391 result.x:=-v.x;
5392 result.y:=-v.y;
5393 result.z:=-v.z;
5394 end;
5395
5396 procedure Vector3Scale(var v:TKraftVector3;const sx,sy,sz:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
5397 begin
5398 v.x:=v.x*sx;
5399 v.y:=v.y*sy;
5400 v.z:=v.z*sz;
5401 end;
5402
5403 procedure Vector3Scale(var v:TKraftVector3;const s:TKraftScalar); overload; {$ifdef caninline}inline;{$endif}
5404 begin
5405 v.x:=v.x*s;
5406 v.y:=v.y*s;
5407 v.z:=v.z*s;
5408 end;
5409
5410 function Vector3Mul(const v1,v2:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5411 begin
5412 result.x:=v1.x*v2.x;
5413 result.y:=v1.y*v2.y;
5414 result.z:=v1.z*v2.z;
5415 end;
5416
5417 function Vector3Length(const v:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5418 begin
5419 result:=sqrt(sqr(v.x)+sqr(v.y)+sqr(v.z));
5420 end;
5421
5422 function Vector3Dist(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5423 begin
5424 result:=sqrt(sqr(v2.x-v1.x)+sqr(v2.y-v1.y)+sqr(v2.z-v1.z));
5425 end;
5426
5427 function Vector3LengthSquared(const v:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5428 begin
5429 result:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5430 end;
5431
5432 function Vector3DistSquared(const v1,v2:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5433 begin
5434 result:=sqr(v2.x-v1.x)+sqr(v2.y-v1.y)+sqr(v2.z-v1.z);
5435 end;
5436
5437 function Vector3Angle(const v1,v2,v3:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5438 var A1,A2:TKraftVector3;
5439 L1,L2:TKraftScalar;
5440 begin
5441 A1:=Vector3Sub(v1,v2);
5442 A2:=Vector3Sub(v3,v2);
5443 L1:=Vector3Length(A1);
5444 L2:=Vector3Length(A2);
5445 if (L1=0) or (L2=0) then begin
5446 result:=0;
5447 end else begin
5448 result:=ArcCos(Vector3Dot(A1,A2)/(L1*L2));
5449 end;
5450 end;
5451
5452 function Vector3LengthNormalize(var v:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5453 var l:TKraftScalar;
5454 begin
5455 result:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5456 if result>0.0 then begin
5457 result:=sqrt(result);
5458 l:=1.0/result;
5459 v.x:=v.x*l;
5460 v.y:=v.y*l;
5461 v.z:=v.z*l;
5462 end else begin
5463 result:=0.0;
5464 v.x:=0.0;
5465 v.y:=0.0;
5466 v.z:=0.0;
5467 end;
5468 end;
5469
5470 procedure Vector3Normalize(var v:TKraftVector3); {$ifdef caninline}inline;{$endif}
5471 var l:TKraftScalar;
5472 begin
5473 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5474 if l>0.0 then begin
5475 l:=1.0/sqrt(l);
5476 v.x:=v.x*l;
5477 v.y:=v.y*l;
5478 v.z:=v.z*l;
5479 end else begin
5480 v.x:=0.0;
5481 v.y:=0.0;
5482 v.z:=0.0;
5483 end;
5484 end;
5485
5486 procedure Vector3NormalizeEx(var v:TKraftVector3); {$ifdef caninline}inline;{$endif}
5487 var l:single;
5488 begin
5489 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5490 if l>0.0 then begin
5491 l:=sqrt(l);
5492 v.x:=v.x/l;
5493 v.y:=v.y/l;
5494 v.z:=v.z/l;
5495 end else begin
5496 v.x:=0.0;
5497 v.y:=0.0;
5498 v.z:=0.0;
5499 end;
5500 end;
5501
5502 function Vector3SafeNorm(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5503 var l:TKraftScalar;
5504 begin
5505 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5506 if l>0.0 then begin
5507 l:=1.0/sqrt(l);
5508 result.x:=v.x*l;
5509 result.y:=v.y*l;
5510 result.z:=v.z*l;
5511 end else begin
5512 result.x:=1.0;
5513 result.y:=0.0;
5514 result.z:=0.0;
5515 end;
5516 end;
5517
5518 function Vector3Norm(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5519 var l:TKraftScalar;
5520 begin
5521 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5522 if l>0.0 then begin
5523 l:=1.0/sqrt(l);
5524 result.x:=v.x*l;
5525 result.y:=v.y*l;
5526 result.z:=v.z*l;
5527 end else begin
5528 result.x:=0.0;
5529 result.y:=0.0;
5530 result.z:=0.0;
5531 end;
5532 end;
5533
5534 function Vector3NormEx(const v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5535 var l:TKraftScalar;
5536 begin
5537 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
5538 if l>0.0 then begin
5539 l:=sqrt(l);
5540 result.x:=v.x/l;
5541 result.y:=v.y/l;
5542 result.z:=v.z/l;
5543 end else begin
5544 result.x:=0.0;
5545 result.y:=0.0;
5546 result.z:=0.0;
5547 end;
5548 end;
5549
5550 procedure Vector3RotateX(var v:TKraftVector3;a:TKraftScalar); {$ifdef caninline}inline;{$endif}
5551 var t:TKraftVector3;
5552 begin
5553 t.x:=v.x;
5554 t.y:=(v.y*cos(a))-(v.z*sin(a));
5555 t.z:=(v.y*sin(a))+(v.z*cos(a));
5556 v:=t;
5557 end;
5558
5559 procedure Vector3RotateY(var v:TKraftVector3;a:TKraftScalar); {$ifdef caninline}inline;{$endif}
5560 var t:TKraftVector3;
5561 begin
5562 t.x:=(v.x*cos(a))+(v.z*sin(a));
5563 t.y:=v.y;
5564 t.z:=(v.z*cos(a))-(v.x*sin(a));
5565 v:=t;
5566 end;
5567
5568 procedure Vector3RotateZ(var v:TKraftVector3;a:TKraftScalar); {$ifdef caninline}inline;{$endif}
5569 var t:TKraftVector3;
5570 begin
5571 t.x:=(v.x*cos(a))-(v.y*sin(a));
5572 t.y:=(v.x*sin(a))+(v.y*cos(a));
5573 t.z:=v.z;
5574 v:=t;
5575 end;
5576
5577 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix3x3); overload; {$ifdef caninline}inline;{$endif}
5578 var t:TKraftVector3;
5579 begin
5580 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
5581 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
5582 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
5583 v:=t;
5584 end;
5585
5586 procedure Vector3MatrixMul(var v:TKraftVector3;const m:TKraftMatrix4x4); overload;
5587 var t:TKraftVector3;
5588 begin
5589 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
5590 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
5591 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
5592 v:=t;
5593 end;
5594
5595 procedure Vector3MatrixMulBasis(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef caninline}inline;{$endif}
5596 var t:TKraftVector3;
5597 begin
5598 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
5599 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
5600 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
5601 v:=t;
5602 end;
5603
5604 procedure Vector3MatrixMulInverted(var v:TKraftVector3;const m:TKraftMatrix4x4); overload; {$ifdef caninline}inline;{$endif}
5605 var p,t:TKraftVector3;
5606 begin
5607 p.x:=v.x-m[3,0];
5608 p.y:=v.y-m[3,1];
5609 p.z:=v.z-m[3,2];
5610 t.x:=(m[0,0]*p.x)+(m[0,1]*p.y)+(m[0,2]*p.z);
5611 t.y:=(m[1,0]*p.x)+(m[1,1]*p.y)+(m[1,2]*p.z);
5612 t.z:=(m[2,0]*p.x)+(m[2,1]*p.y)+(m[2,2]*p.z);
5613 v:=t;
5614 end;
5615
5616 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
5617 begin
5618 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
5619 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
5620 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
5621 end;
5622
5623 function Vector3TermMatrixMulInverse(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
5624 var Determinant:TKraftScalar;
5625 begin
5626 Determinant:=((m[0,0]*((m[1,1]*m[2,2])-(m[2,1]*m[1,2])))-
5627 (m[0,1]*((m[1,0]*m[2,2])-(m[2,0]*m[1,2]))))+
5628 (m[0,2]*((m[1,0]*m[2,1])-(m[2,0]*m[1,1])));
5629 if Determinant<>0.0 then begin
5630 Determinant:=1.0/Determinant;
5631 end;
5632 result.x:=((v.x*((m[1,1]*m[2,2])-(m[1,2]*m[2,1])))+(v.y*((m[1,2]*m[2,0])-(m[1,0]*m[2,2])))+(v.z*((m[1,0]*m[2,1])-(m[1,1]*m[2,0]))))*Determinant;
5633 result.y:=((m[0,0]*((v.y*m[2,2])-(v.z*m[2,1])))+(m[0,1]*((v.z*m[2,0])-(v.x*m[2,2])))+(m[0,2]*((v.x*m[2,1])-(v.y*m[2,0]))))*Determinant;
5634 result.z:=((m[0,0]*((m[1,1]*v.z)-(m[1,2]*v.y)))+(m[0,1]*((m[1,2]*v.x)-(m[1,0]*v.z)))+(m[0,2]*((m[1,0]*v.y)-(m[1,1]*v.x))))*Determinant;
5635 end;
5636
5637 function Vector3TermMatrixMulInverted(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
5638 var p:TKraftVector3;
5639 begin
5640 p.x:=v.x-m[3,0];
5641 p.y:=v.y-m[3,1];
5642 p.z:=v.z-m[3,2];
5643 result.x:=(m[0,0]*p.x)+(m[0,1]*p.y)+(m[0,2]*p.z);
5644 result.y:=(m[1,0]*p.x)+(m[1,1]*p.y)+(m[1,2]*p.z);
5645 result.z:=(m[2,0]*p.x)+(m[2,1]*p.y)+(m[2,2]*p.z);
5646 end;
5647
5648 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix3x3):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
5649 begin
5650 result.x:=(m[0,0]*v.x)+(m[0,1]*v.y)+(m[0,2]*v.z);
5651 result.y:=(m[1,0]*v.x)+(m[1,1]*v.y)+(m[1,2]*v.z);
5652 result.z:=(m[2,0]*v.x)+(m[2,1]*v.y)+(m[2,2]*v.z);
5653 end;
5654
5655 function Vector3TermMatrixMulTransposed(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
5656 begin
5657 result.x:=(m[0,0]*v.x)+(m[0,1]*v.y)+(m[0,2]*v.z)+m[0,3];
5658 result.y:=(m[1,0]*v.x)+(m[1,1]*v.y)+(m[1,2]*v.z)+m[1,3];
5659 result.z:=(m[2,0]*v.x)+(m[2,1]*v.y)+(m[2,2]*v.z)+m[2,3];
5660 end;
5661
5662 function Vector3TermMatrixMulTransposedBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload; {$ifdef caninline}inline;{$endif}
5663 begin
5664 result.x:=(m[0,0]*v.x)+(m[0,1]*v.y)+(m[0,2]*v.z);
5665 result.y:=(m[1,0]*v.x)+(m[1,1]*v.y)+(m[1,2]*v.z);
5666 result.z:=(m[2,0]*v.x)+(m[2,1]*v.y)+(m[2,2]*v.z);
5667 end;
5668
5669 function Vector3TermMatrixMulHomogen(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; {$ifdef caninline}inline;{$endif}
5670 var result_w:TKraftScalar;
5671 begin
5672 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
5673 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
5674 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
5675 result_w:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+m[3,3];
5676 result.x:=result.x/result_w;
5677 result.y:=result.y/result_w;
5678 result.z:=result.z/result_w;
5679 end;
5680
5681 function Vector3TermMatrixMulBasis(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; {$ifdef caninline}inline;{$endif}
5682 begin
5683 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z);
5684 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z);
5685 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z);
5686 end;
5687
5688 function Vector3TermMatrixMul(const v:TKraftVector3;const m:TKraftMatrix4x4):TKraftVector3; overload;
5689 begin
5690 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
5691 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
5692 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
5693 end;
5694
5695 function Vector3Lerp(const v1,v2:TKraftVector3;w:TKraftScalar):TKraftVector3; {$ifdef caninline}inline;{$endif}
5696 var iw:TKraftScalar;
5697 begin
5698 if w<0.0 then begin
5699 result:=v1;
5700 end else if w>1.0 then begin
5701 result:=v2;
5702 end else begin
5703 iw:=1.0-w;
5704 result.x:=(iw*v1.x)+(w*v2.x);
5705 result.y:=(iw*v1.y)+(w*v2.y);
5706 result.z:=(iw*v1.z)+(w*v2.z);
5707 end;
5708 end;
5709
5710 function Vector3Perpendicular(v:TKraftVector3):TKraftVector3; {$ifdef caninline}inline;{$endif}
5711 var p:TKraftVector3;
5712 begin
5713 Vector3NormalizeEx(v);
5714 p.x:=abs(v.x);
5715 p.y:=abs(v.y);
5716 p.z:=abs(v.z);
5717 if (p.x<=p.y) and (p.x<=p.z) then begin
5718 p:=Vector3XAxis;
5719 end else if (p.y<=p.x) and (p.y<=p.z) then begin
5720 p:=Vector3YAxis;
5721 end else begin
5722 p:=Vector3ZAxis;
5723 end;
5724 result:=Vector3NormEx(Vector3Sub(p,Vector3ScalarMul(v,Vector3Dot(v,p))));
5725 end;
5726
5727 function Vector3TermQuaternionRotate(const v:TKraftVector3;const q:TKraftQuaternion):TKraftVector3; {$ifdef caninline}inline;{$endif}
5728 var t,qv:TKraftVector3;
5729 begin
5730 // t = 2 * cross(q.xyz, v)
5731 // v' = v + q.w * t + cross(q.xyz, t)
5732 qv:=PKraftVector3(pointer(@q))^;
5733 t:=Vector3ScalarMul(Vector3Cross(qv,v),2.0);
5734 result:=Vector3Add(Vector3Add(v,Vector3ScalarMul(t,q.w)),Vector3Cross(qv,t));
5735 end;
5736 {var vn:TKraftVector3;
5737 vq,rq:TKraftQuaternion;
5738 begin
5739 vq.x:=vn.x;
5740 vq.y:=vn.y;
5741 vq.z:=vn.z;
5742 vq.w:=0.0;
5743 rq:=QuaternionMul(q,QuaternionMul(vq,QuaternionConjugate(q)));
5744 result.x:=rq.x;
5745 result.y:=rq.y;
5746 result.z:=rq.z;
5747 end;{}
5748
5749 function Vector3ProjectToBounds(const v:TKraftVector3;const MinVector,MaxVector:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
5750 begin
5751 if v.x<0.0 then begin
5752 result:=v.x*MaxVector.x;
5753 end else begin
5754 result:=v.x*MinVector.x;
5755 end;
5756 if v.y<0.0 then begin
5757 result:=result+(v.y*MaxVector.y);
5758 end else begin
5759 result:=result+(v.y*MinVector.y);
5760 end;
5761 if v.z<0.0 then begin
5762 result:=result+(v.z*MaxVector.z);
5763 end else begin
5764 result:=result+(v.z*MinVector.z);
5765 end;
5766 end;
5767 {$endif}
5768
5769 function Vector4Compare(const v1,v2:TKraftVector4):boolean;
5770 begin
5771 result:=(abs(v1.x-v2.x)<EPSILON) and (abs(v1.y-v2.y)<EPSILON) and (abs(v1.z-v2.z)<EPSILON) and (abs(v1.w-v2.w)<EPSILON);
5772 end;
5773
5774 function Vector4CompareEx(const v1,v2:TKraftVector4;const Threshold:TKraftScalar=EPSILON):boolean;
5775 begin
5776 result:=(abs(v1.x-v2.x)<Threshold) and (abs(v1.y-v2.y)<Threshold) and (abs(v1.z-v2.z)<Threshold) and (abs(v1.w-v2.w)<Threshold);
5777 end;
5778
5779 function Vector4Add(const v1,v2:TKraftVector4):TKraftVector4;
5780 begin
5781 result.x:=v1.x+v2.x;
5782 result.y:=v1.y+v2.y;
5783 result.z:=v1.z+v2.z;
5784 result.w:=v1.w+v2.w;
5785 end;
5786
5787 function Vector4Sub(const v1,v2:TKraftVector4):TKraftVector4;
5788 begin
5789 result.x:=v1.x-v2.x;
5790 result.y:=v1.y-v2.y;
5791 result.z:=v1.z-v2.z;
5792 result.w:=v1.w-v2.w;
5793 end;
5794
5795 function Vector4ScalarMul(const v:TKraftVector4;s:TKraftScalar):TKraftVector4;
5796 begin
5797 result.x:=v.x*s;
5798 result.y:=v.y*s;
5799 result.z:=v.z*s;
5800 result.w:=v.w*s;
5801 end;
5802
5803 function Vector4Dot(const v1,v2:TKraftVector4):TKraftScalar;
5804 begin
5805 result:=(v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z)+(v1.w*v2.w);
5806 end;
5807
5808 function Vector4Cross(const v1,v2:TKraftVector4):TKraftVector4;
5809 begin
5810 result.x:=(v1.y*v2.z)-(v2.y*v1.z);
5811 result.y:=(v2.x*v1.z)-(v1.x*v2.z);
5812 result.z:=(v1.x*v2.y)-(v2.x*v1.y);
5813 result.w:=1;
5814 end;
5815
5816 function Vector4Neg(const v:TKraftVector4):TKraftVector4;
5817 begin
5818 result.x:=-v.x;
5819 result.y:=-v.y;
5820 result.z:=-v.z;
5821 result.w:=1;
5822 end;
5823
5824 procedure Vector4Scale(var v:TKraftVector4;sx,sy,sz:TKraftScalar); overload;
5825 begin
5826 v.x:=v.x*sx;
5827 v.y:=v.y*sy;
5828 v.z:=v.z*sz;
5829 end;
5830
5831 procedure Vector4Scale(var v:TKraftVector4;s:TKraftScalar); overload;
5832 begin
5833 v.x:=v.x*s;
5834 v.y:=v.y*s;
5835 v.z:=v.z*s;
5836 end;
5837
5838 function Vector4Mul(const v1,v2:TKraftVector4):TKraftVector4;
5839 begin
5840 result.x:=v1.x*v2.x;
5841 result.y:=v1.y*v2.y;
5842 result.z:=v1.z*v2.z;
5843 result.w:=1;
5844 end;
5845
5846 function Vector4Length(const v:TKraftVector4):TKraftScalar;
5847 begin
5848 result:=SQRT((v.x*v.x)+(v.y*v.y)+(v.z*v.z));
5849 end;
5850
5851 function Vector4Dist(const v1,v2:TKraftVector4):TKraftScalar;
5852 begin
5853 result:=Vector4Length(Vector4Sub(v2,v1));
5854 end;
5855
5856 function Vector4LengthSquared(const v:TKraftVector4):TKraftScalar;
5857 begin
5858 result:=sqr(v.x)+sqr(v.y)+sqr(v.z)+sqr(v.w);
5859 end;
5860
5861 function Vector4DistSquared(const v1,v2:TKraftVector4):TKraftScalar;
5862 begin
5863 result:=Vector4LengthSquared(Vector4Sub(v2,v1));
5864 end;
5865
5866 function Vector4Angle(const v1,v2,v3:TKraftVector4):TKraftScalar;
5867 var A1,A2:TKraftVector4;
5868 L1,L2:TKraftScalar;
5869 begin
5870 A1:=Vector4Sub(v1,v2);
5871 A2:=Vector4Sub(v3,v2);
5872 L1:=Vector4Length(A1);
5873 L2:=Vector4Length(A2);
5874 if (L1=0) or (L2=0) then begin
5875 result:=0;
5876 end else begin
5877 result:=ArcCos(Vector4Dot(A1,A2)/(L1*L2));
5878 end;
5879 end;
5880
5881 procedure Vector4Normalize(var v:TKraftVector4);
5882 var L:TKraftScalar;
5883 begin
5884 L:=Vector4Length(v);
5885 if L<>0.0 then begin
5886 Vector4Scale(v,1/L);
5887 end else begin
5888 v:=Vector4Origin;
5889 end;
5890 end;
5891
5892 function Vector4Norm(const v:TKraftVector4):TKraftVector4;
5893 var L:TKraftScalar;
5894 begin
5895 L:=Vector4Length(v);
5896 if L<>0.0 then begin
5897 result:=Vector4ScalarMul(v,1/L);
5898 end else begin
5899 result:=Vector4Origin;
5900 end;
5901 end;
5902
5903 procedure Vector4RotateX(var v:TKraftVector4;a:TKraftScalar);
5904 var t:TKraftVector4;
5905 begin
5906 t.x:=v.x;
5907 t.y:=(v.y*cos(a))+(v.z*-sin(a));
5908 t.z:=(v.y*sin(a))+(v.z*cos(a));
5909 t.w:=1;
5910 v:=t;
5911 end;
5912
5913 procedure Vector4RotateY(var v:TKraftVector4;a:TKraftScalar);
5914 var t:TKraftVector4;
5915 begin
5916 t.x:=(v.x*cos(a))+(v.z*sin(a));
5917 t.y:=v.y;
5918 t.z:=(v.x*-sin(a))+(v.z*cos(a));
5919 t.w:=1;
5920 v:=t;
5921 end;
5922
5923 procedure Vector4RotateZ(var v:TKraftVector4;a:TKraftScalar);
5924 var t:TKraftVector4;
5925 begin
5926 t.x:=(v.x*cos(a))+(v.y*-sin(a));
5927 t.y:=(v.x*sin(a))+(v.y*cos(a));
5928 t.z:=v.z;
5929 t.w:=1;
5930 v:=t;
5931 end;
5932
5933 procedure Vector4MatrixMul(var v:TKraftVector4;const m:TKraftMatrix4x4); {$ifdef CPU386ASMForSinglePrecision}register;
5934 asm
5935 {mov eax,v
5936 mov edx,m}
5937 movups xmm0,dqword ptr [v] // d c b a
5938 movaps xmm1,xmm0 // d c b a
5939 movaps xmm2,xmm0 // d c b a
5940 movaps xmm3,xmm0 // d c b a
5941 shufps xmm0,xmm0,$00 // a a a a 00000000b
5942 shufps xmm1,xmm1,$55 // b b b b 01010101b
5943 shufps xmm2,xmm2,$aa // c c c c 10101010b
5944 shufps xmm3,xmm3,$ff // d d d d 11111111b
5945 movups xmm4,dqword ptr [m+0]
5946 movups xmm5,dqword ptr [m+16]
5947 movups xmm6,dqword ptr [m+32]
5948 movups xmm7,dqword ptr [m+48]
5949 mulps xmm0,xmm4
5950 mulps xmm1,xmm5
5951 mulps xmm2,xmm6
5952 mulps xmm3,xmm7
5953 addps xmm0,xmm1
5954 addps xmm2,xmm3
5955 addps xmm0,xmm2
5956 movups dqword ptr [v],xmm0
5957 end;
5958 {$else}
5959 var t:TKraftVector4;
5960 begin
5961 t.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+(m[3,0]*v.w);
5962 t.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+(m[3,1]*v.w);
5963 t.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+(m[3,2]*v.w);
5964 t.w:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+(m[3,3]*v.w);
5965 v:=t;
5966 end;
5967 {$endif}
5968
5969 function Vector4TermMatrixMul(const v:TKraftVector4;const m:TKraftMatrix4x4):TKraftVector4; {$ifdef CPU386ASMForSinglePrecision}register;
5970 asm
5971 {mov eax,v
5972 mov edx,m
5973 mov ecx,result}
5974 movups xmm0,[eax] // d c b a
5975 movaps xmm1,xmm0 // d c b a
5976 movaps xmm2,xmm0 // d c b a
5977 movaps xmm3,xmm0 // d c b a
5978 shufps xmm0,xmm0,$00 // a a a a 00000000b
5979 shufps xmm1,xmm1,$55 // b b b b 01010101b
5980 shufps xmm2,xmm2,$aa // c c c c 10101010b
5981 shufps xmm3,xmm3,$ff // d d d d 11111111b
5982 movups xmm4,[edx+0]
5983 movups xmm5,[edx+16]
5984 movups xmm6,[edx+32]
5985 movups xmm7,[edx+48]
5986 mulps xmm0,xmm4
5987 mulps xmm1,xmm5
5988 mulps xmm2,xmm6
5989 mulps xmm3,xmm7
5990 addps xmm0,xmm1
5991 addps xmm2,xmm3
5992 addps xmm0,xmm2
5993 movups [ecx],xmm0
5994 end;
5995 {$else}
5996 begin
5997 result.x:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+(m[3,0]*v.w);
5998 result.y:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+(m[3,1]*v.w);
5999 result.z:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+(m[3,2]*v.w);
6000 result.w:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+(m[3,3]*v.w);
6001 end;
6002 {$endif}
6003
6004 function Vector4TermMatrixMulHomogen(const v:TKraftVector4;const m:TKraftMatrix4x4):TKraftVector4;
6005 begin
6006 result.w:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+(m[3,3]*v.w);
6007 result.x:=((m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+(m[3,0]*v.w))/result.w;
6008 result.y:=((m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+(m[3,1]*v.w))/result.w;
6009 result.z:=((m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+(m[3,2]*v.w))/result.w;
6010 result.w:=1.0;
6011 end;
6012
6013 procedure Vector4Rotate(var v:TKraftVector4;const Axis:TKraftVector4;a:TKraftScalar);
6014 var t:TKraftVector3;
6015 begin
6016 t.x:=Axis.x;
6017 t.y:=Axis.y;
6018 t.z:=Axis.z;
6019 Vector4MatrixMul(v,Matrix4x4Rotate(a,t));
6020 end;
6021
6022 function Vector4Lerp(const v1,v2:TKraftVector4;w:TKraftScalar):TKraftVector4;
6023 var iw:TKraftScalar;
6024 begin
6025 if w<0.0 then begin
6026 result:=v1;
6027 end else if w>1.0 then begin
6028 result:=v2;
6029 end else begin
6030 iw:=1.0-w;
6031 result.x:=(iw*v1.x)+(w*v2.x);
6032 result.y:=(iw*v1.y)+(w*v2.y);
6033 result.z:=(iw*v1.z)+(w*v2.z);
6034 result.w:=(iw*v1.w)+(w*v2.w);
6035 end;
6036 end;
6037
6038 function Matrix2x2Inverse(var mr:TKraftMatrix2x2;const ma:TKraftMatrix2x2):boolean;
6039 var Determinant:TKraftScalar;
6040 begin
6041 Determinant:=(ma[0,0]*ma[1,1])-(ma[0,1]*ma[1,0]);
6042 if abs(Determinant)<EPSILON then begin
6043 mr:=Matrix2x2Identity;
6044 result:=false;
6045 end else begin
6046 Determinant:=1.0/Determinant;
6047 mr[0,0]:=ma[1,1]*Determinant;
6048 mr[0,1]:=-(ma[0,1]*Determinant);
6049 mr[1,0]:=-(ma[1,0]*Determinant);
6050 mr[1,1]:=ma[0,0]*Determinant;
6051 result:=true;
6052 end;
6053 end;
6054
6055 function Matrix2x2TermInverse(const m:TKraftMatrix2x2):TKraftMatrix2x2;
6056 var Determinant:TKraftScalar;
6057 begin
6058 Determinant:=(m[0,0]*m[1,1])-(m[0,1]*m[1,0]);
6059 if abs(Determinant)<EPSILON then begin
6060 result:=Matrix2x2Identity;
6061 end else begin
6062 Determinant:=1.0/Determinant;
6063 result[0,0]:=m[1,1]*Determinant;
6064 result[0,1]:=-(m[0,1]*Determinant);
6065 result[1,0]:=-(m[1,0]*Determinant);
6066 result[1,1]:=m[0,0]*Determinant;
6067 end;
6068 end;
6069
6070 function Matrix3x3RotateX(Angle:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6071 begin
6072 result:=Matrix3x3Identity;
6073 result[1,1]:=cos(Angle);
6074 result[2,2]:=result[1,1];
6075 result[1,2]:=sin(Angle);
6076 result[2,1]:=-result[1,2];
6077 end;
6078
6079 function Matrix3x3RotateY(Angle:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6080 begin
6081 result:=Matrix3x3Identity;
6082 result[0,0]:=cos(Angle);
6083 result[2,2]:=result[0,0];
6084 result[0,2]:=-sin(Angle);
6085 result[2,0]:=-result[0,2];
6086 end;
6087
6088 function Matrix3x3RotateZ(Angle:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6089 begin
6090 result:=Matrix3x3Identity;
6091 result[0,0]:=cos(Angle);
6092 result[1,1]:=result[0,0];
6093 result[0,1]:=sin(Angle);
6094 result[1,0]:=-result[0,1];
6095 end;
6096
6097 function Matrix3x3Rotate(Angle:TKraftScalar;Axis:TKraftVector3):TKraftMatrix3x3; overload;
6098 var m:TKraftMatrix3x3;
6099 CosinusAngle,SinusAngle:TKraftScalar;
6100 begin
6101 m:=Matrix3x3Identity;
6102 CosinusAngle:=cos(Angle);
6103 SinusAngle:=sin(Angle);
6104 m[0,0]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.x));
6105 m[1,0]:=((1.0-CosinusAngle)*Axis.x*Axis.y)-(Axis.z*SinusAngle);
6106 m[2,0]:=((1.0-CosinusAngle)*Axis.x*Axis.z)+(Axis.y*SinusAngle);
6107 m[0,1]:=((1.0-CosinusAngle)*Axis.x*Axis.z)+(Axis.z*SinusAngle);
6108 m[1,1]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.y));
6109 m[2,1]:=((1.0-CosinusAngle)*Axis.y*Axis.z)-(Axis.x*SinusAngle);
6110 m[0,2]:=((1.0-CosinusAngle)*Axis.x*Axis.z)-(Axis.y*SinusAngle);
6111 m[1,2]:=((1.0-CosinusAngle)*Axis.y*Axis.z)+(Axis.x*SinusAngle);
6112 m[2,2]:=CosinusAngle+((1.0-CosinusAngle)*sqr(Axis.z));
6113 {$ifdef SIMD}
6114 m[0,3]:=0.0;
6115 m[1,3]:=0.0;
6116 m[2,3]:=0.0;
6117 {$endif}
6118 result:=m;
6119 end;
6120
6121 function Matrix3x3Scale(sx,sy,sz:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6122 begin
6123 result:=Matrix3x3Identity;
6124 result[0,0]:=sx;
6125 result[1,1]:=sy;
6126 result[2,2]:=sz;
6127 end;
6128
6129 procedure Matrix3x3Add(var m1:TKraftMatrix3x3;const m2:TKraftMatrix3x3); {$ifdef caninline}inline;{$endif}
6130 begin
6131 m1[0,0]:=m1[0,0]+m2[0,0];
6132 m1[0,1]:=m1[0,1]+m2[0,1];
6133 m1[0,2]:=m1[0,2]+m2[0,2];
6134 {$ifdef SIMD}
6135 m1[0,3]:=0.0;
6136 {$endif}
6137 m1[1,0]:=m1[1,0]+m2[1,0];
6138 m1[1,1]:=m1[1,1]+m2[1,1];
6139 m1[1,2]:=m1[1,2]+m2[1,2];
6140 {$ifdef SIMD}
6141 m1[1,3]:=0.0;
6142 {$endif}
6143 m1[2,0]:=m1[2,0]+m2[2,0];
6144 m1[2,1]:=m1[2,1]+m2[2,1];
6145 m1[2,2]:=m1[2,2]+m2[2,2];
6146 {$ifdef SIMD}
6147 m1[2,3]:=0.0;
6148 {$endif}
6149 end;
6150
6151 procedure Matrix3x3Sub(var m1:TKraftMatrix3x3;const m2:TKraftMatrix3x3); {$ifdef caninline}inline;{$endif}
6152 begin
6153 m1[0,0]:=m1[0,0]-m2[0,0];
6154 m1[0,1]:=m1[0,1]-m2[0,1];
6155 m1[0,2]:=m1[0,2]-m2[0,2];
6156 {$ifdef SIMD}
6157 m1[0,3]:=0.0;
6158 {$endif}
6159 m1[1,0]:=m1[1,0]-m2[1,0];
6160 m1[1,1]:=m1[1,1]-m2[1,1];
6161 m1[1,2]:=m1[1,2]-m2[1,2];
6162 {$ifdef SIMD}
6163 m1[1,3]:=0.0;
6164 {$endif}
6165 m1[2,0]:=m1[2,0]-m2[2,0];
6166 m1[2,1]:=m1[2,1]-m2[2,1];
6167 m1[2,2]:=m1[2,2]-m2[2,2];
6168 {$ifdef SIMD}
6169 m1[2,3]:=0.0;
6170 {$endif}
6171 end;
6172
6173 procedure Matrix3x3Mul(var m1:TKraftMatrix3x3;const m2:TKraftMatrix3x3);
6174 var t:TKraftMatrix3x3;
6175 begin
6176 t[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[1,0])+(m1[0,2]*m2[2,0]);
6177 t[0,1]:=(m1[0,0]*m2[0,1])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[2,1]);
6178 t[0,2]:=(m1[0,0]*m2[0,2])+(m1[0,1]*m2[1,2])+(m1[0,2]*m2[2,2]);
6179 {$ifdef SIMD}
6180 t[0,3]:=0.0;
6181 {$endif}
6182 t[1,0]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[1,0])+(m1[1,2]*m2[2,0]);
6183 t[1,1]:=(m1[1,0]*m2[0,1])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[2,1]);
6184 t[1,2]:=(m1[1,0]*m2[0,2])+(m1[1,1]*m2[1,2])+(m1[1,2]*m2[2,2]);
6185 {$ifdef SIMD}
6186 t[1,3]:=0.0;
6187 {$endif}
6188 t[2,0]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[1,0])+(m1[2,2]*m2[2,0]);
6189 t[2,1]:=(m1[2,0]*m2[0,1])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[2,1]);
6190 t[2,2]:=(m1[2,0]*m2[0,2])+(m1[2,1]*m2[1,2])+(m1[2,2]*m2[2,2]);
6191 {$ifdef SIMD}
6192 t[2,3]:=0.0;
6193 {$endif}
6194 m1:=t;
6195 end;
6196
6197 function Matrix3x3TermAdd(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6198 begin
6199 result[0,0]:=m1[0,0]+m2[0,0];
6200 result[0,1]:=m1[0,1]+m2[0,1];
6201 result[0,2]:=m1[0,2]+m2[0,2];
6202 {$ifdef SIMD}
6203 result[0,3]:=0.0;
6204 {$endif}
6205 result[1,0]:=m1[1,0]+m2[1,0];
6206 result[1,1]:=m1[1,1]+m2[1,1];
6207 result[1,2]:=m1[1,2]+m2[1,2];
6208 {$ifdef SIMD}
6209 result[1,3]:=0.0;
6210 {$endif}
6211 result[2,0]:=m1[2,0]+m2[2,0];
6212 result[2,1]:=m1[2,1]+m2[2,1];
6213 result[2,2]:=m1[2,2]+m2[2,2];
6214 {$ifdef SIMD}
6215 result[2,3]:=0.0;
6216 {$endif}
6217 end;
6218
6219 function Matrix3x3TermSub(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6220 begin
6221 result[0,0]:=m1[0,0]-m2[0,0];
6222 result[0,1]:=m1[0,1]-m2[0,1];
6223 result[0,2]:=m1[0,2]-m2[0,2];
6224 {$ifdef SIMD}
6225 result[0,3]:=0.0;
6226 {$endif}
6227 result[1,0]:=m1[1,0]-m2[1,0];
6228 result[1,1]:=m1[1,1]-m2[1,1];
6229 result[1,2]:=m1[1,2]-m2[1,2];
6230 {$ifdef SIMD}
6231 result[1,3]:=0.0;
6232 {$endif}
6233 result[2,0]:=m1[2,0]-m2[2,0];
6234 result[2,1]:=m1[2,1]-m2[2,1];
6235 result[2,2]:=m1[2,2]-m2[2,2];
6236 {$ifdef SIMD}
6237 result[2,3]:=0.0;
6238 {$endif}
6239 end;
6240
6241 function Matrix3x3TermMul(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3;
6242 begin
6243 result[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[1,0])+(m1[0,2]*m2[2,0]);
6244 result[0,1]:=(m1[0,0]*m2[0,1])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[2,1]);
6245 result[0,2]:=(m1[0,0]*m2[0,2])+(m1[0,1]*m2[1,2])+(m1[0,2]*m2[2,2]);
6246 {$ifdef SIMD}
6247 result[0,3]:=0.0;
6248 {$endif}
6249 result[1,0]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[1,0])+(m1[1,2]*m2[2,0]);
6250 result[1,1]:=(m1[1,0]*m2[0,1])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[2,1]);
6251 result[1,2]:=(m1[1,0]*m2[0,2])+(m1[1,1]*m2[1,2])+(m1[1,2]*m2[2,2]);
6252 {$ifdef SIMD}
6253 result[1,3]:=0.0;
6254 {$endif}
6255 result[2,0]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[1,0])+(m1[2,2]*m2[2,0]);
6256 result[2,1]:=(m1[2,0]*m2[0,1])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[2,1]);
6257 result[2,2]:=(m1[2,0]*m2[0,2])+(m1[2,1]*m2[1,2])+(m1[2,2]*m2[2,2]);
6258 {$ifdef SIMD}
6259 result[2,3]:=0.0;
6260 {$endif}
6261 end;
6262
6263 function Matrix3x3TermMulTranspose(const m1,m2:TKraftMatrix3x3):TKraftMatrix3x3;
6264 begin
6265 result[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[0,1])+(m1[0,2]*m2[0,2]);
6266 result[0,1]:=(m1[0,0]*m2[1,0])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[1,2]);
6267 result[0,2]:=(m1[0,0]*m2[2,0])+(m1[0,1]*m2[2,1])+(m1[0,2]*m2[2,2]);
6268 {$ifdef SIMD}
6269 result[0,3]:=0.0;
6270 {$endif}
6271 result[1,0]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[0,1])+(m1[1,2]*m2[0,2]);
6272 result[1,1]:=(m1[1,0]*m2[1,0])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[1,2]);
6273 result[1,2]:=(m1[1,0]*m2[2,0])+(m1[1,1]*m2[2,1])+(m1[1,2]*m2[2,2]);
6274 {$ifdef SIMD}
6275 result[1,3]:=0.0;
6276 {$endif}
6277 result[2,0]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[0,1])+(m1[2,2]*m2[0,2]);
6278 result[2,1]:=(m1[2,0]*m2[1,0])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[1,2]);
6279 result[2,2]:=(m1[2,0]*m2[2,0])+(m1[2,1]*m2[2,1])+(m1[2,2]*m2[2,2]);
6280 {$ifdef SIMD}
6281 result[2,3]:=0.0;
6282 {$endif}
6283 end;
6284
6285 procedure Matrix3x3ScalarMul(var m:TKraftMatrix3x3;s:TKraftScalar); {$ifdef caninline}inline;{$endif}
6286 begin
6287 m[0,0]:=m[0,0]*s;
6288 m[0,1]:=m[0,1]*s;
6289 m[0,2]:=m[0,2]*s;
6290 {$ifdef SIMD}
6291 m[0,3]:=0.0;
6292 {$endif}
6293 m[1,0]:=m[1,0]*s;
6294 m[1,1]:=m[1,1]*s;
6295 m[1,2]:=m[1,2]*s;
6296 {$ifdef SIMD}
6297 m[1,3]:=0.0;
6298 {$endif}
6299 m[2,0]:=m[2,0]*s;
6300 m[2,1]:=m[2,1]*s;
6301 m[2,2]:=m[2,2]*s;
6302 {$ifdef SIMD}
6303 m[2,3]:=0.0;
6304 {$endif}
6305 end;
6306
6307 function Matrix3x3TermScalarMul(const m:TKraftMatrix3x3;s:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6308 begin
6309 result[0,0]:=m[0,0]*s;
6310 result[0,1]:=m[0,1]*s;
6311 result[0,2]:=m[0,2]*s;
6312 {$ifdef SIMD}
6313 result[0,3]:=0.0;
6314 {$endif}
6315 result[1,0]:=m[1,0]*s;
6316 result[1,1]:=m[1,1]*s;
6317 result[1,2]:=m[1,2]*s;
6318 {$ifdef SIMD}
6319 result[1,3]:=0.0;
6320 {$endif}
6321 result[2,0]:=m[2,0]*s;
6322 result[2,1]:=m[2,1]*s;
6323 result[2,2]:=m[2,2]*s;
6324 {$ifdef SIMD}
6325 result[2,3]:=0.0;
6326 {$endif}
6327 end;
6328
6329 procedure Matrix3x3Transpose(var m:TKraftMatrix3x3); {$ifdef caninline}inline;{$endif}
6330 var mt:TKraftMatrix3x3;
6331 begin
6332 mt[0,0]:=m[0,0];
6333 mt[1,0]:=m[0,1];
6334 mt[2,0]:=m[0,2];
6335 mt[0,1]:=m[1,0];
6336 mt[1,1]:=m[1,1];
6337 mt[2,1]:=m[1,2];
6338 mt[0,2]:=m[2,0];
6339 mt[1,2]:=m[2,1];
6340 mt[2,2]:=m[2,2];
6341 {$ifdef SIMD}
6342 mt[0,3]:=0.0;
6343 mt[1,3]:=0.0;
6344 mt[2,3]:=0.0;
6345 {$endif}
6346 m:=mt;
6347 end;
6348
6349 function Matrix3x3TermTranspose(const m:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
6350 begin
6351 result[0,0]:=m[0,0];
6352 result[1,0]:=m[0,1];
6353 result[2,0]:=m[0,2];
6354 result[0,1]:=m[1,0];
6355 result[1,1]:=m[1,1];
6356 result[2,1]:=m[1,2];
6357 result[0,2]:=m[2,0];
6358 result[1,2]:=m[2,1];
6359 result[2,2]:=m[2,2];
6360 {$ifdef SIMD}
6361 result[0,3]:=0.0;
6362 result[1,3]:=0.0;
6363 result[2,3]:=0.0;
6364 {$endif}
6365 end;
6366
6367 function Matrix3x3Determinant(const m:TKraftMatrix3x3):TKraftScalar; {$ifdef caninline}inline;{$endif}
6368 begin
6369 result:=(m[0,0]*((m[1,1]*m[2,2])-(m[2,1]*m[1,2])))-
6370 (m[0,1]*((m[1,0]*m[2,2])-(m[2,0]*m[1,2])))+
6371 (m[0,2]*((m[1,0]*m[2,1])-(m[2,0]*m[1,1])));
6372 end;
6373
6374 function Matrix3x3EulerAngles(const m:TKraftMatrix3x3):TKraftVector3;
6375 var v0,v1:TKraftVector3;
6376 begin
6377 if abs((-1.0)-m[0,2])<EPSILON then begin
6378 result.x:=0.0;
6379 result.y:=pi*0.5;
6380 result.z:=ArcTan2(m[1,0],m[2,0]);
6381 end else if abs(1.0-m[0,2])<EPSILON then begin
6382 result.x:=0.0;
6383 result.y:=-(pi*0.5);
6384 result.z:=ArcTan2(-m[1,0],-m[2,0]);
6385 end else begin
6386 v0.x:=-ArcSin(m[0,2]);
6387 v1.x:=pi-v0.x;
6388 v0.y:=ArcTan2(m[1,2]/cos(v0.x),m[2,2]/cos(v0.x));
6389 v1.y:=ArcTan2(m[1,2]/cos(v1.x),m[2,2]/cos(v1.x));
6390 v0.z:=ArcTan2(m[0,1]/cos(v0.x),m[0,0]/cos(v0.x));
6391 v1.z:=ArcTan2(m[0,1]/cos(v1.x),m[0,0]/cos(v1.x));
6392 if Vector3LengthSquared(v0)<Vector3LengthSquared(v1) then begin
6393 result:=v0;
6394 end else begin
6395 result:=v1;
6396 end;
6397 end;
6398 end;
6399
6400 procedure Matrix3x3SetColumn(var m:TKraftMatrix3x3;const c:longint;const v:TKraftVector3); {$ifdef caninline}inline;{$endif}
6401 begin
6402 m[c,0]:=v.x;
6403 m[c,1]:=v.y;
6404 m[c,2]:=v.z;
6405 end;
6406
6407 function Matrix3x3GetColumn(const m:TKraftMatrix3x3;const c:longint):TKraftVector3; {$ifdef caninline}inline;{$endif}
6408 begin
6409 result.x:=m[c,0];
6410 result.y:=m[c,1];
6411 result.z:=m[c,2];
6412 end;
6413
6414 procedure Matrix3x3SetRow(var m:TKraftMatrix3x3;const r:longint;const v:TKraftVector3); {$ifdef caninline}inline;{$endif}
6415 begin
6416 m[0,r]:=v.x;
6417 m[1,r]:=v.y;
6418 m[2,r]:=v.z;
6419 end;
6420
6421 function Matrix3x3GetRow(const m:TKraftMatrix3x3;const r:longint):TKraftVector3; {$ifdef caninline}inline;{$endif}
6422 begin
6423 result.x:=m[0,r];
6424 result.y:=m[1,r];
6425 result.z:=m[2,r];
6426 end;
6427
6428 function Matrix3x3Compare(const m1,m2:TKraftMatrix3x3):boolean;
6429 var r,c:longint;
6430 begin
6431 result:=true;
6432 for r:=0 to 2 do begin
6433 for c:=0 to 2 do begin
6434 if abs(m1[r,c]-m2[r,c])>EPSILON then begin
6435 result:=false;
6436 exit;
6437 end;
6438 end;
6439 end;
6440 end;
6441
6442 function Matrix3x3Inverse(var mr:TKraftMatrix3x3;const ma:TKraftMatrix3x3):boolean;
6443 var Determinant:TKraftScalar;
6444 begin
6445 Determinant:=((ma[0,0]*((ma[1,1]*ma[2,2])-(ma[2,1]*ma[1,2])))-
6446 (ma[0,1]*((ma[1,0]*ma[2,2])-(ma[2,0]*ma[1,2]))))+
6447 (ma[0,2]*((ma[1,0]*ma[2,1])-(ma[2,0]*ma[1,1])));
6448 if abs(Determinant)<EPSILON then begin
6449 mr:=Matrix3x3Identity;
6450 result:=false;
6451 end else begin
6452 Determinant:=1.0/Determinant;
6453 mr[0,0]:=((ma[1,1]*ma[2,2])-(ma[2,1]*ma[1,2]))*Determinant;
6454 mr[0,1]:=((ma[0,2]*ma[2,1])-(ma[0,1]*ma[2,2]))*Determinant;
6455 mr[0,2]:=((ma[0,1]*ma[1,2])-(ma[0,2]*ma[1,1]))*Determinant;
6456 {$ifdef SIMD}
6457 mr[0,3]:=0.0;
6458 {$endif}
6459 mr[1,0]:=((ma[1,2]*ma[2,0])-(ma[1,0]*ma[2,2]))*Determinant;
6460 mr[1,1]:=((ma[0,0]*ma[2,2])-(ma[0,2]*ma[2,0]))*Determinant;
6461 mr[1,2]:=((ma[1,0]*ma[0,2])-(ma[0,0]*ma[1,2]))*Determinant;
6462 {$ifdef SIMD}
6463 mr[1,3]:=0.0;
6464 {$endif}
6465 mr[2,0]:=((ma[1,0]*ma[2,1])-(ma[2,0]*ma[1,1]))*Determinant;
6466 mr[2,1]:=((ma[2,0]*ma[0,1])-(ma[0,0]*ma[2,1]))*Determinant;
6467 mr[2,2]:=((ma[0,0]*ma[1,1])-(ma[1,0]*ma[0,1]))*Determinant;
6468 {$ifdef SIMD}
6469 mr[2,3]:=0.0;
6470 {$endif}
6471 result:=true;
6472 end;
6473 end;
6474
6475 function Matrix3x3TermInverse(const m:TKraftMatrix3x3):TKraftMatrix3x3;
6476 var Determinant:TKraftScalar;
6477 begin
6478 Determinant:=((m[0,0]*((m[1,1]*m[2,2])-(m[2,1]*m[1,2])))-
6479 (m[0,1]*((m[1,0]*m[2,2])-(m[2,0]*m[1,2]))))+
6480 (m[0,2]*((m[1,0]*m[2,1])-(m[2,0]*m[1,1])));
6481 if abs(Determinant)<EPSILON then begin
6482 result:=Matrix3x3Identity;
6483 end else begin
6484 Determinant:=1.0/Determinant;
6485 result[0,0]:=((m[1,1]*m[2,2])-(m[2,1]*m[1,2]))*Determinant;
6486 result[0,1]:=((m[0,2]*m[2,1])-(m[0,1]*m[2,2]))*Determinant;
6487 result[0,2]:=((m[0,1]*m[1,2])-(m[0,2]*m[1,1]))*Determinant;
6488 {$ifdef SIMD}
6489 result[0,3]:=0.0;
6490 {$endif}
6491 result[1,0]:=((m[1,2]*m[2,0])-(m[1,0]*m[2,2]))*Determinant;
6492 result[1,1]:=((m[0,0]*m[2,2])-(m[0,2]*m[2,0]))*Determinant;
6493 result[1,2]:=((m[1,0]*m[0,2])-(m[0,0]*m[1,2]))*Determinant;
6494 {$ifdef SIMD}
6495 result[1,3]:=0.0;
6496 {$endif}
6497 result[2,0]:=((m[1,0]*m[2,1])-(m[2,0]*m[1,1]))*Determinant;
6498 result[2,1]:=((m[2,0]*m[0,1])-(m[0,0]*m[2,1]))*Determinant;
6499 result[2,2]:=((m[0,0]*m[1,1])-(m[1,0]*m[0,1]))*Determinant;
6500 {$ifdef SIMD}
6501 result[2,3]:=0.0;
6502 {$endif}
6503 end;
6504 end;
6505
6506 procedure Matrix3x3OrthoNormalize(var m:TKraftMatrix3x3);
6507 var x,y,z:TKraftVector3;
6508 begin
6509 x.x:=m[0,0];
6510 x.y:=m[0,1];
6511 x.z:=m[0,2];
6512 Vector3NormalizeEx(x);
6513 y.x:=m[1,0];
6514 y.y:=m[1,1];
6515 y.z:=m[1,2];
6516 z:=Vector3NormEx(Vector3Cross(x,y));
6517 y:=Vector3NormEx(Vector3Cross(z,x));
6518 m[0,0]:=x.x;
6519 m[0,1]:=x.y;
6520 m[0,2]:=x.z;
6521 {$ifdef SIMD}
6522 m[0,3]:=0.0;
6523 {$endif}
6524 m[1,0]:=y.x;
6525 m[1,1]:=y.y;
6526 m[1,2]:=y.z;
6527 {$ifdef SIMD}
6528 m[1,3]:=0.0;
6529 {$endif}
6530 m[2,0]:=z.x;
6531 m[2,1]:=z.y;
6532 m[2,2]:=z.z;
6533 {$ifdef SIMD}
6534 m[2,3]:=0.0;
6535 {$endif}
6536 end;
6537
6538 function Matrix3x3Slerp(const a,b:TKraftMatrix3x3;x:TKraftScalar):TKraftMatrix3x3;
6539 //var ix:TKraftScalar;
6540 begin
6541 if x<=0.0 then begin
6542 result:=a;
6543 end else if x>=1.0 then begin
6544 result:=b;
6545 end else begin
6546 result:=QuaternionToMatrix3x3(QuaternionSlerp(QuaternionFromMatrix3x3(a),QuaternionFromMatrix3x3(b),x));
6547 end;
6548 end;
6549
6550 function Matrix3x3FromToRotation(const FromDirection,ToDirection:TKraftVector3):TKraftMatrix3x3;
6551 var e,h,hvx,hvz,hvxy,hvxz,hvyz:TKraftScalar;
6552 x,u,v,c:TKraftVector3;
6553 begin
6554 e:=(FromDirection.x*ToDirection.x)+(FromDirection.y*ToDirection.y)+(FromDirection.z*ToDirection.z);
6555 if abs(e)>(1.0-EPSILON) then begin
6556 x.x:=abs(FromDirection.x);
6557 x.y:=abs(FromDirection.y);
6558 x.z:=abs(FromDirection.z);
6559 if x.x<x.y then begin
6560 if x.x<x.z then begin
6561 x.x:=1.0;
6562 x.y:=0.0;
6563 x.z:=0.0;
6564 end else begin
6565 x.x:=0.0;
6566 x.y:=0.0;
6567 x.z:=1.0;
6568 end;
6569 end else begin
6570 if x.y<x.z then begin
6571 x.x:=0.0;
6572 x.y:=1.0;
6573 x.z:=0.0;
6574 end else begin
6575 x.x:=0.0;
6576 x.y:=0.0;
6577 x.z:=1.0;
6578 end;
6579 end;
6580 u.x:=x.x-FromDirection.x;
6581 u.y:=x.y-FromDirection.y;
6582 u.z:=x.z-FromDirection.z;
6583 v.x:=x.x-ToDirection.x;
6584 v.y:=x.y-ToDirection.y;
6585 v.z:=x.z-ToDirection.z;
6586 c.x:=2.0/(sqr(u.x)+sqr(u.y)+sqr(u.z));
6587 c.y:=2.0/(sqr(v.x)+sqr(v.y)+sqr(v.z));
6588 c.z:=c.x*c.y*((u.x*v.x)+(u.y*v.y)+(u.z*v.z));
6589 result[0,0]:=1.0+((c.z*(v.x*u.x))-((c.y*(v.x*v.x))+(c.x*(u.x*u.x))));
6590 result[0,1]:=(c.z*(v.x*u.y))-((c.y*(v.x*v.y))+(c.x*(u.x*u.y)));
6591 result[0,2]:=(c.z*(v.x*u.z))-((c.y*(v.x*v.z))+(c.x*(u.x*u.z)));
6592 {$ifdef SIMD}
6593 result[0,3]:=0.0;
6594 {$endif}
6595 result[1,0]:=(c.z*(v.y*u.x))-((c.y*(v.y*v.x))+(c.x*(u.y*u.x)));
6596 result[1,1]:=1.0+((c.z*(v.y*u.y))-((c.y*(v.y*v.y))+(c.x*(u.y*u.y))));
6597 result[1,2]:=(c.z*(v.y*u.z))-((c.y*(v.y*v.z))+(c.x*(u.y*u.z)));
6598 {$ifdef SIMD}
6599 result[1,3]:=0.0;
6600 {$endif}
6601 result[2,0]:=(c.z*(v.z*u.x))-((c.y*(v.z*v.x))+(c.x*(u.z*u.x)));
6602 result[2,1]:=(c.z*(v.z*u.y))-((c.y*(v.z*v.y))+(c.x*(u.z*u.y)));
6603 result[2,2]:=1.0+((c.z*(v.z*u.z))-((c.y*(v.z*v.z))+(c.x*(u.z*u.z))));
6604 {$ifdef SIMD}
6605 result[2,3]:=0.0;
6606 {$endif}
6607 end else begin
6608 v:=Vector3Cross(FromDirection,ToDirection);
6609 h:=1.0/(1.0+e);
6610 hvx:=h*v.x;
6611 hvz:=h*v.z;
6612 hvxy:=hvx*v.y;
6613 hvxz:=hvx*v.z;
6614 hvyz:=hvz*v.y;
6615 result[0,0]:=e+(hvx*v.x);
6616 result[0,1]:=hvxy-v.z;
6617 result[0,2]:=hvxz+v.y;
6618 {$ifdef SIMD}
6619 result[0,3]:=0.0;
6620 {$endif}
6621 result[1,0]:=hvxy+v.z;
6622 result[1,1]:=e+(h*sqr(v.y));
6623 result[1,2]:=hvyz-v.x;
6624 {$ifdef SIMD}
6625 result[1,3]:=0.0;
6626 {$endif}
6627 result[2,0]:=hvxz-v.y;
6628 result[2,1]:=hvyz+v.x;
6629 result[2,2]:=e+(hvz*v.z);
6630 {$ifdef SIMD}
6631 result[2,3]:=0.0;
6632 {$endif}
6633 end;
6634 end;
6635
6636 function Matrix3x3Construct(const Forwards,Up:TKraftVector3):TKraftMatrix3x3;
6637 var RightVector,UpVector,ForwardVector:TKraftVector3;
6638 begin
6639 ForwardVector:=Vector3NormEx(Vector3Neg(Forwards));
6640 RightVector:=Vector3NormEx(Vector3Cross(Up,ForwardVector));
6641 UpVector:=Vector3NormEx(Vector3Cross(ForwardVector,RightVector));
6642 result[0,0]:=RightVector.x;
6643 result[0,1]:=RightVector.y;
6644 result[0,2]:=RightVector.z;
6645 {$ifdef SIMD}
6646 result[0,3]:=0.0;
6647 {$endif}
6648 result[1,0]:=UpVector.x;
6649 result[1,1]:=UpVector.y;
6650 result[1,2]:=UpVector.z;
6651 {$ifdef SIMD}
6652 result[1,3]:=0.0;
6653 {$endif}
6654 result[2,0]:=ForwardVector.x;
6655 result[2,1]:=ForwardVector.y;
6656 result[2,2]:=ForwardVector.z;
6657 {$ifdef SIMD}
6658 result[2,3]:=0.0;
6659 {$endif}
6660 end;
6661
6662 function Matrix3x3OuterProduct(const u,v:TKraftVector3):TKraftMatrix3x3;
6663 begin
6664 result[0,0]:=u.x*v.x;
6665 result[0,1]:=u.x*v.y;
6666 result[0,2]:=u.x*v.z;
6667 {$ifdef SIMD}
6668 result[0,3]:=0.0;
6669 {$endif}
6670 result[1,0]:=u.y*v.x;
6671 result[1,1]:=u.y*v.y;
6672 result[1,2]:=u.y*v.z;
6673 {$ifdef SIMD}
6674 result[1,3]:=0.0;
6675 {$endif}
6676 result[2,0]:=u.z*v.x;
6677 result[2,1]:=u.z*v.y;
6678 result[2,2]:=u.z*v.z;
6679 {$ifdef SIMD}
6680 result[2,3]:=0.0;
6681 {$endif}
6682 end;
6683
6684 function Matrix4x4Set(m:TKraftMatrix3x3):TKraftMatrix4x4;
6685 begin
6686 result[0,0]:=m[0,0];
6687 result[0,1]:=m[0,1];
6688 result[0,2]:=m[0,2];
6689 result[0,3]:=0;
6690 result[1,0]:=m[1,0];
6691 result[1,1]:=m[1,1];
6692 result[1,2]:=m[1,2];
6693 result[1,3]:=0;
6694 result[2,0]:=m[2,0];
6695 result[2,1]:=m[2,1];
6696 result[2,2]:=m[2,2];
6697 result[2,3]:=0;
6698 result[3,0]:=0;
6699 result[3,1]:=0;
6700 result[3,2]:=0;
6701 result[3,3]:=1;
6702 end;
6703
6704 function Matrix4x4Rotation(m:TKraftMatrix4x4):TKraftMatrix4x4;
6705 begin
6706 result[0,0]:=m[0,0];
6707 result[0,1]:=m[0,1];
6708 result[0,2]:=m[0,2];
6709 result[0,3]:=0;
6710 result[1,0]:=m[1,0];
6711 result[1,1]:=m[1,1];
6712 result[1,2]:=m[1,2];
6713 result[1,3]:=0;
6714 result[2,0]:=m[2,0];
6715 result[2,1]:=m[2,1];
6716 result[2,2]:=m[2,2];
6717 result[2,3]:=0;
6718 result[3,0]:=0;
6719 result[3,1]:=0;
6720 result[3,2]:=0;
6721 result[3,3]:=1;
6722 end;
6723
6724 function Matrix4x4RotateX(Angle:TKraftScalar):TKraftMatrix4x4;
6725 begin
6726 result:=Matrix4x4Identity;
6727 result[1,1]:=cos(Angle);
6728 result[2,2]:=result[1,1];
6729 result[1,2]:=sin(Angle);
6730 result[2,1]:=-result[1,2];
6731 end;
6732
6733 function Matrix4x4RotateY(Angle:TKraftScalar):TKraftMatrix4x4;
6734 begin
6735 result:=Matrix4x4Identity;
6736 result[0,0]:=cos(Angle);
6737 result[2,2]:=result[0,0];
6738 result[0,2]:=-sin(Angle);
6739 result[2,0]:=-result[0,2];
6740 end;
6741
6742 function Matrix4x4RotateZ(Angle:TKraftScalar):TKraftMatrix4x4;
6743 begin
6744 result:=Matrix4x4Identity;
6745 result[0,0]:=cos(Angle);
6746 result[1,1]:=result[0,0];
6747 result[0,1]:=sin(Angle);
6748 result[1,0]:=-result[0,1];
6749 end;
6750
6751 function Matrix4x4Rotate(Angle:TKraftScalar;Axis:TKraftVector3):TKraftMatrix4x4; overload;
6752 var m:TKraftMatrix4x4;
6753 CosinusAngle,SinusAngle:TKraftScalar;
6754 begin
6755 m:=Matrix4x4Identity;
6756 CosinusAngle:=cos(Angle);
6757 SinusAngle:=sin(Angle);
6758 m[0,0]:=CosinusAngle+((1-CosinusAngle)*Axis.x*Axis.x);
6759 m[1,0]:=((1-CosinusAngle)*Axis.x*Axis.y)-(Axis.z*SinusAngle);
6760 m[2,0]:=((1-CosinusAngle)*Axis.x*Axis.z)+(Axis.y*SinusAngle);
6761 m[0,1]:=((1-CosinusAngle)*Axis.x*Axis.z)+(Axis.z*SinusAngle);
6762 m[1,1]:=CosinusAngle+((1-CosinusAngle)*Axis.y*Axis.y);
6763 m[2,1]:=((1-CosinusAngle)*Axis.y*Axis.z)-(Axis.x*SinusAngle);
6764 m[0,2]:=((1-CosinusAngle)*Axis.x*Axis.z)-(Axis.y*SinusAngle);
6765 m[1,2]:=((1-CosinusAngle)*Axis.y*Axis.z)+(Axis.x*SinusAngle);
6766 m[2,2]:=CosinusAngle+((1-CosinusAngle)*Axis.z*Axis.z);
6767 result:=m;
6768 end;
6769
6770 function Matrix4x4Translate(x,y,z:TKraftScalar):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
6771 begin
6772 result:=Matrix4x4Identity;
6773 result[3,0]:=x;
6774 result[3,1]:=y;
6775 result[3,2]:=z;
6776 end;
6777
6778 function Matrix4x4Translate(const v:TKraftVector3):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
6779 begin
6780 result:=Matrix4x4Identity;
6781 result[3,0]:=v.x;
6782 result[3,1]:=v.y;
6783 result[3,2]:=v.z;
6784 end;
6785
6786 function Matrix4x4Translate(const v:TKraftVector4):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
6787 begin
6788 result:=Matrix4x4Identity;
6789 result[3,0]:=v.x;
6790 result[3,1]:=v.y;
6791 result[3,2]:=v.z;
6792 end;
6793
6794 procedure Matrix4x4Translate(var m:TKraftMatrix4x4;const v:TKraftVector3); overload; {$ifdef caninline}inline;{$endif}
6795 begin
6796 m[3,0]:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+m[3,0];
6797 m[3,1]:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+m[3,1];
6798 m[3,2]:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+m[3,2];
6799 m[3,3]:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+m[3,3];
6800 end;
6801
6802 procedure Matrix4x4Translate(var m:TKraftMatrix4x4;const v:TKraftVector4); overload; {$ifdef caninline}inline;{$endif}
6803 begin
6804 m[3,0]:=(m[0,0]*v.x)+(m[1,0]*v.y)+(m[2,0]*v.z)+(m[3,0]*v.w);
6805 m[3,1]:=(m[0,1]*v.x)+(m[1,1]*v.y)+(m[2,1]*v.z)+(m[3,1]*v.w);
6806 m[3,2]:=(m[0,2]*v.x)+(m[1,2]*v.y)+(m[2,2]*v.z)+(m[3,2]*v.w);
6807 m[3,3]:=(m[0,3]*v.x)+(m[1,3]*v.y)+(m[2,3]*v.z)+(m[3,3]*v.w);
6808 end;
6809
6810 function Matrix4x4Scale(sx,sy,sz:TKraftScalar):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
6811 begin
6812 result:=Matrix4x4Identity;
6813 result[0,0]:=sx;
6814 result[1,1]:=sy;
6815 result[2,2]:=sz;
6816 end;
6817
6818 function Matrix4x4Scale(const s:TKraftVector3):TKraftMatrix4x4; overload; {$ifdef caninline}inline;{$endif}
6819 begin
6820 result:=Matrix4x4Identity;
6821 result[0,0]:=s.x;
6822 result[1,1]:=s.y;
6823 result[2,2]:=s.z;
6824 end;
6825
6826 procedure Matrix4x4Add(var m1:TKraftMatrix4x4;const m2:TKraftMatrix4x4); {$ifdef caninline}inline;{$endif}
6827 begin
6828 m1[0,0]:=m1[0,0]+m2[0,0];
6829 m1[0,1]:=m1[0,1]+m2[0,1];
6830 m1[0,2]:=m1[0,2]+m2[0,2];
6831 m1[0,3]:=m1[0,3]+m2[0,3];
6832 m1[1,0]:=m1[1,0]+m2[1,0];
6833 m1[1,1]:=m1[1,1]+m2[1,1];
6834 m1[1,2]:=m1[1,2]+m2[1,2];
6835 m1[1,3]:=m1[1,3]+m2[1,3];
6836 m1[2,0]:=m1[2,0]+m2[2,0];
6837 m1[2,1]:=m1[2,1]+m2[2,1];
6838 m1[2,2]:=m1[2,2]+m2[2,2];
6839 m1[2,3]:=m1[2,3]+m2[2,3];
6840 m1[3,0]:=m1[3,0]+m2[3,0];
6841 m1[3,1]:=m1[3,1]+m2[3,1];
6842 m1[3,2]:=m1[3,2]+m2[3,2];
6843 m1[3,3]:=m1[3,3]+m2[3,3];
6844 end;
6845
6846 procedure Matrix4x4Sub(var m1:TKraftMatrix4x4;const m2:TKraftMatrix4x4); {$ifdef caninline}inline;{$endif}
6847 begin
6848 m1[0,0]:=m1[0,0]-m2[0,0];
6849 m1[0,1]:=m1[0,1]-m2[0,1];
6850 m1[0,2]:=m1[0,2]-m2[0,2];
6851 m1[0,3]:=m1[0,3]-m2[0,3];
6852 m1[1,0]:=m1[1,0]-m2[1,0];
6853 m1[1,1]:=m1[1,1]-m2[1,1];
6854 m1[1,2]:=m1[1,2]-m2[1,2];
6855 m1[1,3]:=m1[1,3]-m2[1,3];
6856 m1[2,0]:=m1[2,0]-m2[2,0];
6857 m1[2,1]:=m1[2,1]-m2[2,1];
6858 m1[2,2]:=m1[2,2]-m2[2,2];
6859 m1[2,3]:=m1[2,3]-m2[2,3];
6860 m1[3,0]:=m1[3,0]-m2[3,0];
6861 m1[3,1]:=m1[3,1]-m2[3,1];
6862 m1[3,2]:=m1[3,2]-m2[3,2];
6863 m1[3,3]:=m1[3,3]-m2[3,3];
6864 end;
6865
6866 procedure Matrix4x4Mul(var m1:TKraftMatrix4x4;const m2:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}register;
6867 asm
6868 movups xmm0,dqword ptr [m2+0]
6869 movups xmm1,dqword ptr [m2+16]
6870 movups xmm2,dqword ptr [m2+32]
6871 movups xmm3,dqword ptr [m2+48]
6872
6873 movups xmm7,dqword ptr [m1+0]
6874 pshufd xmm4,xmm7,$00
6875 pshufd xmm5,xmm7,$55
6876 pshufd xmm6,xmm7,$aa
6877 pshufd xmm7,xmm7,$ff
6878 mulps xmm4,xmm0
6879 mulps xmm5,xmm1
6880 mulps xmm6,xmm2
6881 mulps xmm7,xmm3
6882 addps xmm4,xmm5
6883 addps xmm6,xmm7
6884 addps xmm4,xmm6
6885 movups dqword ptr [m1+0],xmm4
6886
6887 movups xmm7,dqword ptr [m1+16]
6888 pshufd xmm4,xmm7,$00
6889 pshufd xmm5,xmm7,$55
6890 pshufd xmm6,xmm7,$aa
6891 pshufd xmm7,xmm7,$ff
6892 mulps xmm4,xmm0
6893 mulps xmm5,xmm1
6894 mulps xmm6,xmm2
6895 mulps xmm7,xmm3
6896 addps xmm4,xmm5
6897 addps xmm6,xmm7
6898 addps xmm4,xmm6
6899 movups dqword ptr [m1+16],xmm4
6900
6901 movups xmm7,dqword ptr [m1+32]
6902 pshufd xmm4,xmm7,$00
6903 pshufd xmm5,xmm7,$55
6904 pshufd xmm6,xmm7,$aa
6905 pshufd xmm7,xmm7,$ff
6906 mulps xmm4,xmm0
6907 mulps xmm5,xmm1
6908 mulps xmm6,xmm2
6909 mulps xmm7,xmm3
6910 addps xmm4,xmm5
6911 addps xmm6,xmm7
6912 addps xmm4,xmm6
6913 movups dqword ptr [m1+32],xmm4
6914
6915 movups xmm7,dqword ptr [m1+48]
6916 pshufd xmm4,xmm7,$00
6917 pshufd xmm5,xmm7,$55
6918 pshufd xmm6,xmm7,$aa
6919 pshufd xmm7,xmm7,$ff
6920 mulps xmm4,xmm0
6921 mulps xmm5,xmm1
6922 mulps xmm6,xmm2
6923 mulps xmm7,xmm3
6924 addps xmm4,xmm5
6925 addps xmm6,xmm7
6926 addps xmm4,xmm6
6927 movups dqword ptr [m1+48],xmm4
6928
6929 end;
6930 {$else}
6931 var t:TKraftMatrix4x4;
6932 begin
6933 t[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[1,0])+(m1[0,2]*m2[2,0])+(m1[0,3]*m2[3,0]);
6934 t[0,1]:=(m1[0,0]*m2[0,1])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[2,1])+(m1[0,3]*m2[3,1]);
6935 t[0,2]:=(m1[0,0]*m2[0,2])+(m1[0,1]*m2[1,2])+(m1[0,2]*m2[2,2])+(m1[0,3]*m2[3,2]);
6936 t[0,3]:=(m1[0,0]*m2[0,3])+(m1[0,1]*m2[1,3])+(m1[0,2]*m2[2,3])+(m1[0,3]*m2[3,3]);
6937 t[1,0]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[1,0])+(m1[1,2]*m2[2,0])+(m1[1,3]*m2[3,0]);
6938 t[1,1]:=(m1[1,0]*m2[0,1])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[2,1])+(m1[1,3]*m2[3,1]);
6939 t[1,2]:=(m1[1,0]*m2[0,2])+(m1[1,1]*m2[1,2])+(m1[1,2]*m2[2,2])+(m1[1,3]*m2[3,2]);
6940 t[1,3]:=(m1[1,0]*m2[0,3])+(m1[1,1]*m2[1,3])+(m1[1,2]*m2[2,3])+(m1[1,3]*m2[3,3]);
6941 t[2,0]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[1,0])+(m1[2,2]*m2[2,0])+(m1[2,3]*m2[3,0]);
6942 t[2,1]:=(m1[2,0]*m2[0,1])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[2,1])+(m1[2,3]*m2[3,1]);
6943 t[2,2]:=(m1[2,0]*m2[0,2])+(m1[2,1]*m2[1,2])+(m1[2,2]*m2[2,2])+(m1[2,3]*m2[3,2]);
6944 t[2,3]:=(m1[2,0]*m2[0,3])+(m1[2,1]*m2[1,3])+(m1[2,2]*m2[2,3])+(m1[2,3]*m2[3,3]);
6945 t[3,0]:=(m1[3,0]*m2[0,0])+(m1[3,1]*m2[1,0])+(m1[3,2]*m2[2,0])+(m1[3,3]*m2[3,0]);
6946 t[3,1]:=(m1[3,0]*m2[0,1])+(m1[3,1]*m2[1,1])+(m1[3,2]*m2[2,1])+(m1[3,3]*m2[3,1]);
6947 t[3,2]:=(m1[3,0]*m2[0,2])+(m1[3,1]*m2[1,2])+(m1[3,2]*m2[2,2])+(m1[3,3]*m2[3,2]);
6948 t[3,3]:=(m1[3,0]*m2[0,3])+(m1[3,1]*m2[1,3])+(m1[3,2]*m2[2,3])+(m1[3,3]*m2[3,3]);
6949 m1:=t;
6950 end;
6951 {$endif}
6952
6953 procedure Matrix4x4Mul(var mr:TKraftMatrix4x4;const m1,m2:TKraftMatrix4x4); overload; {$ifdef CPU386ASMForSinglePrecision}register;
6954 asm
6955
6956 movups xmm0,dqword ptr [m2+0]
6957 movups xmm1,dqword ptr [m2+16]
6958 movups xmm2,dqword ptr [m2+32]
6959 movups xmm3,dqword ptr [m2+48]
6960
6961 movups xmm7,dqword ptr [m1+0]
6962 pshufd xmm4,xmm7,$00
6963 pshufd xmm5,xmm7,$55
6964 pshufd xmm6,xmm7,$aa
6965 pshufd xmm7,xmm7,$ff
6966 mulps xmm4,xmm0
6967 mulps xmm5,xmm1
6968 mulps xmm6,xmm2
6969 mulps xmm7,xmm3
6970 addps xmm4,xmm5
6971 addps xmm6,xmm7
6972 addps xmm4,xmm6
6973 movups dqword ptr [mr+0],xmm4
6974
6975 movups xmm7,dqword ptr [m1+16]
6976 pshufd xmm4,xmm7,$00
6977 pshufd xmm5,xmm7,$55
6978 pshufd xmm6,xmm7,$aa
6979 pshufd xmm7,xmm7,$ff
6980 mulps xmm4,xmm0
6981 mulps xmm5,xmm1
6982 mulps xmm6,xmm2
6983 mulps xmm7,xmm3
6984 addps xmm4,xmm5
6985 addps xmm6,xmm7
6986 addps xmm4,xmm6
6987 movups dqword ptr [mr+16],xmm4
6988
6989 movups xmm7,dqword ptr [m1+32]
6990 pshufd xmm4,xmm7,$00
6991 pshufd xmm5,xmm7,$55
6992 pshufd xmm6,xmm7,$aa
6993 pshufd xmm7,xmm7,$ff
6994 mulps xmm4,xmm0
6995 mulps xmm5,xmm1
6996 mulps xmm6,xmm2
6997 mulps xmm7,xmm3
6998 addps xmm4,xmm5
6999 addps xmm6,xmm7
7000 addps xmm4,xmm6
7001 movups dqword ptr [mr+32],xmm4
7002
7003 movups xmm7,dqword ptr [m1+48]
7004 pshufd xmm4,xmm7,$00
7005 pshufd xmm5,xmm7,$55
7006 pshufd xmm6,xmm7,$aa
7007 pshufd xmm7,xmm7,$ff
7008 mulps xmm4,xmm0
7009 mulps xmm5,xmm1
7010 mulps xmm6,xmm2
7011 mulps xmm7,xmm3
7012 addps xmm4,xmm5
7013 addps xmm6,xmm7
7014 addps xmm4,xmm6
7015 movups dqword ptr [mr+48],xmm4
7016
7017 end;
7018 {$else}
7019 begin
7020 mr[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[1,0])+(m1[0,2]*m2[2,0])+(m1[0,3]*m2[3,0]);
7021 mr[0,1]:=(m1[0,0]*m2[0,1])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[2,1])+(m1[0,3]*m2[3,1]);
7022 mr[0,2]:=(m1[0,0]*m2[0,2])+(m1[0,1]*m2[1,2])+(m1[0,2]*m2[2,2])+(m1[0,3]*m2[3,2]);
7023 mr[0,3]:=(m1[0,0]*m2[0,3])+(m1[0,1]*m2[1,3])+(m1[0,2]*m2[2,3])+(m1[0,3]*m2[3,3]);
7024 mr[1,0]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[1,0])+(m1[1,2]*m2[2,0])+(m1[1,3]*m2[3,0]);
7025 mr[1,1]:=(m1[1,0]*m2[0,1])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[2,1])+(m1[1,3]*m2[3,1]);
7026 mr[1,2]:=(m1[1,0]*m2[0,2])+(m1[1,1]*m2[1,2])+(m1[1,2]*m2[2,2])+(m1[1,3]*m2[3,2]);
7027 mr[1,3]:=(m1[1,0]*m2[0,3])+(m1[1,1]*m2[1,3])+(m1[1,2]*m2[2,3])+(m1[1,3]*m2[3,3]);
7028 mr[2,0]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[1,0])+(m1[2,2]*m2[2,0])+(m1[2,3]*m2[3,0]);
7029 mr[2,1]:=(m1[2,0]*m2[0,1])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[2,1])+(m1[2,3]*m2[3,1]);
7030 mr[2,2]:=(m1[2,0]*m2[0,2])+(m1[2,1]*m2[1,2])+(m1[2,2]*m2[2,2])+(m1[2,3]*m2[3,2]);
7031 mr[2,3]:=(m1[2,0]*m2[0,3])+(m1[2,1]*m2[1,3])+(m1[2,2]*m2[2,3])+(m1[2,3]*m2[3,3]);
7032 mr[3,0]:=(m1[3,0]*m2[0,0])+(m1[3,1]*m2[1,0])+(m1[3,2]*m2[2,0])+(m1[3,3]*m2[3,0]);
7033 mr[3,1]:=(m1[3,0]*m2[0,1])+(m1[3,1]*m2[1,1])+(m1[3,2]*m2[2,1])+(m1[3,3]*m2[3,1]);
7034 mr[3,2]:=(m1[3,0]*m2[0,2])+(m1[3,1]*m2[1,2])+(m1[3,2]*m2[2,2])+(m1[3,3]*m2[3,2]);
7035 mr[3,3]:=(m1[3,0]*m2[0,3])+(m1[3,1]*m2[1,3])+(m1[3,2]*m2[2,3])+(m1[3,3]*m2[3,3]);
7036 end;
7037 {$endif}
7038
7039 function Matrix4x4TermAdd(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
7040 begin
7041 result[0,0]:=m1[0,0]+m2[0,0];
7042 result[0,1]:=m1[0,1]+m2[0,1];
7043 result[0,2]:=m1[0,2]+m2[0,2];
7044 result[0,3]:=m1[0,3]+m2[0,3];
7045 result[1,0]:=m1[1,0]+m2[1,0];
7046 result[1,1]:=m1[1,1]+m2[1,1];
7047 result[1,2]:=m1[1,2]+m2[1,2];
7048 result[1,3]:=m1[1,3]+m2[1,3];
7049 result[2,0]:=m1[2,0]+m2[2,0];
7050 result[2,1]:=m1[2,1]+m2[2,1];
7051 result[2,2]:=m1[2,2]+m2[2,2];
7052 result[2,3]:=m1[2,3]+m2[2,3];
7053 result[3,0]:=m1[3,0]+m2[3,0];
7054 result[3,1]:=m1[3,1]+m2[3,1];
7055 result[3,2]:=m1[3,2]+m2[3,2];
7056 result[3,3]:=m1[3,3]+m2[3,3];
7057 end;
7058
7059 function Matrix4x4TermSub(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
7060 begin
7061 result[0,0]:=m1[0,0]-m2[0,0];
7062 result[0,1]:=m1[0,1]-m2[0,1];
7063 result[0,2]:=m1[0,2]-m2[0,2];
7064 result[0,3]:=m1[0,3]-m2[0,3];
7065 result[1,0]:=m1[1,0]-m2[1,0];
7066 result[1,1]:=m1[1,1]-m2[1,1];
7067 result[1,2]:=m1[1,2]-m2[1,2];
7068 result[1,3]:=m1[1,3]-m2[1,3];
7069 result[2,0]:=m1[2,0]-m2[2,0];
7070 result[2,1]:=m1[2,1]-m2[2,1];
7071 result[2,2]:=m1[2,2]-m2[2,2];
7072 result[2,3]:=m1[2,3]-m2[2,3];
7073 result[3,0]:=m1[3,0]-m2[3,0];
7074 result[3,1]:=m1[3,1]-m2[3,1];
7075 result[3,2]:=m1[3,2]-m2[3,2];
7076 result[3,3]:=m1[3,3]-m2[3,3];
7077 end;
7078
7079 function Matrix4x4TermMul(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef CPU386ASMForSinglePrecision}register;
7080 asm
7081
7082 movups xmm0,dqword ptr [m2+0]
7083 movups xmm1,dqword ptr [m2+16]
7084 movups xmm2,dqword ptr [m2+32]
7085 movups xmm3,dqword ptr [m2+48]
7086
7087 movups xmm7,dqword ptr [m1+0]
7088 pshufd xmm4,xmm7,$00
7089 pshufd xmm5,xmm7,$55
7090 pshufd xmm6,xmm7,$aa
7091 pshufd xmm7,xmm7,$ff
7092 mulps xmm4,xmm0
7093 mulps xmm5,xmm1
7094 mulps xmm6,xmm2
7095 mulps xmm7,xmm3
7096 addps xmm4,xmm5
7097 addps xmm6,xmm7
7098 addps xmm4,xmm6
7099 movups dqword ptr [result+0],xmm4
7100
7101 movups xmm7,dqword ptr [m1+16]
7102 pshufd xmm4,xmm7,$00
7103 pshufd xmm5,xmm7,$55
7104 pshufd xmm6,xmm7,$aa
7105 pshufd xmm7,xmm7,$ff
7106 mulps xmm4,xmm0
7107 mulps xmm5,xmm1
7108 mulps xmm6,xmm2
7109 mulps xmm7,xmm3
7110 addps xmm4,xmm5
7111 addps xmm6,xmm7
7112 addps xmm4,xmm6
7113 movups dqword ptr [result+16],xmm4
7114
7115 movups xmm7,dqword ptr [m1+32]
7116 pshufd xmm4,xmm7,$00
7117 pshufd xmm5,xmm7,$55
7118 pshufd xmm6,xmm7,$aa
7119 pshufd xmm7,xmm7,$ff
7120 mulps xmm4,xmm0
7121 mulps xmm5,xmm1
7122 mulps xmm6,xmm2
7123 mulps xmm7,xmm3
7124 addps xmm4,xmm5
7125 addps xmm6,xmm7
7126 addps xmm4,xmm6
7127 movups dqword ptr [result+32],xmm4
7128
7129 movups xmm7,dqword ptr [m1+48]
7130 pshufd xmm4,xmm7,$00
7131 pshufd xmm5,xmm7,$55
7132 pshufd xmm6,xmm7,$aa
7133 pshufd xmm7,xmm7,$ff
7134 mulps xmm4,xmm0
7135 mulps xmm5,xmm1
7136 mulps xmm6,xmm2
7137 mulps xmm7,xmm3
7138 addps xmm4,xmm5
7139 addps xmm6,xmm7
7140 addps xmm4,xmm6
7141 movups dqword ptr [result+48],xmm4
7142
7143 end;
7144 {$else}
7145 begin
7146 result[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[1,0])+(m1[0,2]*m2[2,0])+(m1[0,3]*m2[3,0]);
7147 result[0,1]:=(m1[0,0]*m2[0,1])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[2,1])+(m1[0,3]*m2[3,1]);
7148 result[0,2]:=(m1[0,0]*m2[0,2])+(m1[0,1]*m2[1,2])+(m1[0,2]*m2[2,2])+(m1[0,3]*m2[3,2]);
7149 result[0,3]:=(m1[0,0]*m2[0,3])+(m1[0,1]*m2[1,3])+(m1[0,2]*m2[2,3])+(m1[0,3]*m2[3,3]);
7150 result[1,0]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[1,0])+(m1[1,2]*m2[2,0])+(m1[1,3]*m2[3,0]);
7151 result[1,1]:=(m1[1,0]*m2[0,1])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[2,1])+(m1[1,3]*m2[3,1]);
7152 result[1,2]:=(m1[1,0]*m2[0,2])+(m1[1,1]*m2[1,2])+(m1[1,2]*m2[2,2])+(m1[1,3]*m2[3,2]);
7153 result[1,3]:=(m1[1,0]*m2[0,3])+(m1[1,1]*m2[1,3])+(m1[1,2]*m2[2,3])+(m1[1,3]*m2[3,3]);
7154 result[2,0]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[1,0])+(m1[2,2]*m2[2,0])+(m1[2,3]*m2[3,0]);
7155 result[2,1]:=(m1[2,0]*m2[0,1])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[2,1])+(m1[2,3]*m2[3,1]);
7156 result[2,2]:=(m1[2,0]*m2[0,2])+(m1[2,1]*m2[1,2])+(m1[2,2]*m2[2,2])+(m1[2,3]*m2[3,2]);
7157 result[2,3]:=(m1[2,0]*m2[0,3])+(m1[2,1]*m2[1,3])+(m1[2,2]*m2[2,3])+(m1[2,3]*m2[3,3]);
7158 result[3,0]:=(m1[3,0]*m2[0,0])+(m1[3,1]*m2[1,0])+(m1[3,2]*m2[2,0])+(m1[3,3]*m2[3,0]);
7159 result[3,1]:=(m1[3,0]*m2[0,1])+(m1[3,1]*m2[1,1])+(m1[3,2]*m2[2,1])+(m1[3,3]*m2[3,1]);
7160 result[3,2]:=(m1[3,0]*m2[0,2])+(m1[3,1]*m2[1,2])+(m1[3,2]*m2[2,2])+(m1[3,3]*m2[3,2]);
7161 result[3,3]:=(m1[3,0]*m2[0,3])+(m1[3,1]*m2[1,3])+(m1[3,2]*m2[2,3])+(m1[3,3]*m2[3,3]);
7162 end;
7163 {$endif}
7164
7165 function Matrix4x4TermMulInverted(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
7166 begin
7167 result:=Matrix4x4TermMul(m1,Matrix4x4TermInverse(m2));
7168 end;
7169
7170 function Matrix4x4TermMulSimpleInverted(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
7171 begin
7172 result:=Matrix4x4TermMul(m1,Matrix4x4TermSimpleInverse(m2));
7173 end;
7174
7175 function Matrix4x4TermMulTranspose(const m1,m2:TKraftMatrix4x4):TKraftMatrix4x4;
7176 begin
7177 result[0,0]:=(m1[0,0]*m2[0,0])+(m1[0,1]*m2[1,0])+(m1[0,2]*m2[2,0])+(m1[0,3]*m2[3,0]);
7178 result[1,0]:=(m1[0,0]*m2[0,1])+(m1[0,1]*m2[1,1])+(m1[0,2]*m2[2,1])+(m1[0,3]*m2[3,1]);
7179 result[2,0]:=(m1[0,0]*m2[0,2])+(m1[0,1]*m2[1,2])+(m1[0,2]*m2[2,2])+(m1[0,3]*m2[3,2]);
7180 result[3,0]:=(m1[0,0]*m2[0,3])+(m1[0,1]*m2[1,3])+(m1[0,2]*m2[2,3])+(m1[0,3]*m2[3,3]);
7181 result[0,1]:=(m1[1,0]*m2[0,0])+(m1[1,1]*m2[1,0])+(m1[1,2]*m2[2,0])+(m1[1,3]*m2[3,0]);
7182 result[1,1]:=(m1[1,0]*m2[0,1])+(m1[1,1]*m2[1,1])+(m1[1,2]*m2[2,1])+(m1[1,3]*m2[3,1]);
7183 result[2,1]:=(m1[1,0]*m2[0,2])+(m1[1,1]*m2[1,2])+(m1[1,2]*m2[2,2])+(m1[1,3]*m2[3,2]);
7184 result[3,1]:=(m1[1,0]*m2[0,3])+(m1[1,1]*m2[1,3])+(m1[1,2]*m2[2,3])+(m1[1,3]*m2[3,3]);
7185 result[0,2]:=(m1[2,0]*m2[0,0])+(m1[2,1]*m2[1,0])+(m1[2,2]*m2[2,0])+(m1[2,3]*m2[3,0]);
7186 result[1,2]:=(m1[2,0]*m2[0,1])+(m1[2,1]*m2[1,1])+(m1[2,2]*m2[2,1])+(m1[2,3]*m2[3,1]);
7187 result[2,2]:=(m1[2,0]*m2[0,2])+(m1[2,1]*m2[1,2])+(m1[2,2]*m2[2,2])+(m1[2,3]*m2[3,2]);
7188 result[3,2]:=(m1[2,0]*m2[0,3])+(m1[2,1]*m2[1,3])+(m1[2,2]*m2[2,3])+(m1[2,3]*m2[3,3]);
7189 result[0,3]:=(m1[3,0]*m2[0,0])+(m1[3,1]*m2[1,0])+(m1[3,2]*m2[2,0])+(m1[3,3]*m2[3,0]);
7190 result[1,3]:=(m1[3,0]*m2[0,1])+(m1[3,1]*m2[1,1])+(m1[3,2]*m2[2,1])+(m1[3,3]*m2[3,1]);
7191 result[2,3]:=(m1[3,0]*m2[0,2])+(m1[3,1]*m2[1,2])+(m1[3,2]*m2[2,2])+(m1[3,3]*m2[3,2]);
7192 result[3,3]:=(m1[3,0]*m2[0,3])+(m1[3,1]*m2[1,3])+(m1[3,2]*m2[2,3])+(m1[3,3]*m2[3,3]);
7193 end;
7194
7195 function Matrix4x4Lerp(const a,b:TKraftMatrix4x4;x:TKraftScalar):TKraftMatrix4x4;
7196 var ix:TKraftScalar;
7197 begin
7198 if x<=0.0 then begin
7199 result:=a;
7200 end else if x>=1.0 then begin
7201 result:=b;
7202 end else begin
7203 ix:=1.0-x;
7204 result[0,0]:=(a[0,0]*ix)+(b[0,0]*x);
7205 result[0,1]:=(a[0,1]*ix)+(b[0,1]*x);
7206 result[0,2]:=(a[0,2]*ix)+(b[0,2]*x);
7207 result[0,3]:=(a[0,3]*ix)+(b[0,3]*x);
7208 result[1,0]:=(a[1,0]*ix)+(b[1,0]*x);
7209 result[1,1]:=(a[1,1]*ix)+(b[1,1]*x);
7210 result[1,2]:=(a[1,2]*ix)+(b[1,2]*x);
7211 result[1,3]:=(a[1,3]*ix)+(b[1,3]*x);
7212 result[2,0]:=(a[2,0]*ix)+(b[2,0]*x);
7213 result[2,1]:=(a[2,1]*ix)+(b[2,1]*x);
7214 result[2,2]:=(a[2,2]*ix)+(b[2,2]*x);
7215 result[2,3]:=(a[2,3]*ix)+(b[2,3]*x);
7216 result[3,0]:=(a[3,0]*ix)+(b[3,0]*x);
7217 result[3,1]:=(a[3,1]*ix)+(b[3,1]*x);
7218 result[3,2]:=(a[3,2]*ix)+(b[3,2]*x);
7219 result[3,3]:=(a[3,3]*ix)+(b[3,3]*x);
7220 end;
7221 end;
7222
7223 function Matrix4x4Slerp(const a,b:TKraftMatrix4x4;x:TKraftScalar):TKraftMatrix4x4;
7224 var ix:TKraftScalar;
7225 m:TKraftMatrix3x3;
7226 begin
7227 if x<=0.0 then begin
7228 result:=a;
7229 end else if x>=1.0 then begin
7230 result:=b;
7231 end else begin
7232 m:=QuaternionToMatrix3x3(QuaternionSlerp(QuaternionFromMatrix4x4(a),QuaternionFromMatrix4x4(b),x));
7233 ix:=1.0-x;
7234 result[0,0]:=m[0,0];
7235 result[0,1]:=m[0,1];
7236 result[0,2]:=m[0,2];
7237 result[0,3]:=(a[0,3]*ix)+(b[0,3]*x);
7238 result[1,0]:=m[1,0];
7239 result[1,1]:=m[1,1];
7240 result[1,2]:=m[1,2];
7241 result[1,3]:=(a[1,3]*ix)+(b[1,3]*x);
7242 result[2,0]:=m[2,0];
7243 result[2,1]:=m[2,1];
7244 result[2,2]:=m[2,2];
7245 result[2,3]:=(a[2,3]*ix)+(b[2,3]*x);
7246 result[3,0]:=(a[3,0]*ix)+(b[3,0]*x);
7247 result[3,1]:=(a[3,1]*ix)+(b[3,1]*x);
7248 result[3,2]:=(a[3,2]*ix)+(b[3,2]*x);
7249 result[3,3]:=(a[3,3]*ix)+(b[3,3]*x);
7250 end;
7251 end;
7252
7253 procedure Matrix4x4ScalarMul(var m:TKraftMatrix4x4;s:TKraftScalar); {$ifdef caninline}inline;{$endif}
7254 begin
7255 m[0,0]:=m[0,0]*s;
7256 m[0,1]:=m[0,1]*s;
7257 m[0,2]:=m[0,2]*s;
7258 m[0,3]:=m[0,3]*s;
7259 m[1,0]:=m[1,0]*s;
7260 m[1,1]:=m[1,1]*s;
7261 m[1,2]:=m[1,2]*s;
7262 m[1,3]:=m[1,3]*s;
7263 m[2,0]:=m[2,0]*s;
7264 m[2,1]:=m[2,1]*s;
7265 m[2,2]:=m[2,2]*s;
7266 m[2,3]:=m[2,3]*s;
7267 m[3,0]:=m[3,0]*s;
7268 m[3,1]:=m[3,1]*s;
7269 m[3,2]:=m[3,2]*s;
7270 m[3,3]:=m[3,3]*s;
7271 end;
7272
7273 procedure Matrix4x4Transpose(var m:TKraftMatrix4x4);
7274 {$ifdef CPU386ASMForSinglePrecision}
7275 asm
7276 movups xmm0,dqword ptr [m+0]
7277 movups xmm4,dqword ptr [m+16]
7278 movups xmm2,dqword ptr [m+32]
7279 movups xmm5,dqword ptr [m+48]
7280 movaps xmm1,xmm0
7281 movaps xmm3,xmm2
7282 unpcklps xmm0,xmm4
7283 unpckhps xmm1,xmm4
7284 unpcklps xmm2,xmm5
7285 unpckhps xmm3,xmm5
7286 movaps xmm4,xmm0
7287 movaps xmm6,xmm1
7288 shufps xmm0,xmm2,$44 // 01000100b
7289 shufps xmm4,xmm2,$ee // 11101110b
7290 shufps xmm1,xmm3,$44 // 01000100b
7291 shufps xmm6,xmm3,$ee // 11101110b
7292 movups dqword ptr [m+0],xmm0
7293 movups dqword ptr [m+16],xmm4
7294 movups dqword ptr [m+32],xmm1
7295 movups dqword ptr [m+48],xmm6
7296 end;
7297 {$else}
7298 var mt:TKraftMatrix4x4;
7299 begin
7300 mt[0,0]:=m[0,0];
7301 mt[0,1]:=m[1,0];
7302 mt[0,2]:=m[2,0];
7303 mt[0,3]:=m[3,0];
7304 mt[1,0]:=m[0,1];
7305 mt[1,1]:=m[1,1];
7306 mt[1,2]:=m[2,1];
7307 mt[1,3]:=m[3,1];
7308 mt[2,0]:=m[0,2];
7309 mt[2,1]:=m[1,2];
7310 mt[2,2]:=m[2,2];
7311 mt[2,3]:=m[3,2];
7312 mt[3,0]:=m[0,3];
7313 mt[3,1]:=m[1,3];
7314 mt[3,2]:=m[2,3];
7315 mt[3,3]:=m[3,3];
7316 m:=mt;
7317 end;
7318 {$endif}
7319
7320 function Matrix4x4TermTranspose(const m:TKraftMatrix4x4):TKraftMatrix4x4;
7321 {$ifdef CPU386ASMForSinglePrecision}
7322 asm
7323 movups xmm0,dqword ptr [m+0]
7324 movups xmm4,dqword ptr [m+16]
7325 movups xmm2,dqword ptr [m+32]
7326 movups xmm5,dqword ptr [m+48]
7327 movaps xmm1,xmm0
7328 movaps xmm3,xmm2
7329 unpcklps xmm0,xmm4
7330 unpckhps xmm1,xmm4
7331 unpcklps xmm2,xmm5
7332 unpckhps xmm3,xmm5
7333 movaps xmm4,xmm0
7334 movaps xmm6,xmm1
7335 shufps xmm0,xmm2,$44 // 01000100b
7336 shufps xmm4,xmm2,$ee // 11101110b
7337 shufps xmm1,xmm3,$44 // 01000100b
7338 shufps xmm6,xmm3,$ee // 11101110b
7339 movups dqword ptr [result+0],xmm0
7340 movups dqword ptr [result+16],xmm4
7341 movups dqword ptr [result+32],xmm1
7342 movups dqword ptr [result+48],xmm6
7343 end;
7344 {$else}
7345 begin
7346 result[0,0]:=m[0,0];
7347 result[0,1]:=m[1,0];
7348 result[0,2]:=m[2,0];
7349 result[0,3]:=m[3,0];
7350 result[1,0]:=m[0,1];
7351 result[1,1]:=m[1,1];
7352 result[1,2]:=m[2,1];
7353 result[1,3]:=m[3,1];
7354 result[2,0]:=m[0,2];
7355 result[2,1]:=m[1,2];
7356 result[2,2]:=m[2,2];
7357 result[2,3]:=m[3,2];
7358 result[3,0]:=m[0,3];
7359 result[3,1]:=m[1,3];
7360 result[3,2]:=m[2,3];
7361 result[3,3]:=m[3,3];
7362 end;
7363 {$endif}
7364
7365 function Matrix4x4Determinant(const m:TKraftMatrix4x4):TKraftScalar;
7366 {$ifdef CPU386ASMForSinglePrecision}
7367 asm
7368 movups xmm0,dqword ptr [m+32]
7369 movups xmm1,dqword ptr [m+48]
7370 movups xmm2,dqword ptr [m+16]
7371 movaps xmm3,xmm0
7372 movaps xmm4,xmm0
7373 movaps xmm6,xmm1
7374 movaps xmm7,xmm2
7375 shufps xmm0,xmm0,$1b // 00011011b
7376 shufps xmm1,xmm1,$b1 // 10110001b
7377 shufps xmm2,xmm2,$4e // 01001110b
7378 shufps xmm7,xmm7,$39 // 00111001b
7379 mulps xmm0,xmm1
7380 shufps xmm3,xmm3,$7d // 01111101b
7381 shufps xmm6,xmm6,$0a // 00001010b
7382 movaps xmm5,xmm0
7383 shufps xmm0,xmm0,$4e // 01001110b
7384 shufps xmm4,xmm4,$0a // 00001010b
7385 shufps xmm1,xmm1,$28 // 00101000b
7386 subps xmm5,xmm0
7387 mulps xmm3,xmm6
7388 mulps xmm4,xmm1
7389 mulps xmm5,xmm2
7390 shufps xmm2,xmm2,$39 // 00111001b
7391 subps xmm3,xmm4
7392 movaps xmm0,xmm3
7393 shufps xmm0,xmm0,$39 // 00111001b
7394 mulps xmm3,xmm2
7395 mulps xmm0,xmm7
7396 addps xmm5,xmm3
7397 subps xmm5,xmm0
7398 movups xmm6,dqword ptr [m+0]
7399 mulps xmm5,xmm6
7400 movhlps xmm7,xmm5
7401 addps xmm5,xmm7
7402 movaps xmm6,xmm5
7403 shufps xmm6,xmm6,$01
7404 addss xmm5,xmm6
7405 movss dword ptr [result],xmm5
7406 end;
7407 {$else}
7408 var inv:array[0..15] of TKraftScalar;
7409 begin
7410 inv[0]:=(((m[1,1]*m[2,2]*m[3,3])-(m[1,1]*m[2,3]*m[3,2]))-(m[2,1]*m[1,2]*m[3,3])+(m[2,1]*m[1,3]*m[3,2])+(m[3,1]*m[1,2]*m[2,3]))-(m[3,1]*m[1,3]*m[2,2]);
7411 inv[4]:=((((-(m[1,0]*m[2,2]*m[3,3]))+(m[1,0]*m[2,3]*m[3,2])+(m[2,0]*m[1,2]*m[3,3]))-(m[2,0]*m[1,3]*m[3,2]))-(m[3,0]*m[1,2]*m[2,3]))+(m[3,0]*m[1,3]*m[2,2]);
7412 inv[8]:=((((m[1,0]*m[2,1]*m[3,3])-(m[1,0]*m[2,3]*m[3,1]))-(m[2,0]*m[1,1]*m[3,3]))+(m[2,0]*m[1,3]*m[3,1])+(m[3,0]*m[1,1]*m[2,3]))-(m[3,0]*m[1,3]*m[2,1]);
7413 inv[12]:=((((-(m[1,0]*m[2,1]*m[3,2]))+(m[1,0]*m[2,2]*m[3,1])+(m[2,0]*m[1,1]*m[3,2]))-(m[2,0]*m[1,2]*m[3,1]))-(m[3,0]*m[1,1]*m[2,2]))+(m[3,0]*m[1,2]*m[2,1]);
7414 inv[1]:=((((-(m[0,1]*m[2,2]*m[3,3]))+(m[0,1]*m[2,3]*m[3,2])+(m[2,1]*m[0,2]*m[3,3]))-(m[2,1]*m[0,3]*m[3,2]))-(m[3,1]*m[0,2]*m[2,3]))+(m[3,1]*m[0,3]*m[2,2]);
7415 inv[5]:=(((m[0,0]*m[2,2]*m[3,3])-(m[0,0]*m[2,3]*m[3,2]))-(m[2,0]*m[0,2]*m[3,3])+(m[2,0]*m[0,3]*m[3,2])+(m[3,0]*m[0,2]*m[2,3]))-(m[3,0]*m[0,3]*m[2,2]);
7416 inv[9]:=((((-(m[0,0]*m[2,1]*m[3,3]))+(m[0,0]*m[2,3]*m[3,1])+(m[2,0]*m[0,1]*m[3,3]))-(m[2,0]*m[0,3]*m[3,1]))-(m[3,0]*m[0,1]*m[2,3]))+(m[3,0]*m[0,3]*m[2,1]);
7417 inv[13]:=((((m[0,0]*m[2,1]*m[3,2])-(m[0,0]*m[2,2]*m[3,1]))-(m[2,0]*m[0,1]*m[3,2]))+(m[2,0]*m[0,2]*m[3,1])+(m[3,0]*m[0,1]*m[2,2]))-(m[3,0]*m[0,2]*m[2,1]);
7418 inv[2]:=((((m[0,1]*m[1,2]*m[3,3])-(m[0,1]*m[1,3]*m[3,2]))-(m[1,1]*m[0,2]*m[3,3]))+(m[1,1]*m[0,3]*m[3,2])+(m[3,1]*m[0,2]*m[1,3]))-(m[3,1]*m[0,3]*m[1,2]);
7419 inv[6]:=((((-(m[0,0]*m[1,2]*m[3,3]))+(m[0,0]*m[1,3]*m[3,2])+(m[1,0]*m[0,2]*m[3,3]))-(m[1,0]*m[0,3]*m[3,2]))-(m[3,0]*m[0,2]*m[1,3]))+(m[3,0]*m[0,3]*m[1,2]);
7420 inv[10]:=((((m[0,0]*m[1,1]*m[3,3])-(m[0,0]*m[1,3]*m[3,1]))-(m[1,0]*m[0,1]*m[3,3]))+(m[1,0]*m[0,3]*m[3,1])+(m[3,0]*m[0,1]*m[1,3]))-(m[3,0]*m[0,3]*m[1,1]);
7421 inv[14]:=((((-(m[0,0]*m[1,1]*m[3,2]))+(m[0,0]*m[1,2]*m[3,1])+(m[1,0]*m[0,1]*m[3,2]))-(m[1,0]*m[0,2]*m[3,1]))-(m[3,0]*m[0,1]*m[1,2]))+(m[3,0]*m[0,2]*m[1,1]);
7422 inv[3]:=((((-(m[0,1]*m[1,2]*m[2,3]))+(m[0,1]*m[1,3]*m[2,2])+(m[1,1]*m[0,2]*m[2,3]))-(m[1,1]*m[0,3]*m[2,2]))-(m[2,1]*m[0,2]*m[1,3]))+(m[2,1]*m[0,3]*m[1,2]);
7423 inv[7]:=((((m[0,0]*m[1,2]*m[2,3])-(m[0,0]*m[1,3]*m[2,2]))-(m[1,0]*m[0,2]*m[2,3]))+(m[1,0]*m[0,3]*m[2,2])+(m[2,0]*m[0,2]*m[1,3]))-(m[2,0]*m[0,3]*m[1,2]);
7424 inv[11]:=((((-(m[0,0]*m[1,1]*m[2,3]))+(m[0,0]*m[1,3]*m[2,1])+(m[1,0]*m[0,1]*m[2,3]))-(m[1,0]*m[0,3]*m[2,1]))-(m[2,0]*m[0,1]*m[1,3]))+(m[2,0]*m[0,3]*m[1,1]);
7425 inv[15]:=((((m[0,0]*m[1,1]*m[2,2])-(m[0,0]*m[1,2]*m[2,1]))-(m[1,0]*m[0,1]*m[2,2]))+(m[1,0]*m[0,2]*m[2,1])+(m[2,0]*m[0,1]*m[1,2]))-(m[2,0]*m[0,2]*m[1,1]);
7426 result:=(m[0,0]*inv[0])+(m[0,1]*inv[4])+(m[0,2]*inv[8])+(m[0,3]*inv[12]);
7427 end;
7428 {$endif}
7429
7430 procedure Matrix4x4SetColumn(var m:TKraftMatrix4x4;const c:longint;const v:TKraftVector4); {$ifdef caninline}inline;{$endif}
7431 begin
7432 m[c,0]:=v.x;
7433 m[c,1]:=v.y;
7434 m[c,2]:=v.z;
7435 m[c,3]:=v.w;
7436 end;
7437
7438 function Matrix4x4GetColumn(const m:TKraftMatrix4x4;const c:longint):TKraftVector4; {$ifdef caninline}inline;{$endif}
7439 begin
7440 result.x:=m[c,0];
7441 result.y:=m[c,1];
7442 result.z:=m[c,2];
7443 result.w:=m[c,3];
7444 end;
7445
7446 procedure Matrix4x4SetRow(var m:TKraftMatrix4x4;const r:longint;const v:TKraftVector4); {$ifdef caninline}inline;{$endif}
7447 begin
7448 m[0,r]:=v.x;
7449 m[1,r]:=v.y;
7450 m[2,r]:=v.z;
7451 m[3,r]:=v.w;
7452 end;
7453
7454 function Matrix4x4GetRow(const m:TKraftMatrix4x4;const r:longint):TKraftVector4; {$ifdef caninline}inline;{$endif}
7455 begin
7456 result.x:=m[0,r];
7457 result.y:=m[1,r];
7458 result.z:=m[2,r];
7459 result.w:=m[3,r];
7460 end;
7461
7462 function Matrix4x4Compare(const m1,m2:TKraftMatrix4x4):boolean;
7463 var r,c:longint;
7464 begin
7465 result:=true;
7466 for r:=0 to 3 do begin
7467 for c:=0 to 3 do begin
7468 if abs(m1[r,c]-m2[r,c])>EPSILON then begin
7469 result:=false;
7470 exit;
7471 end;
7472 end;
7473 end;
7474 end;
7475
7476 function Matrix4x4LengthSquared(const m:TKraftMatrix4x4):TKraftScalar;
7477 begin
7478 result:=Vector4LengthSquared(PKraftVector4(pointer(@m[0,0]))^)+
7479 Vector4LengthSquared(PKraftVector4(pointer(@m[1,0]))^)+
7480 Vector4LengthSquared(PKraftVector4(pointer(@m[2,0]))^)+
7481 Vector4LengthSquared(PKraftVector4(pointer(@m[3,0]))^);
7482 end;
7483
7484 function Matrix4x4Length(const m:TKraftMatrix4x4):TKraftScalar;
7485 begin
7486 result:=Matrix4x4LengthSquared(m);
7487 if result>0.0 then begin
7488 result:=sqrt(result);
7489 end else begin
7490 result:=0.0;
7491 end;
7492 end;
7493
7494 function Matrix4x4DifferenceSquared(const m1,m2:TKraftMatrix4x4):TKraftScalar;
7495 begin
7496 result:=Matrix4x4LengthSquared(Matrix4x4TermSub(m2,m1));
7497 end;
7498
7499 function Matrix4x4Difference(const m1,m2:TKraftMatrix4x4):TKraftScalar;
7500 begin
7501 result:=Matrix4x4Length(Matrix4x4TermSub(m2,m1));
7502 end;
7503
7504 procedure Matrix4x4Reflect(var mr:TKraftMatrix4x4;Plane:TKraftPlane);
7505 begin
7506 PlaneNormalize(Plane);
7507 mr[0,0]:=1.0-(2.0*(Plane.Normal.x*Plane.Normal.x));
7508 mr[0,1]:=-(2.0*(Plane.Normal.x*Plane.Normal.y));
7509 mr[0,2]:=-(2.0*(Plane.Normal.x*Plane.Normal.z));
7510 mr[0,3]:=0.0;
7511 mr[1,0]:=-(2.0*(Plane.Normal.x*Plane.Normal.y));
7512 mr[1,1]:=1.0-(2.0*(Plane.Normal.y*Plane.Normal.y));
7513 mr[1,2]:=-(2.0*(Plane.Normal.y*Plane.Normal.z));
7514 mr[1,3]:=0.0;
7515 mr[2,0]:=-(2.0*(Plane.Normal.z*Plane.Normal.x));
7516 mr[2,1]:=-(2.0*(Plane.Normal.z*Plane.Normal.y));
7517 mr[2,2]:=1.0-(2.0*(Plane.Normal.z*Plane.Normal.z));
7518 mr[2,3]:=0.0;
7519 mr[3,0]:=-(2.0*(Plane.Distance*Plane.Normal.x));
7520 mr[3,1]:=-(2.0*(Plane.Distance*Plane.Normal.y));
7521 mr[3,2]:=-(2.0*(Plane.Distance*Plane.Normal.z));
7522 mr[3,3]:=1.0;
7523 end;
7524
7525 function Matrix4x4TermReflect(Plane:TKraftPlane):TKraftMatrix4x4;
7526 begin
7527 PlaneNormalize(Plane);
7528 result[0,0]:=1.0-(2.0*(Plane.Normal.x*Plane.Normal.x));
7529 result[0,1]:=-(2.0*(Plane.Normal.x*Plane.Normal.y));
7530 result[0,2]:=-(2.0*(Plane.Normal.x*Plane.Normal.z));
7531 result[0,3]:=0.0;
7532 result[1,0]:=-(2.0*(Plane.Normal.x*Plane.Normal.y));
7533 result[1,1]:=1.0-(2.0*(Plane.Normal.y*Plane.Normal.y));
7534 result[1,2]:=-(2.0*(Plane.Normal.y*Plane.Normal.z));
7535 result[1,3]:=0.0;
7536 result[2,0]:=-(2.0*(Plane.Normal.z*Plane.Normal.x));
7537 result[2,1]:=-(2.0*(Plane.Normal.z*Plane.Normal.y));
7538 result[2,2]:=1.0-(2.0*(Plane.Normal.z*Plane.Normal.z));
7539 result[2,3]:=0.0;
7540 result[3,0]:=-(2.0*(Plane.Distance*Plane.Normal.x));
7541 result[3,1]:=-(2.0*(Plane.Distance*Plane.Normal.y));
7542 result[3,2]:=-(2.0*(Plane.Distance*Plane.Normal.z));
7543 result[3,3]:=1.0;
7544 end;
7545
7546 function Matrix4x4SimpleInverse(var mr:TKraftMatrix4x4;const ma:TKraftMatrix4x4):boolean; {$ifdef caninline}inline;{$endif}
7547 begin
7548 mr[0,0]:=ma[0,0];
7549 mr[0,1]:=ma[1,0];
7550 mr[0,2]:=ma[2,0];
7551 mr[0,3]:=ma[0,3];
7552 mr[1,0]:=ma[0,1];
7553 mr[1,1]:=ma[1,1];
7554 mr[1,2]:=ma[2,1];
7555 mr[1,3]:=ma[1,3];
7556 mr[2,0]:=ma[0,2];
7557 mr[2,1]:=ma[1,2];
7558 mr[2,2]:=ma[2,2];
7559 mr[2,3]:=ma[2,3];
7560 mr[3,0]:=-Vector3Dot(PKraftVector3(pointer(@ma[3,0]))^,Vector3(ma[0,0],ma[0,1],ma[0,2]));
7561 mr[3,1]:=-Vector3Dot(PKraftVector3(pointer(@ma[3,0]))^,Vector3(ma[1,0],ma[1,1],ma[1,2]));
7562 mr[3,2]:=-Vector3Dot(PKraftVector3(pointer(@ma[3,0]))^,Vector3(ma[2,0],ma[2,1],ma[2,2]));
7563 mr[3,3]:=ma[3,3];
7564 result:=true;
7565 end;
7566
7567 function Matrix4x4TermSimpleInverse(const ma:TKraftMatrix4x4):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
7568 begin
7569 result[0,0]:=ma[0,0];
7570 result[0,1]:=ma[1,0];
7571 result[0,2]:=ma[2,0];
7572 result[0,3]:=ma[0,3];
7573 result[1,0]:=ma[0,1];
7574 result[1,1]:=ma[1,1];
7575 result[1,2]:=ma[2,1];
7576 result[1,3]:=ma[1,3];
7577 result[2,0]:=ma[0,2];
7578 result[2,1]:=ma[1,2];
7579 result[2,2]:=ma[2,2];
7580 result[2,3]:=ma[2,3];
7581 result[3,0]:=-Vector3Dot(PKraftVector3(pointer(@ma[3,0]))^,Vector3(ma[0,0],ma[0,1],ma[0,2]));
7582 result[3,1]:=-Vector3Dot(PKraftVector3(pointer(@ma[3,0]))^,Vector3(ma[1,0],ma[1,1],ma[1,2]));
7583 result[3,2]:=-Vector3Dot(PKraftVector3(pointer(@ma[3,0]))^,Vector3(ma[2,0],ma[2,1],ma[2,2]));
7584 result[3,3]:=ma[3,3];
7585 end;
7586
7587 function Matrix4x4Inverse(var mr:TKraftMatrix4x4;const ma:TKraftMatrix4x4):boolean;
7588 {$ifdef CPU386ASMForSinglePrecision}
7589 asm
7590 mov ecx,esp
7591 and esp,$fffffff0
7592 sub esp,$b0
7593 movlps xmm2,qword ptr [ma+8]
7594 movlps xmm4,qword ptr [ma+40]
7595 movhps xmm2,qword ptr [ma+24]
7596 movhps xmm4,qword ptr [ma+56]
7597 movlps xmm3,qword ptr [ma+32]
7598 movlps xmm1,qword ptr [ma]
7599 movhps xmm3,qword ptr [ma+48]
7600 movhps xmm1,qword ptr [ma+16]
7601 movaps xmm5,xmm2
7602 shufps xmm5,xmm4,$88
7603 shufps xmm4,xmm2,$dd
7604 movaps xmm2,xmm4
7605 mulps xmm2,xmm5
7606 shufps xmm2,xmm2,$b1
7607 movaps xmm6,xmm2
7608 shufps xmm6,xmm6,$4e
7609 movaps xmm7,xmm3
7610 shufps xmm3,xmm1,$dd
7611 shufps xmm1,xmm7,$88
7612 movaps xmm7,xmm3
7613 mulps xmm3,xmm6
7614 mulps xmm6,xmm1
7615 movaps xmm0,xmm6
7616 movaps xmm6,xmm7
7617 mulps xmm7,xmm2
7618 mulps xmm2,xmm1
7619 subps xmm3,xmm7
7620 movaps xmm7,xmm6
7621 mulps xmm7,xmm5
7622 shufps xmm5,xmm5,$4e
7623 shufps xmm7,xmm7,$b1
7624 movaps dqword ptr [esp+16],xmm2
7625 movaps xmm2,xmm4
7626 mulps xmm2,xmm7
7627 addps xmm2,xmm3
7628 movaps xmm3,xmm7
7629 shufps xmm7,xmm7,$4e
7630 mulps xmm3,xmm1
7631 movaps dqword ptr [esp+32],xmm3
7632 movaps xmm3,xmm4
7633 mulps xmm3,xmm7
7634 mulps xmm7,xmm1
7635 subps xmm2,xmm3
7636 movaps xmm3,xmm6
7637 shufps xmm3,xmm3,$4e
7638 mulps xmm3,xmm4
7639 shufps xmm3,xmm3,$b1
7640 movaps dqword ptr [esp+48],xmm7
7641 movaps xmm7,xmm5
7642 mulps xmm5,xmm3
7643 addps xmm5,xmm2
7644 movaps xmm2,xmm3
7645 shufps xmm3,xmm3,$4e
7646 mulps xmm2,xmm1
7647 movaps dqword ptr [esp+64],xmm4
7648 movaps xmm4,xmm7
7649 mulps xmm7,xmm3
7650 mulps xmm3,xmm1
7651 subps xmm5,xmm7
7652 subps xmm3,xmm2
7653 movaps xmm2,xmm1
7654 mulps xmm1,xmm5
7655 shufps xmm3,xmm3,$4e
7656 movaps xmm7,xmm1
7657 shufps xmm1,xmm1,$4e
7658 movaps dqword ptr [esp],xmm5
7659 addps xmm1,xmm7
7660 movaps xmm5,xmm1
7661 shufps xmm1,xmm1,$b1
7662 addss xmm1,xmm5
7663 movaps xmm5,xmm6
7664 mulps xmm5,xmm2
7665 shufps xmm5,xmm5,$b1
7666 movaps xmm7,xmm5
7667 shufps xmm5,xmm5,$4e
7668 movaps dqword ptr [esp+80],xmm4
7669 movaps xmm4,dqword ptr [esp+64]
7670 movaps dqword ptr [esp+64],xmm6
7671 movaps xmm6,xmm4
7672 mulps xmm6,xmm7
7673 addps xmm6,xmm3
7674 movaps xmm3,xmm4
7675 mulps xmm3,xmm5
7676 subps xmm3,xmm6
7677 movaps xmm6,xmm4
7678 mulps xmm6,xmm2
7679 shufps xmm6,xmm6,$b1
7680 movaps dqword ptr [esp+112],xmm5
7681 movaps xmm5,dqword ptr [esp+64]
7682 movaps dqword ptr [esp+128],xmm7
7683 movaps xmm7,xmm6
7684 mulps xmm7,xmm5
7685 addps xmm7,xmm3
7686 movaps xmm3,xmm6
7687 shufps xmm3,xmm3,$4e
7688 movaps dqword ptr [esp+144],xmm4
7689 movaps xmm4,xmm5
7690 mulps xmm5,xmm3
7691 movaps dqword ptr [esp+160],xmm4
7692 movaps xmm4,xmm6
7693 movaps xmm6,xmm7
7694 subps xmm6,xmm5
7695 movaps xmm5,xmm0
7696 movaps xmm7,dqword ptr [esp+16]
7697 subps xmm5,xmm7
7698 shufps xmm5,xmm5,$4e
7699 movaps xmm7,dqword ptr [esp+80]
7700 mulps xmm4,xmm7
7701 mulps xmm3,xmm7
7702 subps xmm5,xmm4
7703 mulps xmm2,xmm7
7704 addps xmm3,xmm5
7705 shufps xmm2,xmm2,$b1
7706 movaps xmm4,xmm2
7707 shufps xmm4,xmm4,$4e
7708 movaps xmm5,dqword ptr [esp+144]
7709 movaps xmm0,xmm6
7710 movaps xmm6,xmm5
7711 mulps xmm5,xmm2
7712 mulps xmm6,xmm4
7713 addps xmm5,xmm3
7714 movaps xmm3,xmm4
7715 movaps xmm4,xmm5
7716 subps xmm4,xmm6
7717 movaps xmm5,dqword ptr [esp+48]
7718 movaps xmm6,dqword ptr [esp+32]
7719 subps xmm5,xmm6
7720 shufps xmm5,xmm5,$4e
7721 movaps xmm6,[esp+128]
7722 mulps xmm6,xmm7
7723 subps xmm6,xmm5
7724 movaps xmm5,dqword ptr [esp+112]
7725 mulps xmm7,xmm5
7726 subps xmm6,xmm7
7727 movaps xmm5,dqword ptr [esp+160]
7728 mulps xmm2,xmm5
7729 mulps xmm5,xmm3
7730 subps xmm6,xmm2
7731 movaps xmm2,xmm5
7732 addps xmm2,xmm6
7733 movaps xmm6,xmm0
7734 movaps xmm0,xmm1
7735 movaps xmm1,dqword ptr [esp]
7736 movaps xmm3,xmm0
7737 rcpss xmm5,xmm0
7738 mulss xmm0,xmm5
7739 mulss xmm0,xmm5
7740 addss xmm5,xmm5
7741 subss xmm5,xmm0
7742 movaps xmm0,xmm5
7743 addss xmm5,xmm5
7744 mulss xmm0,xmm0
7745 mulss xmm3,xmm0
7746 subss xmm5,xmm3
7747 shufps xmm5,xmm5,$00
7748 mulps xmm1,xmm5
7749 mulps xmm4,xmm5
7750 mulps xmm6,xmm5
7751 mulps xmm5,xmm2
7752 movups dqword ptr [mr+0],xmm1
7753 movups dqword ptr [mr+16],xmm4
7754 movups dqword ptr [mr+32],xmm6
7755 movups dqword ptr [mr+48],xmm5
7756 mov esp,ecx
7757 mov eax,1
7758 end;
7759 {$else}
7760 var inv:array[0..15] of TKraftScalar;
7761 det:TKraftScalar;
7762 begin
7763 inv[0]:=(((ma[1,1]*ma[2,2]*ma[3,3])-(ma[1,1]*ma[2,3]*ma[3,2]))-(ma[2,1]*ma[1,2]*ma[3,3])+(ma[2,1]*ma[1,3]*ma[3,2])+(ma[3,1]*ma[1,2]*ma[2,3]))-(ma[3,1]*ma[1,3]*ma[2,2]);
7764 inv[4]:=((((-(ma[1,0]*ma[2,2]*ma[3,3]))+(ma[1,0]*ma[2,3]*ma[3,2])+(ma[2,0]*ma[1,2]*ma[3,3]))-(ma[2,0]*ma[1,3]*ma[3,2]))-(ma[3,0]*ma[1,2]*ma[2,3]))+(ma[3,0]*ma[1,3]*ma[2,2]);
7765 inv[8]:=((((ma[1,0]*ma[2,1]*ma[3,3])-(ma[1,0]*ma[2,3]*ma[3,1]))-(ma[2,0]*ma[1,1]*ma[3,3]))+(ma[2,0]*ma[1,3]*ma[3,1])+(ma[3,0]*ma[1,1]*ma[2,3]))-(ma[3,0]*ma[1,3]*ma[2,1]);
7766 inv[12]:=((((-(ma[1,0]*ma[2,1]*ma[3,2]))+(ma[1,0]*ma[2,2]*ma[3,1])+(ma[2,0]*ma[1,1]*ma[3,2]))-(ma[2,0]*ma[1,2]*ma[3,1]))-(ma[3,0]*ma[1,1]*ma[2,2]))+(ma[3,0]*ma[1,2]*ma[2,1]);
7767 inv[1]:=((((-(ma[0,1]*ma[2,2]*ma[3,3]))+(ma[0,1]*ma[2,3]*ma[3,2])+(ma[2,1]*ma[0,2]*ma[3,3]))-(ma[2,1]*ma[0,3]*ma[3,2]))-(ma[3,1]*ma[0,2]*ma[2,3]))+(ma[3,1]*ma[0,3]*ma[2,2]);
7768 inv[5]:=(((ma[0,0]*ma[2,2]*ma[3,3])-(ma[0,0]*ma[2,3]*ma[3,2]))-(ma[2,0]*ma[0,2]*ma[3,3])+(ma[2,0]*ma[0,3]*ma[3,2])+(ma[3,0]*ma[0,2]*ma[2,3]))-(ma[3,0]*ma[0,3]*ma[2,2]);
7769 inv[9]:=((((-(ma[0,0]*ma[2,1]*ma[3,3]))+(ma[0,0]*ma[2,3]*ma[3,1])+(ma[2,0]*ma[0,1]*ma[3,3]))-(ma[2,0]*ma[0,3]*ma[3,1]))-(ma[3,0]*ma[0,1]*ma[2,3]))+(ma[3,0]*ma[0,3]*ma[2,1]);
7770 inv[13]:=((((ma[0,0]*ma[2,1]*ma[3,2])-(ma[0,0]*ma[2,2]*ma[3,1]))-(ma[2,0]*ma[0,1]*ma[3,2]))+(ma[2,0]*ma[0,2]*ma[3,1])+(ma[3,0]*ma[0,1]*ma[2,2]))-(ma[3,0]*ma[0,2]*ma[2,1]);
7771 inv[2]:=((((ma[0,1]*ma[1,2]*ma[3,3])-(ma[0,1]*ma[1,3]*ma[3,2]))-(ma[1,1]*ma[0,2]*ma[3,3]))+(ma[1,1]*ma[0,3]*ma[3,2])+(ma[3,1]*ma[0,2]*ma[1,3]))-(ma[3,1]*ma[0,3]*ma[1,2]);
7772 inv[6]:=((((-(ma[0,0]*ma[1,2]*ma[3,3]))+(ma[0,0]*ma[1,3]*ma[3,2])+(ma[1,0]*ma[0,2]*ma[3,3]))-(ma[1,0]*ma[0,3]*ma[3,2]))-(ma[3,0]*ma[0,2]*ma[1,3]))+(ma[3,0]*ma[0,3]*ma[1,2]);
7773 inv[10]:=((((ma[0,0]*ma[1,1]*ma[3,3])-(ma[0,0]*ma[1,3]*ma[3,1]))-(ma[1,0]*ma[0,1]*ma[3,3]))+(ma[1,0]*ma[0,3]*ma[3,1])+(ma[3,0]*ma[0,1]*ma[1,3]))-(ma[3,0]*ma[0,3]*ma[1,1]);
7774 inv[14]:=((((-(ma[0,0]*ma[1,1]*ma[3,2]))+(ma[0,0]*ma[1,2]*ma[3,1])+(ma[1,0]*ma[0,1]*ma[3,2]))-(ma[1,0]*ma[0,2]*ma[3,1]))-(ma[3,0]*ma[0,1]*ma[1,2]))+(ma[3,0]*ma[0,2]*ma[1,1]);
7775 inv[3]:=((((-(ma[0,1]*ma[1,2]*ma[2,3]))+(ma[0,1]*ma[1,3]*ma[2,2])+(ma[1,1]*ma[0,2]*ma[2,3]))-(ma[1,1]*ma[0,3]*ma[2,2]))-(ma[2,1]*ma[0,2]*ma[1,3]))+(ma[2,1]*ma[0,3]*ma[1,2]);
7776 inv[7]:=((((ma[0,0]*ma[1,2]*ma[2,3])-(ma[0,0]*ma[1,3]*ma[2,2]))-(ma[1,0]*ma[0,2]*ma[2,3]))+(ma[1,0]*ma[0,3]*ma[2,2])+(ma[2,0]*ma[0,2]*ma[1,3]))-(ma[2,0]*ma[0,3]*ma[1,2]);
7777 inv[11]:=((((-(ma[0,0]*ma[1,1]*ma[2,3]))+(ma[0,0]*ma[1,3]*ma[2,1])+(ma[1,0]*ma[0,1]*ma[2,3]))-(ma[1,0]*ma[0,3]*ma[2,1]))-(ma[2,0]*ma[0,1]*ma[1,3]))+(ma[2,0]*ma[0,3]*ma[1,1]);
7778 inv[15]:=((((ma[0,0]*ma[1,1]*ma[2,2])-(ma[0,0]*ma[1,2]*ma[2,1]))-(ma[1,0]*ma[0,1]*ma[2,2]))+(ma[1,0]*ma[0,2]*ma[2,1])+(ma[2,0]*ma[0,1]*ma[1,2]))-(ma[2,0]*ma[0,2]*ma[1,1]);
7779 det:=(ma[0,0]*inv[0])+(ma[0,1]*inv[4])+(ma[0,2]*inv[8])+(ma[0,3]*inv[12]);
7780 if det<>0.0 then begin
7781 det:=1.0/det;
7782 mr[0,0]:=inv[0]*det;
7783 mr[0,1]:=inv[1]*det;
7784 mr[0,2]:=inv[2]*det;
7785 mr[0,3]:=inv[3]*det;
7786 mr[1,0]:=inv[4]*det;
7787 mr[1,1]:=inv[5]*det;
7788 mr[1,2]:=inv[6]*det;
7789 mr[1,3]:=inv[7]*det;
7790 mr[2,0]:=inv[8]*det;
7791 mr[2,1]:=inv[9]*det;
7792 mr[2,2]:=inv[10]*det;
7793 mr[2,3]:=inv[11]*det;
7794 mr[3,0]:=inv[12]*det;
7795 mr[3,1]:=inv[13]*det;
7796 mr[3,2]:=inv[14]*det;
7797 mr[3,3]:=inv[15]*det;
7798 result:=true;
7799 end else begin
7800 result:=false;
7801 end;
7802 end;
7803 {$endif}
7804
7805 function Matrix4x4TermInverse(const ma:TKraftMatrix4x4):TKraftMatrix4x4;
7806 {$ifdef CPU386ASMForSinglePrecision}
7807 asm
7808 mov ecx,esp
7809 and esp,$fffffff0
7810 sub esp,$b0
7811 movlps xmm2,qword ptr [ma+8]
7812 movlps xmm4,qword ptr [ma+40]
7813 movhps xmm2,qword ptr [ma+24]
7814 movhps xmm4,qword ptr [ma+56]
7815 movlps xmm3,qword ptr [ma+32]
7816 movlps xmm1,qword ptr [ma]
7817 movhps xmm3,qword ptr [ma+48]
7818 movhps xmm1,qword ptr [ma+16]
7819 movaps xmm5,xmm2
7820 shufps xmm5,xmm4,$88
7821 shufps xmm4,xmm2,$dd
7822 movaps xmm2,xmm4
7823 mulps xmm2,xmm5
7824 shufps xmm2,xmm2,$b1
7825 movaps xmm6,xmm2
7826 shufps xmm6,xmm6,$4e
7827 movaps xmm7,xmm3
7828 shufps xmm3,xmm1,$dd
7829 shufps xmm1,xmm7,$88
7830 movaps xmm7,xmm3
7831 mulps xmm3,xmm6
7832 mulps xmm6,xmm1
7833 movaps xmm0,xmm6
7834 movaps xmm6,xmm7
7835 mulps xmm7,xmm2
7836 mulps xmm2,xmm1
7837 subps xmm3,xmm7
7838 movaps xmm7,xmm6
7839 mulps xmm7,xmm5
7840 shufps xmm5,xmm5,$4e
7841 shufps xmm7,xmm7,$b1
7842 movaps dqword ptr [esp+16],xmm2
7843 movaps xmm2,xmm4
7844 mulps xmm2,xmm7
7845 addps xmm2,xmm3
7846 movaps xmm3,xmm7
7847 shufps xmm7,xmm7,$4e
7848 mulps xmm3,xmm1
7849 movaps dqword ptr [esp+32],xmm3
7850 movaps xmm3,xmm4
7851 mulps xmm3,xmm7
7852 mulps xmm7,xmm1
7853 subps xmm2,xmm3
7854 movaps xmm3,xmm6
7855 shufps xmm3,xmm3,$4e
7856 mulps xmm3,xmm4
7857 shufps xmm3,xmm3,$b1
7858 movaps dqword ptr [esp+48],xmm7
7859 movaps xmm7,xmm5
7860 mulps xmm5,xmm3
7861 addps xmm5,xmm2
7862 movaps xmm2,xmm3
7863 shufps xmm3,xmm3,$4e
7864 mulps xmm2,xmm1
7865 movaps dqword ptr [esp+64],xmm4
7866 movaps xmm4,xmm7
7867 mulps xmm7,xmm3
7868 mulps xmm3,xmm1
7869 subps xmm5,xmm7
7870 subps xmm3,xmm2
7871 movaps xmm2,xmm1
7872 mulps xmm1,xmm5
7873 shufps xmm3,xmm3,$4e
7874 movaps xmm7,xmm1
7875 shufps xmm1,xmm1,$4e
7876 movaps dqword ptr [esp],xmm5
7877 addps xmm1,xmm7
7878 movaps xmm5,xmm1
7879 shufps xmm1,xmm1,$b1
7880 addss xmm1,xmm5
7881 movaps xmm5,xmm6
7882 mulps xmm5,xmm2
7883 shufps xmm5,xmm5,$b1
7884 movaps xmm7,xmm5
7885 shufps xmm5,xmm5,$4e
7886 movaps dqword ptr [esp+80],xmm4
7887 movaps xmm4,dqword ptr [esp+64]
7888 movaps dqword ptr [esp+64],xmm6
7889 movaps xmm6,xmm4
7890 mulps xmm6,xmm7
7891 addps xmm6,xmm3
7892 movaps xmm3,xmm4
7893 mulps xmm3,xmm5
7894 subps xmm3,xmm6
7895 movaps xmm6,xmm4
7896 mulps xmm6,xmm2
7897 shufps xmm6,xmm6,$b1
7898 movaps dqword ptr [esp+112],xmm5
7899 movaps xmm5,dqword ptr [esp+64]
7900 movaps dqword ptr [esp+128],xmm7
7901 movaps xmm7,xmm6
7902 mulps xmm7,xmm5
7903 addps xmm7,xmm3
7904 movaps xmm3,xmm6
7905 shufps xmm3,xmm3,$4e
7906 movaps dqword ptr [esp+144],xmm4
7907 movaps xmm4,xmm5
7908 mulps xmm5,xmm3
7909 movaps dqword ptr [esp+160],xmm4
7910 movaps xmm4,xmm6
7911 movaps xmm6,xmm7
7912 subps xmm6,xmm5
7913 movaps xmm5,xmm0
7914 movaps xmm7,dqword ptr [esp+16]
7915 subps xmm5,xmm7
7916 shufps xmm5,xmm5,$4e
7917 movaps xmm7,dqword ptr [esp+80]
7918 mulps xmm4,xmm7
7919 mulps xmm3,xmm7
7920 subps xmm5,xmm4
7921 mulps xmm2,xmm7
7922 addps xmm3,xmm5
7923 shufps xmm2,xmm2,$b1
7924 movaps xmm4,xmm2
7925 shufps xmm4,xmm4,$4e
7926 movaps xmm5,dqword ptr [esp+144]
7927 movaps xmm0,xmm6
7928 movaps xmm6,xmm5
7929 mulps xmm5,xmm2
7930 mulps xmm6,xmm4
7931 addps xmm5,xmm3
7932 movaps xmm3,xmm4
7933 movaps xmm4,xmm5
7934 subps xmm4,xmm6
7935 movaps xmm5,dqword ptr [esp+48]
7936 movaps xmm6,dqword ptr [esp+32]
7937 subps xmm5,xmm6
7938 shufps xmm5,xmm5,$4e
7939 movaps xmm6,[esp+128]
7940 mulps xmm6,xmm7
7941 subps xmm6,xmm5
7942 movaps xmm5,dqword ptr [esp+112]
7943 mulps xmm7,xmm5
7944 subps xmm6,xmm7
7945 movaps xmm5,dqword ptr [esp+160]
7946 mulps xmm2,xmm5
7947 mulps xmm5,xmm3
7948 subps xmm6,xmm2
7949 movaps xmm2,xmm5
7950 addps xmm2,xmm6
7951 movaps xmm6,xmm0
7952 movaps xmm0,xmm1
7953 movaps xmm1,dqword ptr [esp]
7954 movaps xmm3,xmm0
7955 rcpss xmm5,xmm0
7956 mulss xmm0,xmm5
7957 mulss xmm0,xmm5
7958 addss xmm5,xmm5
7959 subss xmm5,xmm0
7960 movaps xmm0,xmm5
7961 addss xmm5,xmm5
7962 mulss xmm0,xmm0
7963 mulss xmm3,xmm0
7964 subss xmm5,xmm3
7965 shufps xmm5,xmm5,$00
7966 mulps xmm1,xmm5
7967 mulps xmm4,xmm5
7968 mulps xmm6,xmm5
7969 mulps xmm5,xmm2
7970 movups dqword ptr [result+0],xmm1
7971 movups dqword ptr [result+16],xmm4
7972 movups dqword ptr [result+32],xmm6
7973 movups dqword ptr [result+48],xmm5
7974 mov esp,ecx
7975 end;
7976 {$else}
7977 var inv:array[0..15] of TKraftScalar;
7978 det:TKraftScalar;
7979 begin
7980 inv[0]:=(((ma[1,1]*ma[2,2]*ma[3,3])-(ma[1,1]*ma[2,3]*ma[3,2]))-(ma[2,1]*ma[1,2]*ma[3,3])+(ma[2,1]*ma[1,3]*ma[3,2])+(ma[3,1]*ma[1,2]*ma[2,3]))-(ma[3,1]*ma[1,3]*ma[2,2]);
7981 inv[4]:=((((-(ma[1,0]*ma[2,2]*ma[3,3]))+(ma[1,0]*ma[2,3]*ma[3,2])+(ma[2,0]*ma[1,2]*ma[3,3]))-(ma[2,0]*ma[1,3]*ma[3,2]))-(ma[3,0]*ma[1,2]*ma[2,3]))+(ma[3,0]*ma[1,3]*ma[2,2]);
7982 inv[8]:=((((ma[1,0]*ma[2,1]*ma[3,3])-(ma[1,0]*ma[2,3]*ma[3,1]))-(ma[2,0]*ma[1,1]*ma[3,3]))+(ma[2,0]*ma[1,3]*ma[3,1])+(ma[3,0]*ma[1,1]*ma[2,3]))-(ma[3,0]*ma[1,3]*ma[2,1]);
7983 inv[12]:=((((-(ma[1,0]*ma[2,1]*ma[3,2]))+(ma[1,0]*ma[2,2]*ma[3,1])+(ma[2,0]*ma[1,1]*ma[3,2]))-(ma[2,0]*ma[1,2]*ma[3,1]))-(ma[3,0]*ma[1,1]*ma[2,2]))+(ma[3,0]*ma[1,2]*ma[2,1]);
7984 inv[1]:=((((-(ma[0,1]*ma[2,2]*ma[3,3]))+(ma[0,1]*ma[2,3]*ma[3,2])+(ma[2,1]*ma[0,2]*ma[3,3]))-(ma[2,1]*ma[0,3]*ma[3,2]))-(ma[3,1]*ma[0,2]*ma[2,3]))+(ma[3,1]*ma[0,3]*ma[2,2]);
7985 inv[5]:=(((ma[0,0]*ma[2,2]*ma[3,3])-(ma[0,0]*ma[2,3]*ma[3,2]))-(ma[2,0]*ma[0,2]*ma[3,3])+(ma[2,0]*ma[0,3]*ma[3,2])+(ma[3,0]*ma[0,2]*ma[2,3]))-(ma[3,0]*ma[0,3]*ma[2,2]);
7986 inv[9]:=((((-(ma[0,0]*ma[2,1]*ma[3,3]))+(ma[0,0]*ma[2,3]*ma[3,1])+(ma[2,0]*ma[0,1]*ma[3,3]))-(ma[2,0]*ma[0,3]*ma[3,1]))-(ma[3,0]*ma[0,1]*ma[2,3]))+(ma[3,0]*ma[0,3]*ma[2,1]);
7987 inv[13]:=((((ma[0,0]*ma[2,1]*ma[3,2])-(ma[0,0]*ma[2,2]*ma[3,1]))-(ma[2,0]*ma[0,1]*ma[3,2]))+(ma[2,0]*ma[0,2]*ma[3,1])+(ma[3,0]*ma[0,1]*ma[2,2]))-(ma[3,0]*ma[0,2]*ma[2,1]);
7988 inv[2]:=((((ma[0,1]*ma[1,2]*ma[3,3])-(ma[0,1]*ma[1,3]*ma[3,2]))-(ma[1,1]*ma[0,2]*ma[3,3]))+(ma[1,1]*ma[0,3]*ma[3,2])+(ma[3,1]*ma[0,2]*ma[1,3]))-(ma[3,1]*ma[0,3]*ma[1,2]);
7989 inv[6]:=((((-(ma[0,0]*ma[1,2]*ma[3,3]))+(ma[0,0]*ma[1,3]*ma[3,2])+(ma[1,0]*ma[0,2]*ma[3,3]))-(ma[1,0]*ma[0,3]*ma[3,2]))-(ma[3,0]*ma[0,2]*ma[1,3]))+(ma[3,0]*ma[0,3]*ma[1,2]);
7990 inv[10]:=((((ma[0,0]*ma[1,1]*ma[3,3])-(ma[0,0]*ma[1,3]*ma[3,1]))-(ma[1,0]*ma[0,1]*ma[3,3]))+(ma[1,0]*ma[0,3]*ma[3,1])+(ma[3,0]*ma[0,1]*ma[1,3]))-(ma[3,0]*ma[0,3]*ma[1,1]);
7991 inv[14]:=((((-(ma[0,0]*ma[1,1]*ma[3,2]))+(ma[0,0]*ma[1,2]*ma[3,1])+(ma[1,0]*ma[0,1]*ma[3,2]))-(ma[1,0]*ma[0,2]*ma[3,1]))-(ma[3,0]*ma[0,1]*ma[1,2]))+(ma[3,0]*ma[0,2]*ma[1,1]);
7992 inv[3]:=((((-(ma[0,1]*ma[1,2]*ma[2,3]))+(ma[0,1]*ma[1,3]*ma[2,2])+(ma[1,1]*ma[0,2]*ma[2,3]))-(ma[1,1]*ma[0,3]*ma[2,2]))-(ma[2,1]*ma[0,2]*ma[1,3]))+(ma[2,1]*ma[0,3]*ma[1,2]);
7993 inv[7]:=((((ma[0,0]*ma[1,2]*ma[2,3])-(ma[0,0]*ma[1,3]*ma[2,2]))-(ma[1,0]*ma[0,2]*ma[2,3]))+(ma[1,0]*ma[0,3]*ma[2,2])+(ma[2,0]*ma[0,2]*ma[1,3]))-(ma[2,0]*ma[0,3]*ma[1,2]);
7994 inv[11]:=((((-(ma[0,0]*ma[1,1]*ma[2,3]))+(ma[0,0]*ma[1,3]*ma[2,1])+(ma[1,0]*ma[0,1]*ma[2,3]))-(ma[1,0]*ma[0,3]*ma[2,1]))-(ma[2,0]*ma[0,1]*ma[1,3]))+(ma[2,0]*ma[0,3]*ma[1,1]);
7995 inv[15]:=((((ma[0,0]*ma[1,1]*ma[2,2])-(ma[0,0]*ma[1,2]*ma[2,1]))-(ma[1,0]*ma[0,1]*ma[2,2]))+(ma[1,0]*ma[0,2]*ma[2,1])+(ma[2,0]*ma[0,1]*ma[1,2]))-(ma[2,0]*ma[0,2]*ma[1,1]);
7996 det:=(ma[0,0]*inv[0])+(ma[0,1]*inv[4])+(ma[0,2]*inv[8])+(ma[0,3]*inv[12]);
7997 if det<>0.0 then begin
7998 det:=1.0/det;
7999 result[0,0]:=inv[0]*det;
8000 result[0,1]:=inv[1]*det;
8001 result[0,2]:=inv[2]*det;
8002 result[0,3]:=inv[3]*det;
8003 result[1,0]:=inv[4]*det;
8004 result[1,1]:=inv[5]*det;
8005 result[1,2]:=inv[6]*det;
8006 result[1,3]:=inv[7]*det;
8007 result[2,0]:=inv[8]*det;
8008 result[2,1]:=inv[9]*det;
8009 result[2,2]:=inv[10]*det;
8010 result[2,3]:=inv[11]*det;
8011 result[3,0]:=inv[12]*det;
8012 result[3,1]:=inv[13]*det;
8013 result[3,2]:=inv[14]*det;
8014 result[3,3]:=inv[15]*det;
8015 end else begin
8016 result:=ma;
8017 end;
8018 end;
8019 {$endif}
8020
8021 function Matrix4x4InverseOld(var mr:TKraftMatrix4x4;const ma:TKraftMatrix4x4):boolean;
8022 var Det,IDet:TKraftScalar;
8023 begin
8024 Det:=(ma[0,0]*ma[1,1]*ma[2,2])+
8025 (ma[1,0]*ma[2,1]*ma[0,2])+
8026 (ma[2,0]*ma[0,1]*ma[1,2])-
8027 (ma[2,0]*ma[1,1]*ma[0,2])-
8028 (ma[1,0]*ma[0,1]*ma[2,2])-
8029 (ma[0,0]*ma[2,1]*ma[1,2]);
8030 if abs(Det)<EPSILON then begin
8031 mr:=Matrix4x4Identity;
8032 result:=false;
8033 end else begin
8034 IDet:=1/Det;
8035 mr[0,0]:=(ma[1,1]*ma[2,2]-ma[2,1]*ma[1,2])*IDet;
8036 mr[0,1]:=-(ma[0,1]*ma[2,2]-ma[2,1]*ma[0,2])*IDet;
8037 mr[0,2]:=(ma[0,1]*ma[1,2]-ma[1,1]*ma[0,2])*IDet;
8038 mr[0,3]:=0.0;
8039 mr[1,0]:=-(ma[1,0]*ma[2,2]-ma[2,0]*ma[1,2])*IDet;
8040 mr[1,1]:=(ma[0,0]*ma[2,2]-ma[2,0]*ma[0,2])*IDet;
8041 mr[1,2]:=-(ma[0,0]*ma[1,2]-ma[1,0]*ma[0,2])*IDet;
8042 mr[1,3]:=0.0;
8043 mr[2,0]:=(ma[1,0]*ma[2,1]-ma[2,0]*ma[1,1])*IDet;
8044 mr[2,1]:=-(ma[0,0]*ma[2,1]-ma[2,0]*ma[0,1])*IDet;
8045 mr[2,2]:=(ma[0,0]*ma[1,1]-ma[1,0]*ma[0,1])*IDet;
8046 mr[2,3]:=0.0;
8047 mr[3,0]:=-(ma[3,0]*mr[0,0]+ma[3,1]*mr[1,0]+ma[3,2]*mr[2,0]);
8048 mr[3,1]:=-(ma[3,0]*mr[0,1]+ma[3,1]*mr[1,1]+ma[3,2]*mr[2,1]);
8049 mr[3,2]:=-(ma[3,0]*mr[0,2]+ma[3,1]*mr[1,2]+ma[3,2]*mr[2,2]);
8050 mr[3,3]:=1.0;
8051 result:=true;
8052 end;
8053 end;
8054
8055 function Matrix4x4TermInverseOld(const ma:TKraftMatrix4x4):TKraftMatrix4x4;
8056 var Det,IDet:TKraftScalar;
8057 begin
8058 Det:=((((ma[0,0]*ma[1,1]*ma[2,2])+
8059 (ma[1,0]*ma[2,1]*ma[0,2])+
8060 (ma[2,0]*ma[0,1]*ma[1,2]))-
8061 (ma[2,0]*ma[1,1]*ma[0,2]))-
8062 (ma[1,0]*ma[0,1]*ma[2,2]))-
8063 (ma[0,0]*ma[2,1]*ma[1,2]);
8064 if abs(Det)<EPSILON then begin
8065 result:=Matrix4x4Identity;
8066 end else begin
8067 IDet:=1/Det;
8068 result[0,0]:=(ma[1,1]*ma[2,2]-ma[2,1]*ma[1,2])*IDet;
8069 result[0,1]:=-(ma[0,1]*ma[2,2]-ma[2,1]*ma[0,2])*IDet;
8070 result[0,2]:=(ma[0,1]*ma[1,2]-ma[1,1]*ma[0,2])*IDet;
8071 result[0,3]:=0.0;
8072 result[1,0]:=-(ma[1,0]*ma[2,2]-ma[2,0]*ma[1,2])*IDet;
8073 result[1,1]:=(ma[0,0]*ma[2,2]-ma[2,0]*ma[0,2])*IDet;
8074 result[1,2]:=-(ma[0,0]*ma[1,2]-ma[1,0]*ma[0,2])*IDet;
8075 result[1,3]:=0.0;
8076 result[2,0]:=(ma[1,0]*ma[2,1]-ma[2,0]*ma[1,1])*IDet;
8077 result[2,1]:=-(ma[0,0]*ma[2,1]-ma[2,0]*ma[0,1])*IDet;
8078 result[2,2]:=(ma[0,0]*ma[1,1]-ma[1,0]*ma[0,1])*IDet;
8079 result[2,3]:=0.0;
8080 result[3,0]:=-(ma[3,0]*result[0,0]+ma[3,1]*result[1,0]+ma[3,2]*result[2,0]);
8081 result[3,1]:=-(ma[3,0]*result[0,1]+ma[3,1]*result[1,1]+ma[3,2]*result[2,1]);
8082 result[3,2]:=-(ma[3,0]*result[0,2]+ma[3,1]*result[1,2]+ma[3,2]*result[2,2]);
8083 result[3,3]:=1.0;
8084 end;
8085 end;
8086
8087 function Matrix4x4GetSubMatrix3x3(const m:TKraftMatrix4x4;i,j:longint):TKraftMatrix3x3;
8088 var di,dj,si,sj:longint;
8089 begin
8090 for di:=0 to 2 do begin
8091 for dj:=0 to 2 do begin
8092 if di>=i then begin
8093 si:=di+1;
8094 end else begin
8095 si:=di;
8096 end;
8097 if dj>=j then begin
8098 sj:=dj+1;
8099 end else begin
8100 sj:=dj;
8101 end;
8102 result[di,dj]:=m[si,sj];
8103 end;
8104 end;
8105 {$ifdef SIMD}
8106 result[0,3]:=0.0;
8107 result[1,3]:=0.0;
8108 result[2,3]:=0.0;
8109 {$endif}
8110 end;
8111
8112 function Matrix4x4Frustum(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8113 var rml,tmb,fmn:TKraftScalar;
8114 begin
8115 rml:=Right-Left;
8116 tmb:=Top-Bottom;
8117 fmn:=zFar-zNear;
8118 result[0,0]:=(zNear*2.0)/rml;
8119 result[0,1]:=0.0;
8120 result[0,2]:=0.0;
8121 result[0,3]:=0.0;
8122 result[1,0]:=0.0;
8123 result[1,1]:=(zNear*2.0)/tmb;
8124 result[1,2]:=0.0;
8125 result[1,3]:=0.0;
8126 result[2,0]:=(Right+Left)/rml;
8127 result[2,1]:=(Top+Bottom)/tmb;
8128 result[2,2]:=(-(zFar+zNear))/fmn;
8129 result[2,3]:=-1.0;
8130 result[3,0]:=0.0;
8131 result[3,1]:=0.0;
8132 result[3,2]:=(-((zFar*zNear)*2.0))/fmn;
8133 result[3,3]:=0.0;
8134 end;
8135
8136 function Matrix4x4Ortho(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8137 var rml,tmb,fmn:TKraftScalar;
8138 begin
8139 rml:=Right-Left;
8140 tmb:=Top-Bottom;
8141 fmn:=zFar-zNear;
8142 result[0,0]:=2.0/rml;
8143 result[0,1]:=0.0;
8144 result[0,2]:=0.0;
8145 result[0,3]:=0.0;
8146 result[1,0]:=0.0;
8147 result[1,1]:=2.0/tmb;
8148 result[1,2]:=0.0;
8149 result[1,3]:=0.0;
8150 result[2,0]:=0.0;
8151 result[2,1]:=0.0;
8152 result[2,2]:=(-2.0)/fmn;
8153 result[2,3]:=0.0;
8154 result[3,0]:=(-(Right+Left))/rml;
8155 result[3,1]:=(-(Top+Bottom))/tmb;
8156 result[3,2]:=(-(zFar+zNear))/fmn;
8157 result[3,3]:=1.0;
8158 end;
8159
8160 function Matrix4x4OrthoLH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8161 var rml,tmb,fmn:TKraftScalar;
8162 begin
8163 rml:=Right-Left;
8164 tmb:=Top-Bottom;
8165 fmn:=zFar-zNear;
8166 result[0,0]:=2.0/rml;
8167 result[0,1]:=0.0;
8168 result[0,2]:=0.0;
8169 result[0,3]:=0.0;
8170 result[1,0]:=0.0;
8171 result[1,1]:=2.0/tmb;
8172 result[1,2]:=0.0;
8173 result[1,3]:=0.0;
8174 result[2,0]:=0.0;
8175 result[2,1]:=0.0;
8176 result[2,2]:=1.0/fmn;
8177 result[2,3]:=0.0;
8178 result[3,0]:=0;
8179 result[3,1]:=0;
8180 result[3,2]:=(-zNear)/fmn;
8181 result[3,3]:=1.0;
8182 end;
8183
8184 function Matrix4x4OrthoRH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8185 var rml,tmb,fmn:TKraftScalar;
8186 begin
8187 rml:=Right-Left;
8188 tmb:=Top-Bottom;
8189 fmn:=zFar-zNear;
8190 result[0,0]:=2.0/rml;
8191 result[0,1]:=0.0;
8192 result[0,2]:=0.0;
8193 result[0,3]:=0.0;
8194 result[1,0]:=0.0;
8195 result[1,1]:=2.0/tmb;
8196 result[1,2]:=0.0;
8197 result[1,3]:=0.0;
8198 result[2,0]:=0.0;
8199 result[2,1]:=0.0;
8200 result[2,2]:=1.0/fmn;
8201 result[2,3]:=0.0;
8202 result[3,0]:=0;
8203 result[3,1]:=0;
8204 result[3,2]:=zNear/fmn;
8205 result[3,3]:=1.0;
8206 end;
8207
8208 function Matrix4x4OrthoOffCenterLH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8209 var rml,tmb,fmn:TKraftScalar;
8210 begin
8211 rml:=Right-Left;
8212 tmb:=Top-Bottom;
8213 fmn:=zFar-zNear;
8214 result[0,0]:=2.0/rml;
8215 result[0,1]:=0.0;
8216 result[0,2]:=0.0;
8217 result[0,3]:=0.0;
8218 result[1,0]:=0.0;
8219 result[1,1]:=2.0/tmb;
8220 result[1,2]:=0.0;
8221 result[1,3]:=0.0;
8222 result[2,0]:=0.0;
8223 result[2,1]:=0.0;
8224 result[2,2]:=1.0/fmn;
8225 result[2,3]:=0.0;
8226 result[3,0]:=(Right+Left)/rml;
8227 result[3,1]:=(Top+Bottom)/tmb;
8228 result[3,2]:=zNear/fmn;
8229 result[3,3]:=1.0;
8230 end;
8231
8232 function Matrix4x4OrthoOffCenterRH(Left,Right,Bottom,Top,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8233 var rml,tmb,fmn:TKraftScalar;
8234 begin
8235 rml:=Right-Left;
8236 tmb:=Top-Bottom;
8237 fmn:=zFar-zNear;
8238 result[0,0]:=2.0/rml;
8239 result[0,1]:=0.0;
8240 result[0,2]:=0.0;
8241 result[0,3]:=0.0;
8242 result[1,0]:=0.0;
8243 result[1,1]:=2.0/tmb;
8244 result[1,2]:=0.0;
8245 result[1,3]:=0.0;
8246 result[2,0]:=0.0;
8247 result[2,1]:=0.0;
8248 result[2,2]:=(-2.0)/fmn;
8249 result[2,3]:=0.0;
8250 result[3,0]:=(-(Right+Left))/rml;
8251 result[3,1]:=(-(Top+Bottom))/tmb;
8252 result[3,2]:=(-(zFar+zNear))/fmn;
8253 result[3,3]:=1.0;
8254 end;
8255
8256 function Matrix4x4Perspective(fovy,Aspect,zNear,zFar:TKraftScalar):TKraftMatrix4x4;
8257 (*)var Top,Right:TKraftScalar;
8258 begin
8259 Top:=zNear*tan(fovy*pi/360.0);
8260 Right:=Top*Aspect;
8261 result:=Matrix4x4Frustum(-Right,Right,-Top,Top,zNear,zFar);
8262 end;{(**)var Sine,Cotangent,ZDelta,Radians:TKraftScalar;
8263 begin
8264 Radians:=(fovy*0.5)*DEG2RAD;
8265 ZDelta:=zFar-zNear;
8266 Sine:=sin(Radians);
8267 if not ((ZDelta=0) or (Sine=0) or (aspect=0)) then begin
8268 Cotangent:=cos(Radians)/Sine;
8269 result:=Matrix4x4Identity;
8270 result[0][0]:=Cotangent/aspect;
8271 result[1][1]:=Cotangent;
8272 result[2][2]:=(-(zFar+zNear))/ZDelta;
8273 result[2][3]:=-1-0;
8274 result[3][2]:=(-(2.0*zNear*zFar))/ZDelta;
8275 result[3][3]:=0.0;
8276 end;
8277 end;{}
8278
8279 function Matrix4x4LookAt(const Eye,Center,Up:TKraftVector3):TKraftMatrix4x4;
8280 var RightVector,UpVector,ForwardVector:TKraftVector3;
8281 begin
8282 ForwardVector:=Vector3NormEx(Vector3Sub(Eye,Center));
8283 RightVector:=Vector3NormEx(Vector3Cross(Up,ForwardVector));
8284 UpVector:=Vector3NormEx(Vector3Cross(ForwardVector,RightVector));
8285 result[0,0]:=RightVector.x;
8286 result[1,0]:=RightVector.y;
8287 result[2,0]:=RightVector.z;
8288 result[3,0]:=-((RightVector.x*Eye.x)+(RightVector.y*Eye.y)+(RightVector.z*Eye.z));
8289 result[0,1]:=UpVector.x;
8290 result[1,1]:=UpVector.y;
8291 result[2,1]:=UpVector.z;
8292 result[3,1]:=-((UpVector.x*Eye.x)+(UpVector.y*Eye.y)+(UpVector.z*Eye.z));
8293 result[0,2]:=ForwardVector.x;
8294 result[1,2]:=ForwardVector.y;
8295 result[2,2]:=ForwardVector.z;
8296 result[3,2]:=-((ForwardVector.x*Eye.x)+(ForwardVector.y*Eye.y)+(ForwardVector.z*Eye.z));
8297 result[0,3]:=0.0;
8298 result[1,3]:=0.0;
8299 result[2,3]:=0.0;
8300 result[3,3]:=1.0;
8301 end;
8302
8303 function Matrix4x4Fill(const Eye,RightVector,UpVector,ForwardVector:TKraftVector3):TKraftMatrix4x4;
8304 begin
8305 result[0,0]:=RightVector.x;
8306 result[1,0]:=RightVector.y;
8307 result[2,0]:=RightVector.z;
8308 result[3,0]:=-((RightVector.x*Eye.x)+(RightVector.y*Eye.y)+(RightVector.z*Eye.z));
8309 result[0,1]:=UpVector.x;
8310 result[1,1]:=UpVector.y;
8311 result[2,1]:=UpVector.z;
8312 result[3,1]:=-((UpVector.x*Eye.x)+(UpVector.y*Eye.y)+(UpVector.z*Eye.z));
8313 result[0,2]:=ForwardVector.x;
8314 result[1,2]:=ForwardVector.y;
8315 result[2,2]:=ForwardVector.z;
8316 result[3,2]:=-((ForwardVector.x*Eye.x)+(ForwardVector.y*Eye.y)+(ForwardVector.z*Eye.z));
8317 result[0,3]:=0.0;
8318 result[1,3]:=0.0;
8319 result[2,3]:=0.0;
8320 result[3,3]:=1.0;
8321 end;
8322
8323 function Matrix4x4ConstructX(const xAxis:TKraftVector3):TKraftMatrix4x4;
8324 var a,b,c:TKraftVector3;
8325 begin
8326 a:=Vector3NormEx(xAxis);
8327 result[0,0]:=a.x;
8328 result[0,1]:=a.y;
8329 result[0,2]:=a.z;
8330 result[0,3]:=0.0;
8331 //b:=Vector3NormEx(Vector3Cross(Vector3(0,0,1),a));
8332 b:=Vector3NormEx(Vector3Perpendicular(a));
8333 result[1,0]:=b.x;
8334 result[1,1]:=b.y;
8335 result[1,2]:=b.z;
8336 result[1,3]:=0.0;
8337 c:=Vector3NormEx(Vector3Cross(b,a));
8338 result[2,0]:=c.x;
8339 result[2,1]:=c.y;
8340 result[2,2]:=c.z;
8341 result[2,3]:=0.0;
8342 result[3,0]:=0.0;
8343 result[3,1]:=0.0;
8344 result[3,2]:=0.0;
8345 result[3,3]:=1.0;
8346 end;{}
8347
8348 function Matrix4x4ConstructY(const yAxis:TKraftVector3):TKraftMatrix4x4;
8349 var a,b,c:TKraftVector3;
8350 begin
8351 a:=Vector3NormEx(yAxis);
8352 result[1,0]:=a.x;
8353 result[1,1]:=a.y;
8354 result[1,2]:=a.z;
8355 result[1,3]:=0.0;
8356 b:=Vector3NormEx(Vector3Perpendicular(a));
8357 result[0,0]:=b.x;
8358 result[0,1]:=b.y;
8359 result[0,2]:=b.z;
8360 result[0,3]:=0.0;
8361 c:=Vector3Cross(b,a);
8362 result[2,0]:=c.x;
8363 result[2,1]:=c.y;
8364 result[2,2]:=c.z;
8365 result[2,3]:=0.0;
8366 result[3,0]:=0.0;
8367 result[3,1]:=0.0;
8368 result[3,2]:=0.0;
8369 result[3,3]:=1.0;
8370 end;
8371
8372 function Matrix4x4ConstructZ(const zAxis:TKraftVector3):TKraftMatrix4x4;
8373 var a,b,c:TKraftVector3;
8374 begin
8375 a:=Vector3NormEx(zAxis);
8376 result[2,0]:=a.x;
8377 result[2,1]:=a.y;
8378 result[2,2]:=a.z;
8379 result[2,3]:=0.0;
8380 b:=Vector3NormEx(Vector3Perpendicular(a));
8381 //b:=Vector3Sub(Vector3(0,1,0),Vector3ScalarMul(a,a.y));
8382 result[1,0]:=b.x;
8383 result[1,1]:=b.y;
8384 result[1,2]:=b.z;
8385 result[1,3]:=0.0;
8386 c:=Vector3Cross(b,a);
8387 result[0,0]:=c.x;
8388 result[0,1]:=c.y;
8389 result[0,2]:=c.z;
8390 result[0,3]:=0.0;
8391 result[3,0]:=0.0;
8392 result[3,1]:=0.0;
8393 result[3,2]:=0.0;
8394 result[3,3]:=1.0;
8395 end;
8396
8397 function Matrix4x4ProjectionMatrixClip(const ProjectionMatrix:TKraftMatrix4x4;const ClipPlane:TKraftPlane):TKraftMatrix4x4;
8398 var q,c:TKraftVector4;
8399 begin
8400 result:=ProjectionMatrix;
8401 q.x:=(Sign(ClipPlane.Normal.x)+result[2,0])/result[0,0];
8402 q.y:=(Sign(ClipPlane.Normal.y)+result[2,1])/result[1,1];
8403 q.z:=-1.0;
8404 q.w:=(1.0+result[2,2])/result[3,2];
8405 c.x:=ClipPlane.Normal.x;
8406 c.y:=ClipPlane.Normal.y;
8407 c.z:=ClipPlane.Normal.z;
8408 c.w:=ClipPlane.Distance;
8409 c:=Vector4ScalarMul(c,2.0/Vector4Dot(c,q));
8410 result[0,2]:=c.x;
8411 result[1,2]:=c.y;
8412 result[2,2]:=c.z+1.0;
8413 result[3,2]:=c.w;
8414 end;
8415
8416 function PlaneMatrixMul(const Plane:TKraftPlane;const Matrix:TKraftMatrix4x4):TKraftPlane;
8417 begin
8418 result.Normal.x:=(Matrix[0,0]*Plane.Normal.x)+(Matrix[1,0]*Plane.Normal.y)+(Matrix[2,0]*Plane.Normal.z)+(Matrix[3,0]*Plane.Distance);
8419 result.Normal.y:=(Matrix[0,1]*Plane.Normal.x)+(Matrix[1,1]*Plane.Normal.y)+(Matrix[2,1]*Plane.Normal.z)+(Matrix[3,1]*Plane.Distance);
8420 result.Normal.z:=(Matrix[0,2]*Plane.Normal.x)+(Matrix[1,2]*Plane.Normal.y)+(Matrix[2,2]*Plane.Normal.z)+(Matrix[3,2]*Plane.Distance);
8421 result.Distance:=(Matrix[0,3]*Plane.Normal.x)+(Matrix[1,3]*Plane.Normal.y)+(Matrix[2,3]*Plane.Normal.z)+(Matrix[3,3]*Plane.Distance);
8422 end;
8423
8424 function PlaneTransform(const Plane:TKraftPlane;const Matrix:TKraftMatrix4x4):TKraftPlane; overload;
8425 begin
8426 result.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(Plane.Normal,Matrix4x4TermTranspose(Matrix4x4TermInverse(Matrix))));
8427 result.Distance:=-Vector3Dot(result.Normal,Vector3TermMatrixMul(Vector3ScalarMul(Plane.Normal,-Plane.Distance),Matrix));
8428 end;
8429
8430 function PlaneTransform(const Plane:TKraftPlane;const Matrix,NormalMatrix:TKraftMatrix4x4):TKraftPlane; overload;
8431 begin
8432 result.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(Plane.Normal,NormalMatrix));
8433 result.Distance:=-Vector3Dot(result.Normal,Vector3TermMatrixMul(Vector3ScalarMul(Plane.Normal,-Plane.Distance),Matrix));
8434 end;
8435
8436 function PlaneFastTransform(const Plane:TKraftPlane;const Matrix:TKraftMatrix4x4):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
8437 begin
8438 result.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(Plane.Normal,Matrix));
8439 result.Distance:=-Vector3Dot(result.Normal,Vector3TermMatrixMul(Vector3ScalarMul(Plane.Normal,-Plane.Distance),Matrix));
8440 end;
8441
8442 procedure PlaneNormalize(var Plane:TKraftPlane); {$ifdef caninline}inline;{$endif}
8443 var l:TKraftScalar;
8444 begin
8445 l:=sqr(Plane.Normal.x)+sqr(Plane.Normal.y)+sqr(Plane.Normal.z);
8446 if l>0.0 then begin
8447 l:=sqrt(l);
8448 Plane.Normal.x:=Plane.Normal.x/l;
8449 Plane.Normal.y:=Plane.Normal.y/l;
8450 Plane.Normal.z:=Plane.Normal.z/l;
8451 Plane.Distance:=Plane.Distance/l;
8452 end else begin
8453 Plane.Normal.x:=0.0;
8454 Plane.Normal.y:=0.0;
8455 Plane.Normal.z:=0.0;
8456 Plane.Distance:=0.0;
8457 end;
8458 end;
8459
8460 function PlaneVectorDistance(const Plane:TKraftPlane;const Point:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
8461 begin
8462 result:=(Plane.Normal.x*Point.x)+(Plane.Normal.y*Point.y)+(Plane.Normal.z*Point.z)+Plane.Distance;
8463 end;
8464
8465 function PlaneVectorDistance(const Plane:TKraftPlane;const Point:TKraftVector4):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
8466 begin
8467 result:=(Plane.Normal.x*Point.x)+(Plane.Normal.y*Point.y)+(Plane.Normal.z*Point.z)+(Plane.Distance*Point.w);
8468 end;
8469
8470 function PlaneFromPoints(const p1,p2,p3:TKraftVector3):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
8471 var n:TKraftVector3;
8472 begin
8473 n:=Vector3NormEx(Vector3Cross(Vector3Sub(p2,p1),Vector3Sub(p3,p1)));
8474 result.Normal.x:=n.x;
8475 result.Normal.y:=n.y;
8476 result.Normal.z:=n.z;
8477 result.Distance:=-((result.Normal.x*p1.x)+(result.Normal.y*p1.y)+(result.Normal.z*p1.z));
8478 end;
8479
8480 function PlaneFromPoints(const p1,p2,p3:TKraftVector4):TKraftPlane; overload; {$ifdef caninline}inline;{$endif}
8481 var n:TKraftVector4;
8482 begin
8483 n:=Vector4Norm(Vector4Cross(Vector4Sub(p2,p1),Vector4Sub(p3,p1)));
8484 result.Normal.x:=n.x;
8485 result.Normal.y:=n.y;
8486 result.Normal.z:=n.z;
8487 result.Distance:=-((result.Normal.x*p1.x)+(result.Normal.y*p1.y)+(result.Normal.z*p1.z));
8488 end;
8489
8490 function QuaternionNormal(const AQuaternion:TKraftQuaternion):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
8491 asm
8492 movups xmm0,dqword ptr [AQuaternion]
8493 mulps xmm0,xmm0
8494 movhlps xmm1,xmm0
8495 addps xmm0,xmm1
8496 pshufd xmm1,xmm0,$01
8497 addss xmm0,xmm1
8498 sqrtss xmm0,xmm0
8499 movss dword ptr [result],xmm0
8500 end;
8501 {$else}
8502 begin
8503 result:=sqrt(sqr(AQuaternion.x)+sqr(AQuaternion.y)+sqr(AQuaternion.z)+sqr(AQuaternion.w));
8504 end;
8505 {$endif}
8506
8507 function QuaternionLengthSquared(const AQuaternion:TKraftQuaternion):TKraftScalar; {$ifdef CPU386ASMForSinglePrecision}assembler;
8508 asm
8509 movups xmm0,dqword ptr [AQuaternion]
8510 mulps xmm0,xmm0
8511 movhlps xmm1,xmm0
8512 addps xmm0,xmm1
8513 pshufd xmm1,xmm0,$01
8514 addss xmm0,xmm1
8515 movss dword ptr [result],xmm0
8516 end;
8517 {$else}
8518 begin
8519 result:=sqr(AQuaternion.x)+sqr(AQuaternion.y)+sqr(AQuaternion.z)+sqr(AQuaternion.w);
8520 end;
8521 {$endif}
8522
8523 procedure QuaternionNormalize(var AQuaternion:TKraftQuaternion); {$ifdef CPU386ASMForSinglePrecision}assembler;
8524 asm
8525 {movups xmm2,dqword ptr [AQuaternion]
8526 movaps xmm0,xmm2
8527 mulps xmm0,xmm0
8528 movhlps xmm1,xmm0
8529 addps xmm0,xmm1
8530 pshufd xmm1,xmm0,$01
8531 addss xmm0,xmm1
8532 movss xmm3,xmm0
8533 xorps xmm1,xmm1
8534 cmpps xmm3,xmm1,4
8535 rsqrtss xmm0,xmm0
8536 andps xmm0,xmm3
8537 shufps xmm0,xmm0,$00
8538 mulps xmm2,xmm0
8539 movups dqword ptr [AQuaternion],xmm2}
8540 movups xmm2,dqword ptr [AQuaternion]
8541 movaps xmm0,xmm2
8542 mulps xmm0,xmm0
8543 movhlps xmm1,xmm0
8544 addps xmm0,xmm1
8545 pshufd xmm1,xmm0,$01
8546 addss xmm0,xmm1
8547 sqrtss xmm0,xmm0
8548 shufps xmm0,xmm0,$00
8549 divps xmm2,xmm0
8550 subps xmm1,xmm2
8551 cmpps xmm1,xmm0,7
8552 andps xmm2,xmm1
8553 movups dqword ptr [AQuaternion],xmm2
8554 end;
8555 {$else}
8556 var Normal:TKraftScalar;
8557 begin
8558 Normal:=sqrt(sqr(AQuaternion.x)+sqr(AQuaternion.y)+sqr(AQuaternion.z)+sqr(AQuaternion.w));
8559 if Normal>0.0 then begin
8560 Normal:=1.0/Normal;
8561 end;
8562 AQuaternion.x:=AQuaternion.x*Normal;
8563 AQuaternion.y:=AQuaternion.y*Normal;
8564 AQuaternion.z:=AQuaternion.z*Normal;
8565 AQuaternion.w:=AQuaternion.w*Normal;
8566 end;
8567 {$endif}
8568
8569 function QuaternionTermNormalize(const AQuaternion:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8570 asm
8571 movups xmm2,dqword ptr [AQuaternion]
8572 movaps xmm0,xmm2
8573 mulps xmm0,xmm0
8574 movhlps xmm1,xmm0
8575 addps xmm0,xmm1
8576 pshufd xmm1,xmm0,$01
8577 addss xmm0,xmm1
8578 sqrtss xmm0,xmm0
8579 shufps xmm0,xmm0,$00
8580 divps xmm2,xmm0
8581 subps xmm1,xmm2
8582 cmpps xmm1,xmm0,7
8583 andps xmm2,xmm1
8584 movups dqword ptr [result],xmm2
8585 end;
8586 {$else}
8587 var Normal:TKraftScalar;
8588 begin
8589 Normal:=sqrt(sqr(AQuaternion.x)+sqr(AQuaternion.y)+sqr(AQuaternion.z)+sqr(AQuaternion.w));
8590 if Normal>0.0 then begin
8591 Normal:=1.0/Normal;
8592 end;
8593 result.x:=AQuaternion.x*Normal;
8594 result.y:=AQuaternion.y*Normal;
8595 result.z:=AQuaternion.z*Normal;
8596 result.w:=AQuaternion.w*Normal;
8597 end;
8598 {$endif}
8599
8600 function QuaternionNeg(const AQuaternion:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8601 asm
8602 movups xmm1,dqword ptr [AQuaternion]
8603 xorps xmm0,xmm0
8604 subps xmm0,xmm1
8605 movups dqword ptr [result],xmm0
8606 end;
8607 {$else}
8608 begin
8609 result.x:=-AQuaternion.x;
8610 result.y:=-AQuaternion.y;
8611 result.z:=-AQuaternion.z;
8612 result.w:=-AQuaternion.w;
8613 end;
8614 {$endif}
8615
8616 function QuaternionConjugate(const AQuaternion:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8617 const XORMask:array[0..3] of longword=($80000000,$80000000,$80000000,$00000000);
8618 asm
8619 movups xmm0,dqword ptr [AQuaternion]
8620 movups xmm1,dqword ptr [XORMask]
8621 xorps xmm0,xmm1
8622 movups dqword ptr [result],xmm0
8623 end;
8624 {$else}
8625 begin
8626 result.x:=-AQuaternion.x;
8627 result.y:=-AQuaternion.y;
8628 result.z:=-AQuaternion.z;
8629 result.w:=AQuaternion.w;
8630 end;
8631 {$endif}
8632
8633 function QuaternionInverse(const AQuaternion:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8634 const XORMask:array[0..3] of longword=($80000000,$80000000,$80000000,$00000000);
8635 asm
8636 movups xmm2,dqword ptr [AQuaternion]
8637 movups xmm3,dqword ptr [XORMask]
8638 movaps xmm0,xmm2
8639 mulps xmm0,xmm0
8640 movhlps xmm1,xmm0
8641 addps xmm0,xmm1
8642 pshufd xmm1,xmm0,$01
8643 addss xmm0,xmm1
8644 sqrtss xmm0,xmm0
8645 shufps xmm0,xmm0,$00
8646 divps xmm2,xmm0
8647 xorps xmm2,xmm3
8648 movups dqword ptr [result],xmm2
8649 end;
8650 {$else}
8651 var Normal:TKraftScalar;
8652 begin
8653 Normal:=sqrt(sqr(AQuaternion.x)+sqr(AQuaternion.y)+sqr(AQuaternion.z)+sqr(AQuaternion.w));
8654 if Normal>0.0 then begin
8655 Normal:=1.0/Normal;
8656 end;
8657 result.x:=-(AQuaternion.x*Normal);
8658 result.y:=-(AQuaternion.y*Normal);
8659 result.z:=-(AQuaternion.z*Normal);
8660 result.w:=(AQuaternion.w*Normal);
8661 end;
8662 {$endif}
8663
8664 function QuaternionAdd(const q1,q2:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8665 asm
8666 movups xmm0,dqword ptr [q1]
8667 movups xmm1,dqword ptr [q2]
8668 addps xmm0,xmm1
8669 movups dqword ptr [result],xmm0
8670 end;
8671 {$else}
8672 begin
8673 result.x:=q1.x+q2.x;
8674 result.y:=q1.y+q2.y;
8675 result.z:=q1.z+q2.z;
8676 result.w:=q1.w+q2.w;
8677 end;
8678 {$endif}
8679
8680 function QuaternionSub(const q1,q2:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8681 asm
8682 movups xmm0,dqword ptr [q1]
8683 movups xmm1,dqword ptr [q2]
8684 subps xmm0,xmm1
8685 movups dqword ptr [result],xmm0
8686 end;
8687 {$else}
8688 begin
8689 result.x:=q1.x-q2.x;
8690 result.y:=q1.y-q2.y;
8691 result.z:=q1.z-q2.z;
8692 result.w:=q1.w-q2.w;
8693 end;
8694 {$endif}
8695
8696 function QuaternionScalarMul(const q:TKraftQuaternion;const s:TKraftScalar):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8697 asm
8698 movups xmm0,dqword ptr [q]
8699 movss xmm1,dword ptr [s]
8700 shufps xmm1,xmm1,$00
8701 mulps xmm0,xmm1
8702 movups dqword ptr [result],xmm0
8703 end;
8704 {$else}
8705 begin
8706 result.x:=q.x*s;
8707 result.y:=q.y*s;
8708 result.z:=q.z*s;
8709 result.w:=q.w*s;
8710 end;
8711 {$endif}
8712
8713 function QuaternionMul(const q1,q2:TKraftQuaternion):TKraftQuaternion; {$ifdef CPU386ASMForSinglePrecision}assembler;
8714 const XORMaskW:array[0..3] of longword=($00000000,$00000000,$00000000,$80000000);
8715 asm
8716 movups xmm4,dqword ptr [q1]
8717 movaps xmm0,xmm4
8718 shufps xmm0,xmm4,$49
8719 movups xmm2,dqword ptr [q2]
8720 movaps xmm3,xmm2
8721 movaps xmm1,xmm2
8722 shufps xmm3,xmm2,$52 // 001010010b
8723 mulps xmm3,xmm0
8724 movaps xmm0,xmm4
8725 shufps xmm0,xmm4,$24 // 000100100b
8726 shufps xmm1,xmm2,$3f // 000111111b
8727 movups xmm5,dqword ptr [XORMaskW]
8728 mulps xmm1,xmm0
8729 movaps xmm0,xmm4
8730 shufps xmm0,xmm4,$92 // 001001001b
8731 shufps xmm4,xmm4,$ff // 011111111b
8732 mulps xmm4,xmm2
8733 addps xmm3,xmm1
8734 movaps xmm1,xmm2
8735 shufps xmm1,xmm2,$89 // 010001001b
8736 mulps xmm1,xmm0
8737 xorps xmm3,xmm5
8738 subps xmm4,xmm1
8739 addps xmm3,xmm4
8740 movups dqword ptr [result],xmm3
8741 end;
8742 {$else}
8743 begin
8744 result.x:=((q1.w*q2.x)+(q1.x*q2.w)+(q1.y*q2.z))-(q1.z*q2.y);
8745 result.y:=((q1.w*q2.y)+(q1.y*q2.w)+(q1.z*q2.x))-(q1.x*q2.z);
8746 result.z:=((q1.w*q2.z)+(q1.z*q2.w)+(q1.x*q2.y))-(q1.y*q2.x);
8747 result.w:=(q1.w*q2.w)-((q1.x*q2.x)+(q1.y*q2.y)+(q1.z*q2.z));
8748 end;
8749 {$endif}
8750
8751 function QuaternionRotateAroundAxis(const q1,q2:TKraftQuaternion):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
8752 begin
8753 result.x:=((q1.x*q2.w)+(q1.z*q2.y))-(q1.y*q2.z);
8754 result.y:=((q1.x*q2.z)+(q1.y*q2.w))-(q1.z*q2.x);
8755 result.z:=((q1.y*q2.x)+(q1.z*q2.w))-(q1.x*q2.y);
8756 result.w:=((q1.x*q2.x)+(q1.y*q2.y))+(q1.z*q2.z);
8757 end;
8758
8759 function QuaternionFromAxisAngle(const Axis:TKraftVector3;Angle:TKraftScalar):TKraftQuaternion; overload; {$ifdef caninline}inline;{$endif}
8760 var sa2:TKraftScalar;
8761 begin
8762 result.w:=cos(Angle*0.5);
8763 sa2:=sin(Angle*0.5);
8764 result.x:=Axis.x*sa2;
8765 result.y:=Axis.y*sa2;
8766 result.z:=Axis.z*sa2;
8767 QuaternionNormalize(result);
8768 end;
8769
8770 function QuaternionFromSpherical(const Latitude,Longitude:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
8771 begin
8772 result.x:=cos(Latitude)*sin(Longitude);
8773 result.y:=sin(Latitude);
8774 result.z:=cos(Latitude)*cos(Longitude);
8775 result.w:=0.0;
8776 end;
8777
8778 procedure QuaternionToSpherical(const q:TKraftQuaternion;var Latitude,Longitude:TKraftScalar);
8779 var y:TKraftScalar;
8780 begin
8781 y:=q.y;
8782 if y<-1.0 then begin
8783 y:=-1.0;
8784 end else if y>1.0 then begin
8785 y:=1.0;
8786 end;
8787 Latitude:=ArcSin(y);
8788 if (sqr(q.x)+sqr(q.z))>0.00005 then begin
8789 Longitude:=ArcTan2(q.x,q.z);
8790 end else begin
8791 Longitude:=0.0;
8792 end;
8793 end;
8794
8795 function QuaternionFromAngles(const Pitch,Yaw,Roll:TKraftScalar):TKraftQuaternion; overload; {$ifdef caninline}inline;{$endif}
8796 var sp,sy,sr,cp,cy,cr:TKraftScalar;
8797 begin
8798 sp:=sin(Pitch*0.5);
8799 sy:=sin(Yaw*0.5);
8800 sr:=sin(Roll*0.5);
8801 cp:=cos(Pitch*0.5);
8802 cy:=cos(Yaw*0.5);
8803 cr:=cos(Roll*0.5);
8804 result.x:=(sr*cp*cy)-(cr*sp*sy);
8805 result.y:=(cr*sp*cy)+(sr*cp*sy);
8806 result.z:=(cr*cp*sy)-(sr*sp*cy);
8807 result.w:=(cr*cp*cy)+(sr*sp*sy);
8808 QuaternionNormalize(result);
8809 end;
8810
8811 function QuaternionFromAngles(const Angles:TKraftAngles):TKraftQuaternion; overload; {$ifdef caninline}inline;{$endif}
8812 var sp,sy,sr,cp,cy,cr:TKraftScalar;
8813 begin
8814 sp:=sin(Angles.Pitch*0.5);
8815 sy:=sin(Angles.Yaw*0.5);
8816 sr:=sin(Angles.Roll*0.5);
8817 cp:=cos(Angles.Pitch*0.5);
8818 cy:=cos(Angles.Yaw*0.5);
8819 cr:=cos(Angles.Roll*0.5);
8820 result.x:=(sr*cp*cy)-(cr*sp*sy);
8821 result.y:=(cr*sp*cy)+(sr*cp*sy);
8822 result.z:=(cr*cp*sy)-(sr*sp*cy);
8823 result.w:=(cr*cp*cy)+(sr*sp*sy);
8824 QuaternionNormalize(result);
8825 end;
8826
8827 function QuaternionFromMatrix3x3(const AMatrix:TKraftMatrix3x3):TKraftQuaternion;
8828 var t,s:TKraftScalar;
8829 begin
8830 t:=AMatrix[0,0]+(AMatrix[1,1]+AMatrix[2,2]);
8831 if t>2.9999999 then begin
8832 result.x:=0.0;
8833 result.y:=0.0;
8834 result.z:=0.0;
8835 result.w:=1.0;
8836 end else if t>0.0000001 then begin
8837 s:=sqrt(1.0+t)*2.0;
8838 result.x:=(AMatrix[1,2]-AMatrix[2,1])/s;
8839 result.y:=(AMatrix[2,0]-AMatrix[0,2])/s;
8840 result.z:=(AMatrix[0,1]-AMatrix[1,0])/s;
8841 result.w:=s*0.25;
8842 end else if (AMatrix[0,0]>AMatrix[1,1]) and (AMatrix[0,0]>AMatrix[2,2]) then begin
8843 s:=sqrt(1.0+(AMatrix[0,0]-(AMatrix[1,1]+AMatrix[2,2])))*2.0;
8844 result.x:=s*0.25;
8845 result.y:=(AMatrix[1,0]+AMatrix[0,1])/s;
8846 result.z:=(AMatrix[2,0]+AMatrix[0,2])/s;
8847 result.w:=(AMatrix[1,2]-AMatrix[2,1])/s;
8848 end else if AMatrix[1,1]>AMatrix[2,2] then begin
8849 s:=sqrt(1.0+(AMatrix[1,1]-(AMatrix[0,0]+AMatrix[2,2])))*2.0;
8850 result.x:=(AMatrix[1,0]+AMatrix[0,1])/s;
8851 result.y:=s*0.25;
8852 result.z:=(AMatrix[2,1]+AMatrix[1,2])/s;
8853 result.w:=(AMatrix[2,0]-AMatrix[0,2])/s;
8854 end else begin
8855 s:=sqrt(1.0+(AMatrix[2,2]-(AMatrix[0,0]+AMatrix[1,1])))*2.0;
8856 result.x:=(AMatrix[2,0]+AMatrix[0,2])/s;
8857 result.y:=(AMatrix[2,1]+AMatrix[1,2])/s;
8858 result.z:=s*0.25;
8859 result.w:=(AMatrix[0,1]-AMatrix[1,0])/s;
8860 end;
8861 QuaternionNormalize(result);
8862 end;
8863 {var xx,yx,zx,xy,yy,zy,xz,yz,zz,Trace,Radicand,Scale,TempX,TempY,TempZ,TempW:TKraftScalar;
8864 NegativeTrace,ZgtX,ZgtY,YgtX,LargestXorY,LargestYorZ,LargestZorX:boolean;
8865 begin
8866 xx:=AMatrix[0,0];
8867 yx:=AMatrix[0,1];
8868 zx:=AMatrix[0,2];
8869 xy:=AMatrix[1,0];
8870 yy:=AMatrix[1,1];
8871 zy:=AMatrix[1,2];
8872 xz:=AMatrix[2,0];
8873 yz:=AMatrix[2,1];
8874 zz:=AMatrix[2,2];
8875 Trace:=(xx+yy)+zz;
8876 NegativeTrace:=Trace<0.0;
8877 ZgtX:=zz>xx;
8878 ZgtY:=zz>yy;
8879 YgtX:=yy>xx;
8880 LargestXorY:=NegativeTrace and ((not ZgtX) or not ZgtY);
8881 LargestYorZ:=NegativeTrace and (YgtX or ZgtX);
8882 LargestZorX:=NegativeTrace and (ZgtY or not YgtX);
8883 if LargestXorY then begin
8884 zz:=-zz;
8885 xy:=-xy;
8886 end;
8887 if LargestYorZ then begin
8888 xx:=-xx;
8889 yz:=-yz;
8890 end;
8891 if LargestZorX then begin
8892 yy:=-yy;
8893 zx:=-zx;
8894 end;
8895 Radicand:=((xx+yy)+zz)+1.0;
8896 Scale:=0.5/sqrt(Radicand);
8897 TempX:=(zy-yz)*Scale;
8898 TempY:=(xz-zx)*Scale;
8899 TempZ:=(yx-xy)*Scale;
8900 TempW:=Radicand*Scale;
8901 if LargestXorY then begin
8902 result.x:=TempW;
8903 result.y:=TempZ;
8904 result.z:=TempY;
8905 result.w:=TempX;
8906 end else begin
8907 result.x:=TempX;
8908 result.y:=TempY;
8909 result.z:=TempZ;
8910 result.w:=TempW;
8911 end;
8912 if LargestYorZ then begin
8913 TempX:=result.x;
8914 TempZ:=result.z;
8915 result.x:=result.y;
8916 result.y:=TempX;
8917 result.z:=result.w;
8918 result.w:=TempZ;
8919 end;
8920 end;{}
8921
8922 function QuaternionToMatrix3x3(AQuaternion:TKraftQuaternion):TKraftMatrix3x3;
8923 var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TKraftScalar;
8924 begin
8925 QuaternionNormalize(AQuaternion);
8926 qx2:=AQuaternion.x+AQuaternion.x;
8927 qy2:=AQuaternion.y+AQuaternion.y;
8928 qz2:=AQuaternion.z+AQuaternion.z;
8929 qxqx2:=AQuaternion.x*qx2;
8930 qxqy2:=AQuaternion.x*qy2;
8931 qxqz2:=AQuaternion.x*qz2;
8932 qxqw2:=AQuaternion.w*qx2;
8933 qyqy2:=AQuaternion.y*qy2;
8934 qyqz2:=AQuaternion.y*qz2;
8935 qyqw2:=AQuaternion.w*qy2;
8936 qzqz2:=AQuaternion.z*qz2;
8937 qzqw2:=AQuaternion.w*qz2;
8938 result[0,0]:=1.0-(qyqy2+qzqz2);
8939 result[0,1]:=qxqy2+qzqw2;
8940 result[0,2]:=qxqz2-qyqw2;
8941 {$ifdef SIMD}
8942 result[0,3]:=0.0;
8943 {$endif}
8944 result[1,0]:=qxqy2-qzqw2;
8945 result[1,1]:=1.0-(qxqx2+qzqz2);
8946 result[1,2]:=qyqz2+qxqw2;
8947 {$ifdef SIMD}
8948 result[1,3]:=0.0;
8949 {$endif}
8950 result[2,0]:=qxqz2+qyqw2;
8951 result[2,1]:=qyqz2-qxqw2;
8952 result[2,2]:=1.0-(qxqx2+qyqy2);
8953 {$ifdef SIMD}
8954 result[2,3]:=0.0;
8955 {$endif}
8956 end;
8957
8958 function QuaternionFromTangentSpaceMatrix3x3(AMatrix:TKraftMatrix3x3):TKraftQuaternion;
8959 const Threshold=1.0/127.0;
8960 var Scale,t,s,Renormalization:TKraftScalar;
8961 begin
8962 if ((((((AMatrix[0,0]*AMatrix[1,1]*AMatrix[2,2])+
8963 (AMatrix[0,1]*AMatrix[1,2]*AMatrix[2,0])
8964 )+
8965 (AMatrix[0,2]*AMatrix[1,0]*AMatrix[2,1])
8966 )-
8967 (AMatrix[0,2]*AMatrix[1,1]*AMatrix[2,0])
8968 )-
8969 (AMatrix[0,1]*AMatrix[1,0]*AMatrix[2,2])
8970 )-
8971 (AMatrix[0,0]*AMatrix[1,2]*AMatrix[2,1])
8972 )<0.0 then begin
8973 // Reflection matrix, so flip y axis in case the tangent frame encodes a reflection
8974 Scale:=-1.0;
8975 AMatrix[2,0]:=-AMatrix[2,0];
8976 AMatrix[2,1]:=-AMatrix[2,1];
8977 AMatrix[2,2]:=-AMatrix[2,2];
8978 end else begin
8979 // Rotation matrix, so nothing is doing to do
8980 Scale:=1.0;
8981 end;
8982 begin
8983 // Convert to quaternion
8984 t:=AMatrix[0,0]+(AMatrix[1,1]+AMatrix[2,2]);
8985 if t>2.9999999 then begin
8986 result.x:=0.0;
8987 result.y:=0.0;
8988 result.z:=0.0;
8989 result.w:=1.0;
8990 end else if t>0.0000001 then begin
8991 s:=sqrt(1.0+t)*2.0;
8992 result.x:=(AMatrix[1,2]-AMatrix[2,1])/s;
8993 result.y:=(AMatrix[2,0]-AMatrix[0,2])/s;
8994 result.z:=(AMatrix[0,1]-AMatrix[1,0])/s;
8995 result.w:=s*0.25;
8996 end else if (AMatrix[0,0]>AMatrix[1,1]) and (AMatrix[0,0]>AMatrix[2,2]) then begin
8997 s:=sqrt(1.0+(AMatrix[0,0]-(AMatrix[1,1]+AMatrix[2,2])))*2.0;
8998 result.x:=s*0.25;
8999 result.y:=(AMatrix[1,0]+AMatrix[0,1])/s;
9000 result.z:=(AMatrix[2,0]+AMatrix[0,2])/s;
9001 result.w:=(AMatrix[1,2]-AMatrix[2,1])/s;
9002 end else if AMatrix[1,1]>AMatrix[2,2] then begin
9003 s:=sqrt(1.0+(AMatrix[1,1]-(AMatrix[0,0]+AMatrix[2,2])))*2.0;
9004 result.x:=(AMatrix[1,0]+AMatrix[0,1])/s;
9005 result.y:=s*0.25;
9006 result.z:=(AMatrix[2,1]+AMatrix[1,2])/s;
9007 result.w:=(AMatrix[2,0]-AMatrix[0,2])/s;
9008 end else begin
9009 s:=sqrt(1.0+(AMatrix[2,2]-(AMatrix[0,0]+AMatrix[1,1])))*2.0;
9010 result.x:=(AMatrix[2,0]+AMatrix[0,2])/s;
9011 result.y:=(AMatrix[2,1]+AMatrix[1,2])/s;
9012 result.z:=s*0.25;
9013 result.w:=(AMatrix[0,1]-AMatrix[1,0])/s;
9014 end;
9015 QuaternionNormalize(result);
9016 end;
9017 begin
9018 // Make sure, that we don't end up with 0 as w component
9019 if abs(result.w)<=Threshold then begin
9020 Renormalization:=sqrt(1.0-sqr(Threshold));
9021 result.x:=result.x*Renormalization;
9022 result.y:=result.y*Renormalization;
9023 result.z:=result.z*Renormalization;
9024 if result.w<0.0 then begin
9025 result.w:=-Threshold;
9026 end else begin
9027 result.w:=Threshold;
9028 end;
9029 end;
9030 end;
9031 if ((Scale<0.0) and (result.w>=0.0)) or ((Scale>=0.0) and (result.w<0.0)) then begin
9032 // Encode reflection into quaternion's w element by making sign of w negative,
9033 // if y axis needs to be flipped, otherwise it stays positive
9034 result.x:=-result.x;
9035 result.y:=-result.y;
9036 result.z:=-result.z;
9037 result.w:=-result.w;
9038 end;
9039 end;
9040
9041 function QuaternionToTangentSpaceMatrix3x3(AQuaternion:TKraftQuaternion):TKraftMatrix3x3;
9042 var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TKraftScalar;
9043 begin
9044 QuaternionNormalize(AQuaternion);
9045 qx2:=AQuaternion.x+AQuaternion.x;
9046 qy2:=AQuaternion.y+AQuaternion.y;
9047 qz2:=AQuaternion.z+AQuaternion.z;
9048 qxqx2:=AQuaternion.x*qx2;
9049 qxqy2:=AQuaternion.x*qy2;
9050 qxqz2:=AQuaternion.x*qz2;
9051 qxqw2:=AQuaternion.w*qx2;
9052 qyqy2:=AQuaternion.y*qy2;
9053 qyqz2:=AQuaternion.y*qz2;
9054 qyqw2:=AQuaternion.w*qy2;
9055 qzqz2:=AQuaternion.z*qz2;
9056 qzqw2:=AQuaternion.w*qz2;
9057 result[0,0]:=1.0-(qyqy2+qzqz2);
9058 result[0,1]:=qxqy2+qzqw2;
9059 result[0,2]:=qxqz2-qyqw2;
9060 {$ifdef SIMD}
9061 result[0,3]:=0.0;
9062 {$endif}
9063 result[1,0]:=qxqy2-qzqw2;
9064 result[1,1]:=1.0-(qxqx2+qzqz2);
9065 result[1,2]:=qyqz2+qxqw2;
9066 {$ifdef SIMD}
9067 result[1,3]:=0.0;
9068 {$endif}
9069 result[2,0]:=qxqz2+qyqw2;
9070 result[2,1]:=qyqz2-qxqw2;
9071 result[2,2]:=1.0-(qxqx2+qyqy2);
9072 if AQuaternion.w<0.0 then begin
9073 result[2,0]:=-result[2,0];
9074 result[2,1]:=-result[2,1];
9075 result[2,2]:=-result[2,2];
9076 end;
9077 {$ifdef SIMD}
9078 result[2,3]:=0.0;
9079 {$endif}
9080 end;
9081
9082 function QuaternionFromMatrix4x4(const AMatrix:TKraftMatrix4x4):TKraftQuaternion;
9083 var t,s:TKraftScalar;
9084 begin
9085 t:=AMatrix[0,0]+(AMatrix[1,1]+AMatrix[2,2]);
9086 if t>2.9999999 then begin
9087 result.x:=0.0;
9088 result.y:=0.0;
9089 result.z:=0.0;
9090 result.w:=1.0;
9091 end else if t>0.0000001 then begin
9092 s:=sqrt(1.0+t)*2.0;
9093 result.x:=(AMatrix[1,2]-AMatrix[2,1])/s;
9094 result.y:=(AMatrix[2,0]-AMatrix[0,2])/s;
9095 result.z:=(AMatrix[0,1]-AMatrix[1,0])/s;
9096 result.w:=s*0.25;
9097 end else if (AMatrix[0,0]>AMatrix[1,1]) and (AMatrix[0,0]>AMatrix[2,2]) then begin
9098 s:=sqrt(1.0+(AMatrix[0,0]-(AMatrix[1,1]+AMatrix[2,2])))*2.0;
9099 result.x:=s*0.25;
9100 result.y:=(AMatrix[1,0]+AMatrix[0,1])/s;
9101 result.z:=(AMatrix[2,0]+AMatrix[0,2])/s;
9102 result.w:=(AMatrix[1,2]-AMatrix[2,1])/s;
9103 end else if AMatrix[1,1]>AMatrix[2,2] then begin
9104 s:=sqrt(1.0+(AMatrix[1,1]-(AMatrix[0,0]+AMatrix[2,2])))*2.0;
9105 result.x:=(AMatrix[1,0]+AMatrix[0,1])/s;
9106 result.y:=s*0.25;
9107 result.z:=(AMatrix[2,1]+AMatrix[1,2])/s;
9108 result.w:=(AMatrix[2,0]-AMatrix[0,2])/s;
9109 end else begin
9110 s:=sqrt(1.0+(AMatrix[2,2]-(AMatrix[0,0]+AMatrix[1,1])))*2.0;
9111 result.x:=(AMatrix[2,0]+AMatrix[0,2])/s;
9112 result.y:=(AMatrix[2,1]+AMatrix[1,2])/s;
9113 result.z:=s*0.25;
9114 result.w:=(AMatrix[0,1]-AMatrix[1,0])/s;
9115 end;
9116 QuaternionNormalize(result);
9117 end;
9118 {var xx,yx,zx,xy,yy,zy,xz,yz,zz,Trace,Radicand,Scale,TempX,TempY,TempZ,TempW:TKraftScalar;
9119 NegativeTrace,ZgtX,ZgtY,YgtX,LargestXorY,LargestYorZ,LargestZorX:boolean;
9120 begin
9121 xx:=AMatrix[0,0];
9122 yx:=AMatrix[0,1];
9123 zx:=AMatrix[0,2];
9124 xy:=AMatrix[1,0];
9125 yy:=AMatrix[1,1];
9126 zy:=AMatrix[1,2];
9127 xz:=AMatrix[2,0];
9128 yz:=AMatrix[2,1];
9129 zz:=AMatrix[2,2];
9130 Trace:=(xx+yy)+zz;
9131 NegativeTrace:=Trace<0.0;
9132 ZgtX:=zz>xx;
9133 ZgtY:=zz>yy;
9134 YgtX:=yy>xx;
9135 LargestXorY:=NegativeTrace and ((not ZgtX) or not ZgtY);
9136 LargestYorZ:=NegativeTrace and (YgtX or ZgtX);
9137 LargestZorX:=NegativeTrace and (ZgtY or not YgtX);
9138 if LargestXorY then begin
9139 zz:=-zz;
9140 xy:=-xy;
9141 end;
9142 if LargestYorZ then begin
9143 xx:=-xx;
9144 yz:=-yz;
9145 end;
9146 if LargestZorX then begin
9147 yy:=-yy;
9148 zx:=-zx;
9149 end;
9150 Radicand:=((xx+yy)+zz)+1.0;
9151 Scale:=0.5/sqrt(Radicand);
9152 TempX:=(zy-yz)*Scale;
9153 TempY:=(xz-zx)*Scale;
9154 TempZ:=(yx-xy)*Scale;
9155 TempW:=Radicand*Scale;
9156 if LargestXorY then begin
9157 result.x:=TempW;
9158 result.y:=TempZ;
9159 result.z:=TempY;
9160 result.w:=TempX;
9161 end else begin
9162 result.x:=TempX;
9163 result.y:=TempY;
9164 result.z:=TempZ;
9165 result.w:=TempW;
9166 end;
9167 if LargestYorZ then begin
9168 TempX:=result.x;
9169 TempZ:=result.z;
9170 result.x:=result.y;
9171 result.y:=TempX;
9172 result.z:=result.w;
9173 result.w:=TempZ;
9174 end;
9175 end;{}
9176
9177 function QuaternionToMatrix4x4(AQuaternion:TKraftQuaternion):TKraftMatrix4x4;
9178 var qx2,qy2,qz2,qxqx2,qxqy2,qxqz2,qxqw2,qyqy2,qyqz2,qyqw2,qzqz2,qzqw2:TKraftScalar;
9179 begin
9180 QuaternionNormalize(AQuaternion);
9181 qx2:=AQuaternion.x+AQuaternion.x;
9182 qy2:=AQuaternion.y+AQuaternion.y;
9183 qz2:=AQuaternion.z+AQuaternion.z;
9184 qxqx2:=AQuaternion.x*qx2;
9185 qxqy2:=AQuaternion.x*qy2;
9186 qxqz2:=AQuaternion.x*qz2;
9187 qxqw2:=AQuaternion.w*qx2;
9188 qyqy2:=AQuaternion.y*qy2;
9189 qyqz2:=AQuaternion.y*qz2;
9190 qyqw2:=AQuaternion.w*qy2;
9191 qzqz2:=AQuaternion.z*qz2;
9192 qzqw2:=AQuaternion.w*qz2;
9193 result[0,0]:=1.0-(qyqy2+qzqz2);
9194 result[0,1]:=qxqy2+qzqw2;
9195 result[0,2]:=qxqz2-qyqw2;
9196 result[0,3]:=0.0;
9197 result[1,0]:=qxqy2-qzqw2;
9198 result[1,1]:=1.0-(qxqx2+qzqz2);
9199 result[1,2]:=qyqz2+qxqw2;
9200 result[1,3]:=0.0;
9201 result[2,0]:=qxqz2+qyqw2;
9202 result[2,1]:=qyqz2-qxqw2;
9203 result[2,2]:=1.0-(qxqx2+qyqy2);
9204 result[2,3]:=0.0;
9205 result[3,0]:=0.0;
9206 result[3,1]:=0.0;
9207 result[3,2]:=0.0;
9208 result[3,3]:=1.0;
9209 end;
9210
9211 function QuaternionToEuler(const AQuaternion:TKraftQuaternion):TKraftVector3; {$ifdef caninline}inline;{$endif}
9212 begin
9213 result.x:=ArcTan2(2.0*((AQuaternion.x*AQuaternion.y)+(AQuaternion.z*AQuaternion.w)),1.0-(2.0*(sqr(AQuaternion.y)+sqr(AQuaternion.z))));
9214 result.y:=ArcSin(2.0*((AQuaternion.x*AQuaternion.z)-(AQuaternion.y*AQuaternion.w)));
9215 result.z:=ArcTan2(2.0*((AQuaternion.x*AQuaternion.w)+(AQuaternion.y*AQuaternion.z)),1.0-(2.0*(sqr(AQuaternion.z)+sqr(AQuaternion.w))));
9216 end;
9217
9218 procedure QuaternionToAxisAngle(AQuaternion:TKraftQuaternion;var Axis:TKraftVector3;var Angle:TKraftScalar); {$ifdef caninline}inline;{$endif}
9219 var SinAngle:TKraftScalar;
9220 begin
9221 QuaternionNormalize(AQuaternion);
9222 SinAngle:=sqrt(1.0-sqr(AQuaternion.w));
9223 if abs(SinAngle)<EPSILON then begin
9224 SinAngle:=1.0;
9225 end;
9226 Angle:=2.0*ArcCos(AQuaternion.w);
9227 Axis.x:=AQuaternion.x/SinAngle;
9228 Axis.y:=AQuaternion.y/SinAngle;
9229 Axis.z:=AQuaternion.z/SinAngle;
9230 end;
9231
9232 function QuaternionGenerator(AQuaternion:TKraftQuaternion):TKraftVector3; {$ifdef caninline}inline;{$endif}
9233 var s:TKraftScalar;
9234 begin
9235 s:=sqrt(1.0-sqr(AQuaternion.w));
9236 result.x:=AQuaternion.x;
9237 result.y:=AQuaternion.y;
9238 result.z:=AQuaternion.z;
9239 if s>0.0 then begin
9240 result:=Vector3ScalarMul(result,s);
9241 end;
9242 result:=Vector3ScalarMul(result,2.0*ArcTan2(s,AQuaternion.w));
9243 end;
9244
9245 function QuaternionLerp(const q1,q2:TKraftQuaternion;const t:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
9246 var it,sf:TKraftScalar;
9247 begin
9248 if ((q1.x*q2.x)+(q1.y*q2.y)+(q1.z*q2.z)+(q1.w*q2.w))<0.0 then begin
9249 sf:=-1.0;
9250 end else begin
9251 sf:=1.0;
9252 end;
9253 it:=1.0-t;
9254 result.x:=(it*q1.x)+(t*(sf*q2.x));
9255 result.y:=(it*q1.y)+(t*(sf*q2.y));
9256 result.z:=(it*q1.z)+(t*(sf*q2.z));
9257 result.w:=(it*q1.w)+(t*(sf*q2.w));
9258 end;
9259
9260 function QuaternionNlerp(const q1,q2:TKraftQuaternion;const t:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
9261 var it,sf:TKraftScalar;
9262 begin
9263 if ((q1.x*q2.x)+(q1.y*q2.y)+(q1.z*q2.z)+(q1.w*q2.w))<0.0 then begin
9264 sf:=-1.0;
9265 end else begin
9266 sf:=1.0;
9267 end;
9268 it:=1.0-t;
9269 result.x:=(it*q1.x)+(t*(sf*q2.x));
9270 result.y:=(it*q1.y)+(t*(sf*q2.y));
9271 result.z:=(it*q1.z)+(t*(sf*q2.z));
9272 result.w:=(it*q1.w)+(t*(sf*q2.w));
9273 QuaternionNormalize(result);
9274 end;
9275
9276 function QuaternionSlerp(const q1,q2:TKraftQuaternion;const t:TKraftScalar):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
9277 var Omega,co,so,s0,s1,s2:TKraftScalar;
9278 begin
9279 co:=(q1.x*q2.x)+(q1.y*q2.y)+(q1.z*q2.z)+(q1.w*q2.w);
9280 if co<0.0 then begin
9281 co:=-co;
9282 s2:=-1.0;
9283 end else begin
9284 s2:=1.0;
9285 end;
9286 if (1.0-co)>EPSILON then begin
9287 Omega:=ArcCos(co);
9288 so:=sin(Omega);
9289 s0:=sin((1.0-t)*Omega)/so;
9290 s1:=sin(t*Omega)/so;
9291 end else begin
9292 s0:=1.0-t;
9293 s1:=t;
9294 end;
9295 result.x:=(s0*q1.x)+(s1*(s2*q2.x));
9296 result.y:=(s0*q1.y)+(s1*(s2*q2.y));
9297 result.z:=(s0*q1.z)+(s1*(s2*q2.z));
9298 result.w:=(s0*q1.w)+(s1*(s2*q2.w));
9299 end;
9300
9301 function QuaternionIntegrate(const q:TKraftQuaternion;const Omega:TKraftVector3;const DeltaTime:TKraftScalar):TKraftQuaternion;
9302 var ThetaLenSquared,ThetaLen,s:TKraftScalar;
9303 DeltaQ:TKraftQuaternion;
9304 Theta:TKraftVector3;
9305 begin
9306 Theta:=Vector3ScalarMul(Omega,DeltaTime*0.5);
9307 ThetaLenSquared:=Vector3LengthSquared(Theta);
9308 if (sqr(ThetaLenSquared)/24.0)<EPSILON then begin
9309 DeltaQ.w:=1.0-(ThetaLenSquared*0.5);
9310 s:=1.0-(ThetaLenSquared/6.0);
9311 end else begin
9312 ThetaLen:=sqrt(ThetaLenSquared);
9313 DeltaQ.w:=cos(ThetaLen);
9314 s:=sin(ThetaLen)/ThetaLen;
9315 end;
9316 DeltaQ.x:=Theta.x*s;
9317 DeltaQ.y:=Theta.y*s;
9318 DeltaQ.z:=Theta.z*s;
9319 result:=QuaternionMul(DeltaQ,q);
9320 end;
9321
9322 function QuaternionSpin(const q:TKraftQuaternion;const Omega:TKraftVector3;const DeltaTime:TKraftScalar):TKraftQuaternion; overload;
9323 var wq:TKraftQuaternion;
9324 begin
9325 wq.x:=Omega.x*DeltaTime;
9326 wq.y:=Omega.y*DeltaTime;
9327 wq.z:=Omega.z*DeltaTime;
9328 wq.w:=0.0;
9329 result:=QuaternionTermNormalize(QuaternionAdd(q,QuaternionScalarMul(QuaternionMul(wq,q),0.5)));
9330 end;
9331
9332 procedure QuaternionDirectSpin(var q:TKraftQuaternion;const Omega:TKraftVector3;const DeltaTime:TKraftScalar); overload;
9333 var wq,tq:TKraftQuaternion;
9334 begin
9335 wq.x:=Omega.x*DeltaTime;
9336 wq.y:=Omega.y*DeltaTime;
9337 wq.z:=Omega.z*DeltaTime;
9338 wq.w:=0.0;
9339 tq:=QuaternionAdd(q,QuaternionScalarMul(QuaternionMul(wq,q),0.5));
9340 q:=QuaternionTermNormalize(tq);
9341 end;
9342
9343 function QuaternionFromToRotation(const FromDirection,ToDirection:TKraftVector3):TKraftQuaternion; {$ifdef caninline}inline;{$endif}
9344 var t:TKraftVector3;
9345 begin
9346 t:=Vector3Cross(Vector3Norm(FromDirection),Vector3Norm(ToDirection));
9347 result.x:=t.x;
9348 result.y:=t.y;
9349 result.z:=t.z;
9350 result.w:=sqrt((sqr(FromDirection.x)+sqr(FromDirection.y)+sqr(FromDirection.z))*
9351 (sqr(ToDirection.x)+sqr(ToDirection.y)+sqr(ToDirection.z)))+
9352 ((FromDirection.x*ToDirection.x)+(FromDirection.y*ToDirection.y)+(FromDirection.z*ToDirection.z));
9353 end;
9354
9355 function AABBCost(const AABB:TKraftAABB):TKraftScalar; {$ifdef caninline}inline;{$endif}
9356 begin
9357 // result:=(AABB.Max.x-AABB.Min.x)+(AABB.Max.y-AABB.Min.y)+(AABB.Max.z-AABB.Min.z); // Manhattan distance
9358 result:=(AABB.Max.x-AABB.Min.x)*(AABB.Max.y-AABB.Min.y)*(AABB.Max.z-AABB.Min.z); // Volume
9359 end;
9360
9361 function AABBCombine(const AABB,WithAABB:TKraftAABB):TKraftAABB; {$ifdef caninline}inline;{$endif}
9362 begin
9363 result.Min.x:=Min(AABB.Min.x,WithAABB.Min.x);
9364 result.Min.y:=Min(AABB.Min.y,WithAABB.Min.y);
9365 result.Min.z:=Min(AABB.Min.z,WithAABB.Min.z);
9366 result.Max.x:=Max(AABB.Max.x,WithAABB.Max.x);
9367 result.Max.y:=Max(AABB.Max.y,WithAABB.Max.y);
9368 result.Max.z:=Max(AABB.Max.z,WithAABB.Max.z);
9369 end;
9370
9371 function AABBCombineVector3(const AABB:TKraftAABB;v:TKraftVector3):TKraftAABB; {$ifdef caninline}inline;{$endif}
9372 begin
9373 result.Min.x:=Min(AABB.Min.x,v.x);
9374 result.Min.y:=Min(AABB.Min.y,v.y);
9375 result.Min.z:=Min(AABB.Min.z,v.z);
9376 result.Max.x:=Max(AABB.Max.x,v.x);
9377 result.Max.y:=Max(AABB.Max.y,v.y);
9378 result.Max.z:=Max(AABB.Max.z,v.z);
9379 end;
9380
9381 function AABBIntersect(const AABB,WithAABB:TKraftAABB;Threshold:TKraftScalar=EPSILON):boolean; {$ifdef caninline}inline;{$endif}
9382 begin
9383 result:=(((AABB.Max.x+Threshold)>=(WithAABB.Min.x-Threshold)) and ((AABB.Min.x-Threshold)<=(WithAABB.Max.x+Threshold))) and
9384 (((AABB.Max.y+Threshold)>=(WithAABB.Min.y-Threshold)) and ((AABB.Min.y-Threshold)<=(WithAABB.Max.y+Threshold))) and
9385 (((AABB.Max.z+Threshold)>=(WithAABB.Min.z-Threshold)) and ((AABB.Min.z-Threshold)<=(WithAABB.Max.z+Threshold)));
9386 end;
9387
9388 function AABBContains(const InAABB,AABB:TKraftAABB):boolean; overload; {$ifdef caninline}inline;{$endif}
9389 begin
9390 result:=((InAABB.Min.x-EPSILON)<=(AABB.Min.x+EPSILON)) and ((InAABB.Min.y-EPSILON)<=(AABB.Min.y+EPSILON)) and ((InAABB.Min.z-EPSILON)<=(AABB.Min.z+EPSILON)) and
9391 ((InAABB.Max.x+EPSILON)>=(AABB.Min.x+EPSILON)) and ((InAABB.Max.y+EPSILON)>=(AABB.Min.y+EPSILON)) and ((InAABB.Max.z+EPSILON)>=(AABB.Min.z+EPSILON)) and
9392 ((InAABB.Min.x-EPSILON)<=(AABB.Max.x-EPSILON)) and ((InAABB.Min.y-EPSILON)<=(AABB.Max.y-EPSILON)) and ((InAABB.Min.z-EPSILON)<=(AABB.Max.z-EPSILON)) and
9393 ((InAABB.Max.x+EPSILON)>=(AABB.Max.x-EPSILON)) and ((InAABB.Max.y+EPSILON)>=(AABB.Max.y-EPSILON)) and ((InAABB.Max.z+EPSILON)>=(AABB.Max.z-EPSILON));
9394 end;
9395
9396 function AABBContains(const AABB:TKraftAABB;Vector:TKraftVector3):boolean; overload; {$ifdef caninline}inline;{$endif}
9397 begin
9398 result:=((Vector.x>=(AABB.Min.x-EPSILON)) and (Vector.x<=(AABB.Max.x+EPSILON))) and
9399 ((Vector.y>=(AABB.Min.y-EPSILON)) and (Vector.y<=(AABB.Max.y+EPSILON))) and
9400 ((Vector.z>=(AABB.Min.z-EPSILON)) and (Vector.z<=(AABB.Max.z+EPSILON)));
9401 end;
9402
9403 function AABBTransform(const DstAABB:TKraftAABB;const Transform:TKraftMatrix4x4):TKraftAABB; {$ifdef caninline}inline;{$endif}
9404 var i,j:longint;
9405 a,b:TKraftScalar;
9406 begin
9407 result.Min:=Vector3(Transform[3,0],Transform[3,1],Transform[3,2]);
9408 result.Max:=result.Min;
9409 for i:=0 to 2 do begin
9410 for j:=0 to 2 do begin
9411 a:=Transform[j,i]*DstAABB.Min.xyz[j];
9412 b:=Transform[j,i]*DstAABB.Max.xyz[j];
9413 if a<b then begin
9414 result.Min.xyz[i]:=result.Min.xyz[i]+a;
9415 result.Max.xyz[i]:=result.Max.xyz[i]+b;
9416 end else begin
9417 result.Min.xyz[i]:=result.Min.xyz[i]+b;
9418 result.Max.xyz[i]:=result.Max.xyz[i]+a;
9419 end;
9420 end;
9421 end;
9422 end;
9423
9424 function AABBRayIntersection(const AABB:TKraftAABB;const Origin,Direction:TKraftVector3;var Time:TKraftScalar):boolean; overload; {$ifdef caninline}inline;{$endif}
9425 var InvDirection,a,b,AABBMin,AABBMax:TKraftVector3;
9426 TimeMin,TimeMax:TKraftScalar;
9427 begin
9428 if Direction.x<>0.0 then begin
9429 InvDirection.x:=1.0/Direction.x;
9430 end else begin
9431 InvDirection.x:=0.0;
9432 end;
9433 if Direction.y<>0.0 then begin
9434 InvDirection.y:=1.0/Direction.y;
9435 end else begin
9436 InvDirection.y:=0.0;
9437 end;
9438 if Direction.z<>0.0 then begin
9439 InvDirection.z:=1.0/Direction.z;
9440 end else begin
9441 InvDirection.z:=0.0;
9442 end;
9443 a.x:=(AABB.Min.x-Origin.x)*InvDirection.x;
9444 a.y:=(AABB.Min.y-Origin.y)*InvDirection.y;
9445 a.z:=(AABB.Min.z-Origin.z)*InvDirection.z;
9446 b.x:=(AABB.Max.x-Origin.x)*InvDirection.x;
9447 b.y:=(AABB.Max.y-Origin.y)*InvDirection.y;
9448 b.z:=(AABB.Max.z-Origin.z)*InvDirection.z;
9449 if a.x<b.x then begin
9450 AABBMin.x:=a.x;
9451 AABBMax.x:=b.x;
9452 end else begin
9453 AABBMin.x:=b.x;
9454 AABBMax.x:=a.x;
9455 end;
9456 if a.y<b.y then begin
9457 AABBMin.y:=a.y;
9458 AABBMax.y:=b.y;
9459 end else begin
9460 AABBMin.y:=b.y;
9461 AABBMax.y:=a.y;
9462 end;
9463 if a.z<b.z then begin
9464 AABBMin.z:=a.z;
9465 AABBMax.z:=b.z;
9466 end else begin
9467 AABBMin.z:=b.z;
9468 AABBMax.z:=a.z;
9469 end;
9470 if AABBMin.x<AABBMin.y then begin
9471 if AABBMin.x<AABBMin.z then begin
9472 TimeMin:=AABBMin.x;
9473 end else begin
9474 TimeMin:=AABBMin.z;
9475 end;
9476 end else begin
9477 if AABBMin.y<AABBMin.z then begin
9478 TimeMin:=AABBMin.y;
9479 end else begin
9480 TimeMin:=AABBMin.z;
9481 end;
9482 end;
9483 if AABBMax.x>AABBMax.y then begin
9484 if AABBMax.x>AABBMax.z then begin
9485 TimeMax:=AABBMax.x;
9486 end else begin
9487 TimeMax:=AABBMax.z;
9488 end;
9489 end else begin
9490 if AABBMax.y>AABBMax.z then begin
9491 TimeMax:=AABBMax.y;
9492 end else begin
9493 TimeMax:=AABBMax.z;
9494 end;
9495 end;
9496 if (TimeMax<0) or (TimeMin>TimeMax) then begin
9497 Time:=TimeMax;
9498 result:=false;
9499 end else begin
9500 Time:=TimeMin;
9501 result:=true;
9502 end;
9503 end;
9504
9505 function AABBRayIntersect(const AABB:TKraftAABB;const Origin,Direction:TKraftVector3):boolean; {$ifdef caninline}inline;{$endif}
9506 var Center,BoxExtents,Diff:TKraftVector3;
9507 begin
9508 Center:=Vector3ScalarMul(Vector3Add(AABB.Min,AABB.Max),0.5);
9509 BoxExtents:=Vector3Sub(Center,AABB.Min);
9510 Diff:=Vector3Sub(Origin,Center);
9511 result:=not ((((abs(Diff.x)>BoxExtents.x) and ((Diff.x*Direction.x)>=0)) or
9512 ((abs(Diff.y)>BoxExtents.y) and ((Diff.y*Direction.y)>=0)) or
9513 ((abs(Diff.z)>BoxExtents.z) and ((Diff.z*Direction.z)>=0))) or
9514 ((abs((Direction.y*Diff.z)-(Direction.z*Diff.y))>((BoxExtents.y*abs(Direction.z))+(BoxExtents.z*abs(Direction.y)))) or
9515 (abs((Direction.z*Diff.x)-(Direction.x*Diff.z))>((BoxExtents.x*abs(Direction.z))+(BoxExtents.z*abs(Direction.x)))) or
9516 (abs((Direction.x*Diff.y)-(Direction.y*Diff.x))>((BoxExtents.x*abs(Direction.y))+(BoxExtents.y*abs(Direction.x))))));
9517 end;
9518
9519 function ClosestPointToAABB(const AABB:TKraftAABB;const Point:TKraftVector3;const ClosestPointOnAABB:PKraftVector3=nil):TKraftScalar; {$ifdef caninline}inline;{$endif}
9520 var ClosestPoint:TKraftVector3;
9521 begin
9522 ClosestPoint.x:=Min(Max(Point.x,AABB.Min.x),AABB.Max.x);
9523 ClosestPoint.y:=Min(Max(Point.y,AABB.Min.y),AABB.Max.y);
9524 ClosestPoint.z:=Min(Max(Point.z,AABB.Min.z),AABB.Max.z);
9525 if assigned(ClosestPointOnAABB) then begin
9526 ClosestPointOnAABB^:=ClosestPoint;
9527 end;
9528 result:=Vector3Dist(ClosestPoint,Point);
9529 end;
9530
9531 function SquaredDistanceFromPointToAABB(const AABB:TKraftAABB;const Point:TKraftVector3):TKraftScalar; {$ifdef caninline}inline;{$endif}
9532 var ClosestPoint:TKraftVector3;
9533 begin
9534 ClosestPoint.x:=Min(Max(Point.x,AABB.Min.x),AABB.Max.x);
9535 ClosestPoint.y:=Min(Max(Point.y,AABB.Min.y),AABB.Max.y);
9536 ClosestPoint.z:=Min(Max(Point.z,AABB.Min.z),AABB.Max.z);
9537 result:=Vector3DistSquared(ClosestPoint,Point);
9538 end;
9539
9540 function SphereFromAABB(const AABB:TKraftAABB):TKraftSphere; {$ifdef caninline}inline;{$endif}
9541 begin
9542 result.Center:=Vector3Avg(AABB.Min,AABB.Max);
9543 result.Radius:=Vector3Dist(AABB.Min,AABB.Max)*0.5;
9544 end;
9545
9546 function RayIntersectTriangle(const RayOrigin,RayDirection,v0,v1,v2:TKraftVector3;var Time,u,v:TKraftScalar):boolean; overload;
9547 var e0,e1,p,t,q:TKraftVector3;
9548 Determinant,InverseDeterminant:TKraftScalar;
9549 begin
9550 result:=false;
9551
9552 e0.x:=v1.x-v0.x;
9553 e0.y:=v1.y-v0.y;
9554 e0.z:=v1.z-v0.z;
9555 e1.x:=v2.x-v0.x;
9556 e1.y:=v2.y-v0.y;
9557 e1.z:=v2.z-v0.z;
9558
9559 p.x:=(RayDirection.y*e1.z)-(RayDirection.z*e1.y);
9560 p.y:=(RayDirection.z*e1.x)-(RayDirection.x*e1.z);
9561 p.z:=(RayDirection.x*e1.y)-(RayDirection.y*e1.x);
9562
9563 Determinant:=(e0.x*p.x)+(e0.y*p.y)+(e0.z*p.z);
9564 if Determinant<EPSILON then begin
9565 exit;
9566 end;
9567
9568 t.x:=RayOrigin.x-v0.x;
9569 t.y:=RayOrigin.y-v0.y;
9570 t.z:=RayOrigin.z-v0.z;
9571
9572 u:=(t.x*p.x)+(t.y*p.y)+(t.z*p.z);
9573 if (u<0.0) or (u>Determinant) then begin
9574 exit;
9575 end;
9576
9577 q.x:=(t.y*e0.z)-(t.z*e0.y);
9578 q.y:=(t.z*e0.x)-(t.x*e0.z);
9579 q.z:=(t.x*e0.y)-(t.y*e0.x);
9580
9581 v:=(RayDirection.x*q.x)+(RayDirection.y*q.y)+(RayDirection.z*q.z);
9582 if (v<0.0) or ((u+v)>Determinant) then begin
9583 exit;
9584 end;
9585
9586 Time:=(e1.x*q.x)+(e1.y*q.y)+(e1.z*q.z);
9587 if abs(Determinant)<EPSILON then begin
9588 Determinant:=0.01;
9589 end;
9590 InverseDeterminant:=1.0/Determinant;
9591 Time:=Time*InverseDeterminant;
9592 u:=u*InverseDeterminant;
9593 v:=v*InverseDeterminant;
9594
9595 result:=true;
9596 end;
9597
9598 function IsPointsSameSide(const p0,p1,Origin,Direction:TKraftVector3):boolean; overload; {$ifdef caninline}inline;{$endif}
9599 begin
9600 result:=Vector3Dot(Vector3Cross(Direction,Vector3Sub(p0,Origin)),Vector3Cross(Direction,Vector3Sub(p1,Origin)))>=0.0;
9601 end;
9602
9603 function PointInTriangle(const p0,p1,p2,Normal,p:TKraftVector3):boolean; overload; {$ifdef caninline}inline;{$endif}
9604 var r0,r1,r2:TKraftScalar;
9605 begin
9606 r0:=Vector3Dot(Vector3Cross(Vector3Sub(p1,p0),Normal),Vector3Sub(p,p0));
9607 r1:=Vector3Dot(Vector3Cross(Vector3Sub(p2,p1),Normal),Vector3Sub(p,p1));
9608 r2:=Vector3Dot(Vector3Cross(Vector3Sub(p0,p2),Normal),Vector3Sub(p,p2));
9609 result:=((r0>0.0) and (r1>0.0) and (r2>0.0)) or ((r0<=0.0) and (r1<=0.0) and (r2<=0.0));
9610 end;
9611
9612 function PointInTriangle(const p0,p1,p2,p:TKraftVector3):boolean; overload; {$ifdef caninline}inline;{$endif}
9613 begin
9614 result:=IsPointsSameSide(p,p0,p1,Vector3Sub(p2,p1)) and
9615 IsPointsSameSide(p,p1,p0,Vector3Sub(p2,p0)) and
9616 IsPointsSameSide(p,p2,p0,Vector3Sub(p1,p0));
9617 end;
9618
9619 function SquaredDistanceFromPointToTriangle(const p,a,b,c:TKraftVector3):TKraftScalar;
9620 var ab,ac,bc,pa,pb,pc,ap,bp,cp,n:TKraftVector3;
9621 snom,sdenom,tnom,tdenom,unom,udenom,vc,vb,va,u,v,w:TKraftScalar;
9622 begin
9623
9624 ab.x:=b.x-a.x;
9625 ab.y:=b.y-a.y;
9626 ab.z:=b.z-a.z;
9627
9628 ac.x:=c.x-a.x;
9629 ac.y:=c.y-a.y;
9630 ac.z:=c.z-a.z;
9631
9632 bc.x:=c.x-b.x;
9633 bc.y:=c.y-b.y;
9634 bc.z:=c.z-b.z;
9635
9636 pa.x:=p.x-a.x;
9637 pa.y:=p.y-a.y;
9638 pa.z:=p.z-a.z;
9639
9640 pb.x:=p.x-b.x;
9641 pb.y:=p.y-b.y;
9642 pb.z:=p.z-b.z;
9643
9644 pc.x:=p.x-c.x;
9645 pc.y:=p.y-c.y;
9646 pc.z:=p.z-c.z;
9647
9648 // Determine the parametric position s for the projection of P onto AB (i.e. PPU2 = A+s*AB, where
9649 // s = snom/(snom+sdenom), and then parametric position t for P projected onto AC
9650 snom:=(ab.x*pa.x)+(ab.y*pa.y)+(ab.z*pa.z);
9651 sdenom:=(pb.x*(a.x-b.x))+(pb.y*(a.y-b.y))+(pb.z*(a.z-b.z));
9652 tnom:=(ac.x*pa.x)+(ac.y*pa.y)+(ac.z*pa.z);
9653 tdenom:=(pc.x*(a.x-c.x))+(pc.y*(a.y-c.y))+(pc.z*(a.z-c.z));
9654 if (snom<=0.0) and (tnom<=0.0) then begin
9655 // Vertex voronoi region hit early out
9656 result:=sqr(a.x-p.x)+sqr(a.y-p.y)+sqr(a.z-p.z);
9657 exit;
9658 end;
9659
9660 // Parametric position u for P projected onto BC
9661 unom:=(bc.x*pb.x)+(bc.y*pb.y)+(bc.z*pb.z);
9662 udenom:=(pc.x*(b.x-c.x))+(pc.y*(b.y-c.y))+(pc.z*(b.z-c.z));
9663 if (sdenom<=0.0) and (unom<=0.0) then begin
9664 // Vertex voronoi region hit early out
9665 result:=sqr(b.x-p.x)+sqr(b.y-p.y)+sqr(b.z-p.z);
9666 exit;
9667 end;
9668 if (tdenom<=0.0) and (udenom<=0.0) then begin
9669 // Vertex voronoi region hit early out
9670 result:=sqr(c.x-p.x)+sqr(c.y-p.y)+sqr(c.z-p.z);
9671 exit;
9672 end;
9673
9674 // Determine if P is outside (or on) edge AB by finding the area formed by vectors PA, PB and
9675 // the triangle normal. A scalar triple product is used. P is outside (or on) AB if the triple
9676 // scalar product [N PA PB] <= 0
9677 n.x:=(ab.y*ac.z)-(ab.z*ac.y);
9678 n.y:=(ab.z*ac.x)-(ab.x*ac.z);
9679 n.z:=(ab.x*ac.y)-(ab.y*ac.x);
9680 ap.x:=a.x-p.x;
9681 ap.y:=a.y-p.y;
9682 ap.z:=a.z-p.z;
9683 bp.x:=b.x-p.x;
9684 bp.y:=b.y-p.y;
9685 bp.z:=b.z-p.z;
9686 vc:=(n.x*((ap.y*bp.z)-(ap.z*bp.y)))+(n.y*((ap.z*bp.x)-(ap.x*bp.z)))+(n.z*((ap.x*bp.y)-(ap.y*bp.x)));
9687
9688 // If P is outside of AB (signed area <= 0) and within voronoi feature region, then return
9689 // projection of P onto AB
9690 if (vc<=0.0) and (snom>=0.0) and (sdenom>=0.0) then begin
9691 u:=snom/(snom+sdenom);
9692 result:=sqr((a.x+(ab.x*u))-p.x)+sqr((a.y+(ab.y*u))-p.y)+sqr((a.z+(ab.z*u))-p.z);
9693 exit;
9694 end;
9695
9696 // Repeat the same test for P onto BC
9697 cp.x:=c.x-p.x;
9698 cp.y:=c.y-p.y;
9699 cp.z:=c.z-p.z;
9700 va:=(n.x*((bp.y*cp.z)-(bp.z*cp.y)))+(n.y*((bp.z*cp.x)-(bp.x*cp.z)))+(n.z*((bp.x*cp.y)-(bp.y*cp.x)));
9701 if (va<=0.0) and (unom>=0.0) and (udenom>=0.0) then begin
9702 v:=unom/(unom+udenom);
9703 result:=sqr((b.x+(bc.x*v))-p.x)+sqr((b.y+(bc.y*v))-p.y)+sqr((b.z+(bc.z*v))-p.z);
9704 exit;
9705 end;
9706
9707 // Repeat the same test for P onto CA
9708 vb:=(n.x*((cp.y*ap.z)-(cp.z*ap.y)))+(n.y*((cp.z*ap.x)-(cp.x*ap.z)))+(n.z*((cp.x*ap.y)-(cp.y*ap.x)));
9709 if (vb<=0.0) and (tnom>=0.0) and (tdenom>=0.0) then begin
9710 w:=tnom/(tnom+tdenom);
9711 result:=sqr((a.x+(ac.x*w))-p.x)+sqr((a.y+(ac.y*w))-p.y)+sqr((a.z+(ac.z*w))-p.z);
9712 exit;
9713 end;
9714
9715 // P must project onto inside face. Find closest point using the barycentric coordinates
9716 w:=1.0/(va+vb+vc);
9717 u:=va*w;
9718 v:=vb*w;
9719 w:=(1.0-u)-v;
9720
9721 result:=sqr(((a.x*u)+(b.x*v)+(c.x*w))-p.x)+sqr(((a.y*u)+(b.y*v)+(c.y*w))-p.y)+sqr(((a.z*u)+(b.z*v)+(c.z*w))-p.z);
9722
9723 end;
9724
9725 function SegmentSqrDistance(const FromVector,ToVector,p:TKraftVector3;out Nearest:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
9726 var t,DotUV:TKraftScalar;
9727 Diff,v:TKraftVector3;
9728 begin
9729 Diff:=Vector3Sub(p,FromVector);
9730 v:=Vector3Sub(ToVector,FromVector);
9731 t:=Vector3Dot(v,Diff);
9732 if t>0.0 then begin
9733 DotUV:=Vector3LengthSquared(v);
9734 if t<DotUV then begin
9735 t:=t/DotUV;
9736 Diff:=Vector3Sub(Diff,Vector3ScalarMul(v,t));
9737 end else begin
9738 t:=1;
9739 Diff:=Vector3Sub(Diff,v);
9740 end;
9741 end else begin
9742 t:=0.0;
9743 end;
9744 Nearest:=Vector3Lerp(FromVector,ToVector,t);
9745 result:=Vector3LengthSquared(Diff);
9746 end;
9747
9748 function ClipSegmentToPlane(const Plane:TKraftPlane;var p0,p1:TKraftVector3):boolean;
9749 var d0,d1:TKraftScalar;
9750 o0,o1:boolean;
9751 begin
9752 d0:=PlaneVectorDistance(Plane,p0);
9753 d1:=PlaneVectorDistance(Plane,p1);
9754 o0:=d0<0.0;
9755 o1:=d1<0.0;
9756 if o0 and o1 then begin
9757 // Both points are below which means that the whole line segment is below => return false
9758 result:=false;
9759 end else begin
9760 // At least one point is above or in the plane which means that the line segment is above => return true
9761 if (o0<>o1) and (abs(d0-d1)>EPSILON) then begin
9762 if o0 then begin
9763 // p1 is above or in the plane which means that the line segment is above => clip l0
9764 p0:=Vector3Add(p0,Vector3ScalarMul(Vector3Sub(p1,p0),d0/(d0-d1)));
9765 end else begin
9766 // p0 is above or in the plane which means that the line segment is above => clip l1
9767 p1:=Vector3Add(p0,Vector3ScalarMul(Vector3Sub(p1,p0),d0/(d0-d1)));
9768 end;
9769 end else begin
9770 // Near parallel case => no clipping
9771 end;
9772 result:=true;
9773 end;
9774 end;
9775
9776 function SegmentSegmentDistanceSq(out t0,t1:single;seg0,seg1:TKraftRelativeSegment):single;
9777 var kDiff:TKraftVector3;
9778 fA00,fA01,fA11,fB0,fC,fDet,fB1,fS,fT,fSqrDist,fTmp,fInvDet:TKraftScalar;
9779 begin
9780 kDiff:=Vector3Sub(seg0.Origin,seg1.Origin);
9781 fA00:=Vector3LengthSquared(seg0.Delta);
9782 fA01:=-Vector3Dot(seg0.Delta,seg1.Delta);
9783 fA11:=Vector3LengthSquared(seg1.Delta);
9784 fB0:=Vector3Dot(kDiff,seg0.Delta);
9785 fC:=Vector3LengthSquared(kDiff);
9786 fDet:=abs((fA00*fA11)-(fA01*fA01));
9787 if fDet>=EPSILON then begin
9788 // line segments are not parallel
9789 fB1:=-Vector3Dot(kDiff,seg1.Delta);
9790 fS:=(fA01*fB1)-(fA11*fB0);
9791 fT:=(fA01*fB0)-(fA00*fB1);
9792 if fS>=0.0 then begin
9793 if fS<=fDet then begin
9794 if fT>=0.0 then begin
9795 if fT<=fDet then begin // region 0 (interior)
9796 // minimum at two interior points of 3D lines
9797 fInvDet:=1.0/fDet;
9798 fS:=fS*fInvDet;
9799 fT:=fT*fInvDet;
9800 fSqrDist:=(fS*((fA00*fS)+(fA01*fT)+(2.0*fB0)))+(fT*((fA01*fS)+(fA11*fT)+(2.0*fB1)))+fC;
9801 end else begin // region 3 (side)
9802 fT:=1.0;
9803 fTmp:=fA01+fB0;
9804 if fTmp>=0.0 then begin
9805 fS:=0.0;
9806 fSqrDist:=fA11+(2.0*fB1)+fC;
9807 end else if (-fTmp)>=fA00 then begin
9808 fS:=1.0;
9809 fSqrDist:=fA00+fA11+fC+(2.0*(fB1+fTmp));
9810 end else begin
9811 fS:=-fTmp/fA00;
9812 fSqrDist:=fTmp*fS+fA11+(2.0*fB1)+fC;
9813 end;
9814 end;
9815 end else begin // region 7 (side)
9816 fT:=0.0;
9817 if fB0>=0.0 then begin
9818 fS:=0.0;
9819 fSqrDist:=fC;
9820 end else if (-fB0)>=fA00 then begin
9821 fS:=1.0;
9822 fSqrDist:=fA00+(2.0*fB0)+fC;
9823 end else begin
9824 fS:=(-fB0)/fA00;
9825 fSqrDist:=(fB0*fS)+fC;
9826 end;
9827 end;
9828 end else begin
9829 if fT>=0.0 then begin
9830 if fT<=fDet then begin // region 1 (side)
9831 fS:=1.0;
9832 fTmp:=fA01+fB1;
9833 if fTmp>=0.0 then begin
9834 fT:=0.0;
9835 fSqrDist:=fA00+(2.0*fB0)+fC;
9836 end else if (-fTmp)>=fA11 then begin
9837 fT:=1.0;
9838 fSqrDist:=fA00+fA11+fC+(2.0*(fB0+fTmp));
9839 end else begin
9840 fT:=(-fTmp)/fA11;
9841 fSqrDist:=(fTmp*fT)+fA00+(2.0*fB0)+fC;
9842 end;
9843 end else begin // region 2 (corner)
9844 fTmp:=fA01+fB0;
9845 if (-fTmp)<=fA00 then begin
9846 fT:=1.0;
9847 if fTmp>=0.0 then begin
9848 fS:=0.0;
9849 fSqrDist:=fA11+(2.0*fB1)+fC;
9850 end else begin
9851 fS:=(-fTmp)/fA00;
9852 fSqrDist:=(fTmp*fS)+fA11+(2.0*fB1)+fC;
9853 end;
9854 end else begin
9855 fS:=1.0;
9856 fTmp:=fA01+fB1;
9857 if fTmp>=0.0 then begin
9858 fT:=0.0;
9859 fSqrDist:=fA00+(2.0*fB0)+fC;
9860 end else if (-fTmp)>=fA11 then begin
9861 fT:=1.0;
9862 fSqrDist:=fA00+fA11+fC+(2.0*(fB0+fTmp));
9863 end else begin
9864 fT:=(-fTmp)/fA11;
9865 fSqrDist:=(fTmp*fT)+fA00+(2.0*fB0)+fC;
9866 end;
9867 end;
9868 end;
9869 end else begin // region 8 (corner)
9870 if (-fB0)<fA00 then begin
9871 fT:=0.0;
9872 if fB0>=0.0 then begin
9873 fS:=0.0;
9874 fSqrDist:=fC;
9875 end else begin
9876 fS:=(-fB0)/fA00;
9877 fSqrDist:=(fB0*fS)+fC;
9878 end;
9879 end else begin
9880 fS:=1.0;
9881 fTmp:=fA01+fB1;
9882 if fTmp>=0.0 then begin
9883 fT:=0.0;
9884 fSqrDist:=fA00+(2.0*fB0)+fC;
9885 end else if (-fTmp)>=fA11 then begin
9886 fT:=1.0;
9887 fSqrDist:=fA00+fA11+fC+(2.0*(fB0+fTmp));
9888 end else begin
9889 fT:=(-fTmp)/fA11;
9890 fSqrDist:=(fTmp*fT)+fA00+(2.0*fB0)+fC;
9891 end;
9892 end;
9893 end;
9894 end;
9895 end else begin
9896 if fT>=0.0 then begin
9897 if fT<=fDet then begin // region 5 (side)
9898 fS:=0.0;
9899 if fB1>=0.0 then begin
9900 fT:=0.0;
9901 fSqrDist:=fC;
9902 end else if (-fB1)>=fA11 then begin
9903 fT:=1.0;
9904 fSqrDist:=fA11+(2.0*fB1)+fC;
9905 end else begin
9906 fT:=(-fB1)/fA11;
9907 fSqrDist:=fB1*fT+fC;
9908 end
9909 end else begin // region 4 (corner)
9910 fTmp:=fA01+fB0;
9911 if fTmp<0.0 then begin
9912 fT:=1.0;
9913 if (-fTmp)>=fA00 then begin
9914 fS:=1.0;
9915 fSqrDist:=fA00+fA11+fC+(2.0*(fB1+fTmp));
9916 end else begin
9917 fS:=(-fTmp)/fA00;
9918 fSqrDist:=fTmp*fS+fA11+(2.0*fB1)+fC;
9919 end;
9920 end else begin
9921 fS:=0.0;
9922 if fB1>=0.0 then begin
9923 fT:=0.0;
9924 fSqrDist:=fC;
9925 end else if (-fB1)>=fA11 then begin
9926 fT:=1.0;
9927 fSqrDist:=fA11+(2.0*fB1)+fC;
9928 end else begin
9929 fT:=(-fB1)/fA11;
9930 fSqrDist:=(fB1*fT)+fC;
9931 end;
9932 end;
9933 end;
9934 end else begin // region 6 (corner)
9935 if fB0<0.0 then begin
9936 fT:=0.0;
9937 if (-fB0)>=fA00 then begin
9938 fS:=1.0;
9939 fSqrDist:=fA00+(2.0*fB0)+fC;
9940 end else begin
9941 fS:=(-fB0)/fA00;
9942 fSqrDist:=(fB0*fS)+fC;
9943 end;
9944 end else begin
9945 fS:=0.0;
9946 if fB1>=0.0 then begin
9947 fT:=0.0;
9948 fSqrDist:=fC;
9949 end else if (-fB1)>=fA11 then begin
9950 fT:=1.0;
9951 fSqrDist:=fA11+(2.0*fB1)+fC;
9952 end else begin
9953 fT:=(-fB1)/fA11;
9954 fSqrDist:=(fB1*fT)+fC;
9955 end;
9956 end;
9957 end;
9958 end;
9959 end else begin // line segments are parallel
9960 if fA01>0.0 then begin // direction vectors form an obtuse angle
9961 if fB0>=0.0 then begin
9962 fS:=0.0;
9963 fT:=0.0;
9964 fSqrDist:=fC;
9965 end else if (-fB0)<=fA00 then begin
9966 fS:=(-fB0)/fA00;
9967 fT:=0.0;
9968 fSqrDist:=(fB0*fS)+fC;
9969 end else begin
9970 fB1:=-Vector3Dot(kDiff,seg1.Delta);
9971 fS:=1.0;
9972 fTmp:=fA00+fB0;
9973 if (-fTmp)>=fA01 then begin
9974 fT:=1.0;
9975 fSqrDist:=fA00+fA11+fC+(2.0*(fA01+fB0+fB1));
9976 end else begin
9977 fT:=(-fTmp)/fA01;
9978 fSqrDist:=fA00+(2.0*fB0)+fC+(fT*((fA11*fT)+(2.0*(fA01+fB1))));
9979 end;
9980 end;
9981 end else begin // direction vectors form an acute angle
9982 if (-fB0)>=fA00 then begin
9983 fS:=1.0;
9984 fT:=0.0;
9985 fSqrDist:=fA00+(2.0*fB0)+fC;
9986 end else if fB0<=0.0 then begin
9987 fS:=(-fB0)/fA00;
9988 fT:=0.0;
9989 fSqrDist:=(fB0*fS)+fC;
9990 end else begin
9991 fB1:=-Vector3Dot(kDiff,seg1.Delta);
9992 fS:=0.0;
9993 if fB0>=(-fA01) then begin
9994 fT:=1.0;
9995 fSqrDist:=fA11+(2.0*fB1)+fC;
9996 end else begin
9997 fT:=(-fB0)/fA01;
9998 fSqrDist:=fC+(fT*((2.0)*fB1)+(fA11*fT));
9999 end;
10000 end;
10001 end;
10002 end;
10003 t0:=fS;
10004 t1:=fT;
10005 result:=abs(fSqrDist);
10006 end;
10007
10008 procedure SIMDSegment(out Segment:TKraftSegment;const p0,p1:TKraftVector3); overload;
10009 begin
10010 Segment.Points[0]:=p0;
10011 Segment.Points[1]:=p1;
10012 end;
10013
10014 function SIMDSegment(const p0,p1:TKraftVector3):TKraftSegment; overload;
10015 begin
10016 result.Points[0]:=p0;
10017 result.Points[1]:=p1;
10018 end;
10019
10020 function SIMDSegmentSquaredDistanceTo(const Segment:TKraftSegment;const p:TKraftVector3):TKraftScalar;
10021 var pq,pp:TKraftVector3;
10022 e,f:TKraftScalar;
10023 begin
10024 pq:=Vector3Sub(Segment.Points[1],Segment.Points[0]);
10025 pp:=Vector3Sub(p,Segment.Points[0]);
10026 e:=Vector3Dot(pp,pq);
10027 if e<=0.0 then begin
10028 result:=Vector3LengthSquared(pp);
10029 end else begin
10030 f:=Vector3LengthSquared(pq);
10031 if e<f then begin
10032 result:=Vector3LengthSquared(pp)-(sqr(e)/f);
10033 end else begin
10034 result:=Vector3LengthSquared(Vector3Sub(p,Segment.Points[1]));
10035 end;
10036 end;
10037 end;
10038
10039 procedure SIMDSegmentClosestPointTo(const Segment:TKraftSegment;const p:TKraftVector3;out Time:TKraftScalar;out ClosestPoint:TKraftVector3);
10040 var u,v:TKraftVector3;
10041 begin
10042 u:=Vector3Sub(Segment.Points[1],Segment.Points[0]);
10043 v:=Vector3Sub(p,Segment.Points[0]);
10044 Time:=Vector3Dot(u,v)/Vector3LengthSquared(u);
10045 if Time<=0.0 then begin
10046 ClosestPoint:=Segment.Points[0];
10047 end else if Time>=1.0 then begin
10048 ClosestPoint:=Segment.Points[1];
10049 end else begin
10050 ClosestPoint:=Vector3Add(Vector3ScalarMul(Segment.Points[0],1.0-Time),Vector3ScalarMul(Segment.Points[1],Time));
10051 end;
10052 end;
10053
10054 procedure SIMDSegmentTransform(out OutputSegment:TKraftSegment;const Segment:TKraftSegment;const Transform:TKraftMatrix4x4); overload;
10055 begin
10056 OutputSegment.Points[0]:=Vector3TermMatrixMul(Segment.Points[0],Transform);
10057 OutputSegment.Points[1]:=Vector3TermMatrixMul(Segment.Points[1],Transform);
10058 end;
10059
10060 function SIMDSegmentTransform(const Segment:TKraftSegment;const Transform:TKraftMatrix4x4):TKraftSegment; overload;
10061 begin
10062 result.Points[0]:=Vector3TermMatrixMul(Segment.Points[0],Transform);
10063 result.Points[1]:=Vector3TermMatrixMul(Segment.Points[1],Transform);
10064 end;
10065
10066 procedure SIMDSegmentClosestPoints(const SegmentA,SegmentB:TKraftSegment;out TimeA:TKraftScalar;out ClosestPointA:TKraftVector3;out TimeB:TKraftScalar;out ClosestPointB:TKraftVector3);
10067 var dA,dB,r:TKraftVector3;
10068 a,b,c,{d,}e,f,Denominator,aA,aB,bA,bB:TKraftScalar;
10069 begin
10070 dA:=Vector3Sub(SegmentA.Points[1],SegmentA.Points[0]);
10071 dB:=Vector3Sub(SegmentB.Points[1],SegmentB.Points[0]);
10072 r:=Vector3Sub(SegmentA.Points[0],SegmentB.Points[0]);
10073 a:=Vector3LengthSquared(dA);
10074 e:=Vector3LengthSquared(dB);
10075 f:=Vector3Dot(dB,r);
10076 if (a<EPSILON) and (e<EPSILON) then begin
10077 // segment a and b are both points
10078 TimeA:=0.0;
10079 TimeB:=0.0;
10080 ClosestPointA:=SegmentA.Points[0];
10081 ClosestPointB:=SegmentB.Points[0];
10082 end else begin
10083 if a<EPSILON then begin
10084 // segment a is a point
10085 TimeA:=0.0;
10086 TimeB:=f/e;
10087 if TimeB<0.0 then begin
10088 TimeB:=0.0;
10089 end else if TimeB>1.0 then begin
10090 TimeB:=1.0;
10091 end;
10092 end else begin
10093 c:=Vector3Dot(dA,r);
10094 if e<EPSILON then begin
10095 // segment b is a point
10096 TimeA:=-(c/a);
10097 if TimeA<0.0 then begin
10098 TimeA:=0.0;
10099 end else if TimeA>1.0 then begin
10100 TimeA:=1.0;
10101 end;
10102 TimeB:=0.0;
10103 end else begin
10104 b:=Vector3Dot(dA,dB);
10105 Denominator:=(a*e)-sqr(b);
10106 if Denominator<EPSILON then begin
10107 // segments are parallel
10108 aA:=Vector3Dot(dB,SegmentA.Points[0]);
10109 aB:=Vector3Dot(dB,SegmentA.Points[1]);
10110 bA:=Vector3Dot(dB,SegmentB.Points[0]);
10111 bB:=Vector3Dot(dB,SegmentB.Points[1]);
10112 if (aA<=bA) and (aB<=bA) then begin
10113 // segment A is completely "before" segment B
10114 if aB>aA then begin
10115 TimeA:=1.0;
10116 end else begin
10117 TimeA:=0.0;
10118 end;
10119 TimeB:=0.0;
10120 end else if (aA>=bB) and (aB>=bB) then begin
10121 // segment B is completely "before" segment A
10122 if aB>aA then begin
10123 TimeA:=0.0;
10124 end else begin
10125 TimeA:=1.0;
10126 end;
10127 TimeB:=1.0;
10128 end else begin
10129 // segments A and B overlap, use midpoint of shared length
10130 if aA>aB then begin
10131 f:=aA;
10132 aA:=aB;
10133 aB:=f;
10134 end;
10135 f:=(Min(aB,bB)+Max(aA,bA))*0.5;
10136 TimeB:=(f-bA)/e;
10137 ClosestPointB:=Vector3Add(SegmentB.Points[0],Vector3ScalarMul(dB,TimeB));
10138 SIMDSegmentClosestPointTo(SegmentA,ClosestPointB,TimeB,ClosestPointA);
10139 exit;
10140 end;
10141 end else begin
10142 // general case
10143 TimeA:=((b*f)-(c*e))/Denominator;
10144 if TimeA<0.0 then begin
10145 TimeA:=0.0;
10146 end else if TimeA>1.0 then begin
10147 TimeA:=1.0;
10148 end;
10149 TimeB:=((b*TimeA)+f)/e;
10150 if TimeB<0.0 then begin
10151 TimeB:=0.0;
10152 TimeA:=-(c/a);
10153 if TimeA<0.0 then begin
10154 TimeA:=0.0;
10155 end else if TimeA>1.0 then begin
10156 TimeA:=1.0;
10157 end;
10158 end else if TimeB>1.0 then begin
10159 TimeB:=1.0;
10160 TimeA:=(b-c)/a;
10161 if TimeA<0.0 then begin
10162 TimeA:=0.0;
10163 end else if TimeA>1.0 then begin
10164 TimeA:=1.0;
10165 end;
10166 end;
10167 end;
10168 end;
10169 end;
10170 ClosestPointA:=Vector3Add(SegmentA.Points[0],Vector3ScalarMul(dA,TimeA));
10171 ClosestPointB:=Vector3Add(SegmentB.Points[0],Vector3ScalarMul(dB,TimeB));
10172 end;
10173 end;
10174
10175 function SIMDSegmentIntersect(const SegmentA,SegmentB:TKraftSegment;out TimeA,TimeB:TKraftScalar;out IntersectionPoint:TKraftVector3):boolean;
10176 var PointA:TKraftVector3;
10177 begin
10178 SIMDSegmentClosestPoints(SegmentA,SegmentB,TimeA,PointA,TimeB,IntersectionPoint);
10179 result:=Vector3DistSquared(PointA,IntersectionPoint)<EPSILON;
10180 end;
10181
10182 function SIMDTriangleContains(const Triangle:TKraftTriangle;const p:TKraftVector3):boolean;
10183 var vA,vB,vC:TKraftVector3;
10184 dAB,dAC,dBC:TKraftScalar;
10185 begin
10186 vA:=Vector3Sub(Triangle.Points[0],p);
10187 vB:=Vector3Sub(Triangle.Points[1],p);
10188 vC:=Vector3Sub(Triangle.Points[2],p);
10189 dAB:=Vector3Dot(vA,vB);
10190 dAC:=Vector3Dot(vA,vC);
10191 dBC:=Vector3Dot(vB,vC);
10192 if ((dBC*dAC)-(Vector3LengthSquared(vC)*dAB))<0.0 then begin
10193 result:=false;
10194 end else begin
10195 result:=((dAB*dBC)-(dAC*Vector3LengthSquared(vB)))>=0.0;
10196 end;
10197 end;
10198
10199 function SIMDTriangleIntersect(const Triangle:TKraftTriangle;const Segment:TKraftSegment;out Time:TKraftScalar;out IntersectionPoint:TKraftVector3):boolean;
10200 var Switched:boolean;
10201 d,t,v,w:TKraftScalar;
10202 vAB,vAC,pBA,vApA,e,n:TKraftVector3;
10203 s:TKraftSegment;
10204 begin
10205
10206 result:=false;
10207
10208 Time:=NaN;
10209
10210 IntersectionPoint:=Vector3Origin;
10211
10212 Switched:=false;
10213
10214 vAB:=Vector3Sub(Triangle.Points[1],Triangle.Points[0]);
10215 vAC:=Vector3Sub(Triangle.Points[2],Triangle.Points[0]);
10216
10217 pBA:=Vector3Sub(Segment.Points[0],Segment.Points[1]);
10218
10219 n:=Vector3Cross(vAB,vAC);
10220
10221 d:=Vector3Dot(n,pBA);
10222
10223 if abs(d)<EPSILON then begin
10224 exit; // segment is parallel
10225 end else if d<0.0 then begin
10226 s.Points[0]:=Segment.Points[1];
10227 s.Points[1]:=Segment.Points[0];
10228 Switched:=true;
10229 pBA:=Vector3Sub(s.Points[0],s.Points[1]);
10230 d:=-d;
10231 end else begin
10232 s:=Segment;
10233 end;
10234
10235 vApA:=Vector3Sub(s.Points[0],Triangle.Points[0]);
10236 t:=Vector3Dot(n,vApA);
10237 e:=Vector3Cross(pBA,vApA);
10238
10239 v:=Vector3Dot(vAC,e);
10240 if (v<0.0) or (v>d) then begin
10241 exit; // intersects outside triangle
10242 end;
10243
10244 w:=-Vector3Dot(vAB,e);
10245 if (w<0.0) or ((v+w)>d) then begin
10246 exit; // intersects outside triangle
10247 end;
10248
10249 d:=1.0/d;
10250 t:=t*d;
10251 v:=v*d;
10252 w:=w*d;
10253 Time:=t;
10254
10255 IntersectionPoint:=Vector3Add(Triangle.Points[0],Vector3Add(Vector3ScalarMul(vAB,v),Vector3ScalarMul(vAC,w)));
10256
10257 if Switched then begin
10258 Time:=1.0-Time;
10259 end;
10260
10261 result:=(Time>=0.0) and (Time<=1.0);
10262 end;
10263
10264 function SIMDTriangleClosestPointTo(const Triangle:TKraftTriangle;const Point:TKraftVector3;out ClosestPoint:TKraftVector3):boolean; overload;
10265 var u,v,w,d1,d2,d3,d4,d5,d6,Denominator:TKraftScalar;
10266 vAB,vAC,vAp,vBp,vCp:TKraftVector3;
10267 begin
10268 result:=false;
10269
10270 vAB:=Vector3Sub(Triangle.Points[1],Triangle.Points[0]);
10271 vAC:=Vector3Sub(Triangle.Points[2],Triangle.Points[0]);
10272 vAp:=Vector3Sub(Point,Triangle.Points[0]);
10273
10274 d1:=Vector3Dot(vAB,vAp);
10275 d2:=Vector3Dot(vAC,vAp);
10276 if (d1<=0.0) and (d2<=0.0) then begin
10277 ClosestPoint:=Triangle.Points[0]; // closest point is vertex A
10278 exit;
10279 end;
10280
10281 vBp:=Vector3Sub(Point,Triangle.Points[1]);
10282 d3:=Vector3Dot(vAB,vBp);
10283 d4:=Vector3Dot(vAC,vBp);
10284 if (d3>=0.0) and (d4<=d3) then begin
10285 ClosestPoint:=Triangle.Points[1]; // closest point is vertex B
10286 exit;
10287 end;
10288
10289 w:=(d1*d4)-(d3*d2);
10290 if (w<=0.0) and (d1>=0.0) and (d3<=0.0) then begin
10291 // closest point is along edge 1-2
10292 ClosestPoint:=Vector3Add(Triangle.Points[0],Vector3ScalarMul(vAB,d1/(d1-d3)));
10293 exit;
10294 end;
10295
10296 vCp:=Vector3Sub(Point,Triangle.Points[2]);
10297 d5:=Vector3Dot(vAB,vCp);
10298 d6:=Vector3Dot(vAC,vCp);
10299 if (d6>=0.0) and (d5<=d6) then begin
10300 ClosestPoint:=Triangle.Points[2]; // closest point is vertex C
10301 exit;
10302 end;
10303
10304 v:=(d5*d2)-(d1*d6);
10305 if (v<=0.0) and (d2>=0.0) and (d6<=0.0) then begin
10306 // closest point is along edge 1-3
10307 ClosestPoint:=Vector3Add(Triangle.Points[0],Vector3ScalarMul(vAC,d2/(d2-d6)));
10308 exit;
10309 end;
10310
10311 u:=(d3*d6)-(d5*d4);
10312 if (u<=0.0) and ((d4-d3)>=0.0) and ((d5-d6)>=0.0) then begin
10313 // closest point is along edge 2-3
10314 ClosestPoint:=Vector3Add(Triangle.Points[1],Vector3ScalarMul(Vector3Sub(Triangle.Points[2],Triangle.Points[1]),(d4-d3)/((d4-d3)+(d5-d6))));
10315 exit;
10316 end;
10317
10318 Denominator:=1.0/(u+v+w);
10319
10320 ClosestPoint:=Vector3Add(Triangle.Points[0],Vector3Add(Vector3ScalarMul(vAB,v*Denominator),Vector3ScalarMul(vAC,w*Denominator)));
10321
10322 result:=true;
10323 end;
10324
10325 function SIMDTriangleClosestPointTo(const Triangle:TKraftTriangle;const Segment:TKraftSegment;out Time:TKraftScalar;out ClosestPointOnSegment,ClosestPointOnTriangle:TKraftVector3):boolean; overload;
10326 var MinDist,dtri,d1,d2,sa,sb,dist:TKraftScalar;
10327 pAInside,pBInside:boolean;
10328 pa,pb:TKraftVector3;
10329 Edge:TKraftSegment;
10330 begin
10331
10332 result:=SIMDTriangleIntersect(Triangle,Segment,Time,ClosestPointOnTriangle);
10333
10334 if result then begin
10335
10336 // segment intersects triangle
10337 ClosestPointOnSegment:=ClosestPointOnTriangle;
10338
10339 end else begin
10340
10341 MinDist:=MAX_SCALAR;
10342
10343 ClosestPointOnSegment:=Vector3Origin;
10344
10345 dtri:=Vector3Dot(Triangle.Normal,Triangle.Points[0]);
10346
10347 pAInside:=SIMDTriangleContains(Triangle,Segment.Points[0]);
10348 pBInside:=SIMDTriangleContains(Triangle,Segment.Points[1]);
10349
10350 if pAInside and pBInside then begin
10351 // both points inside triangle
10352 d1:=Vector3Dot(Triangle.Normal,Segment.Points[0])-dtri;
10353 d2:=Vector3Dot(Triangle.Normal,Segment.Points[1])-dtri;
10354 if abs(d2-d1)<EPSILON then begin
10355 // segment is parallel to triangle
10356 ClosestPointOnSegment:=Vector3Avg(Segment.Points[0],Segment.Points[1]);
10357 MinDist:=d1;
10358 Time:=0.5;
10359 end else if abs(d1)<abs(d2) then begin
10360 ClosestPointOnSegment:=Segment.Points[0];
10361 MinDist:=d1;
10362 Time:=0.0;
10363 end else begin
10364 ClosestPointOnSegment:=Segment.Points[1];
10365 MinDist:=d2;
10366 Time:=1.0;
10367 end;
10368 ClosestPointOnTriangle:=Vector3Add(ClosestPointOnSegment,Vector3ScalarMul(Triangle.Normal,-MinDist));
10369 result:=true;
10370 exit;
10371 end else if pAInside then begin
10372 // one point is inside triangle
10373 ClosestPointOnSegment:=Segment.Points[0];
10374 Time:=0.0;
10375 MinDist:=Vector3Dot(Triangle.Normal,ClosestPointOnSegment)-dtri;
10376 ClosestPointOnTriangle:=Vector3Add(ClosestPointOnSegment,Vector3ScalarMul(Triangle.Normal,-MinDist));
10377 MinDist:=sqr(MinDist);
10378 end else if pBInside then begin
10379 // one point is inside triangle
10380 ClosestPointOnSegment:=Segment.Points[1];
10381 Time:=1.0;
10382 MinDist:=Vector3Dot(Triangle.Normal,ClosestPointOnSegment)-dtri;
10383 ClosestPointOnTriangle:=Vector3Add(ClosestPointOnSegment,Vector3ScalarMul(Triangle.Normal,-MinDist));
10384 MinDist:=sqr(MinDist);
10385 end;
10386
10387 // test edge 1
10388 Edge.Points[0]:=Triangle.Points[0];
10389 Edge.Points[1]:=Triangle.Points[1];
10390 SIMDSegmentClosestPoints(Segment,Edge,sa,pa,sb,pb);
10391 Dist:=Vector3DistSquared(pa,pb);
10392 if Dist<MinDist then begin
10393 MinDist:=Dist;
10394 Time:=sa;
10395 ClosestPointOnSegment:=pa;
10396 ClosestPointOnTriangle:=pb;
10397 end;
10398
10399 // test edge 2
10400 Edge.Points[0]:=Triangle.Points[1];
10401 Edge.Points[1]:=Triangle.Points[2];
10402 SIMDSegmentClosestPoints(Segment,Edge,sa,pa,sb,pb);
10403 Dist:=Vector3DistSquared(pa,pb);
10404 if Dist<MinDist then begin
10405 MinDist:=Dist;
10406 Time:=sa;
10407 ClosestPointOnSegment:=pa;
10408 ClosestPointOnTriangle:=pb;
10409 end;
10410
10411 // test edge 3
10412 Edge.Points[0]:=Triangle.Points[2];
10413 Edge.Points[1]:=Triangle.Points[0];
10414 SIMDSegmentClosestPoints(Segment,Edge,sa,pa,sb,pb);
10415 Dist:=Vector3DistSquared(pa,pb);
10416 if Dist<MinDist then begin
10417 // MinDist:=Dist;
10418 Time:=sa;
10419 ClosestPointOnSegment:=pa;
10420 ClosestPointOnTriangle:=pb;
10421 end;
10422
10423 end;
10424
10425 end;
10426
10427 function InertiaTensorTransform(const Inertia,Transform:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
10428 begin
10429 result:=Matrix3x3TermMulTranspose(Matrix3x3TermMul(Transform,Inertia),Transform);
10430 end;
10431
10432 function InertiaTensorParallelAxisTheorem(const Center:TKraftVector3;const Mass:TKraftScalar):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
10433 var CenterDotCenter:TKraftScalar;
10434 begin
10435 CenterDotCenter:=sqr(Center.x)+sqr(Center.y)+sqr(Center.z);
10436 result[0,0]:=((Matrix3x3Identity[0,0]*CenterDotCenter)-(Center.x*Center.x))*Mass;
10437 result[0,1]:=((Matrix3x3Identity[0,1]*CenterDotCenter)-(Center.y*Center.x))*Mass;
10438 result[0,2]:=((Matrix3x3Identity[0,2]*CenterDotCenter)-(Center.z*Center.x))*Mass;
10439 result[1,0]:=((Matrix3x3Identity[1,0]*CenterDotCenter)-(Center.x*Center.y))*Mass;
10440 result[1,1]:=((Matrix3x3Identity[1,1]*CenterDotCenter)-(Center.y*Center.y))*Mass;
10441 result[1,2]:=((Matrix3x3Identity[1,2]*CenterDotCenter)-(Center.z*Center.y))*Mass;
10442 result[2,0]:=((Matrix3x3Identity[2,0]*CenterDotCenter)-(Center.x*Center.z))*Mass;
10443 result[2,1]:=((Matrix3x3Identity[2,1]*CenterDotCenter)-(Center.y*Center.z))*Mass;
10444 result[2,2]:=((Matrix3x3Identity[2,2]*CenterDotCenter)-(Center.z*Center.z))*Mass;
10445 end;
10446
10447 constructor TKraftHighResolutionTimer.Create(FrameRate:longint=60);
10448 begin
10449 inherited Create;
10450 fFrequencyShift:=0;
10451 {$if defined(USE_CASTLE_TIME_UTILS)}
10452 // Copied from TimerFrequency constant in CastleTimeUtils
10453 fFrequency:= 1000000;
10454 {$elseif defined(windows)}
10455 if QueryPerformanceFrequency(fFrequency) then begin
10456 while (fFrequency and $ffffffffe0000000)<>0 do begin
10457 fFrequency:=fFrequency shr 1;
10458 inc(fFrequencyShift);
10459 end;
10460 end else begin
10461 fFrequency:=1000;
10462 end;
10463 {$elseif defined(linux) or defined(android)}
10464 fFrequency:=1000000000;
10465 {$elseif defined(unix)}
10466 fFrequency:=1000000;
10467 {$else}
10468 fFrequency:=1000;
10469 {$ifend}
10470 fFrameInterval:=(fFrequency+((abs(FrameRate)+1) shr 1)) div abs(FrameRate);
10471 fMillisecondInterval:=(fFrequency+500) div 1000;
10472 fTwoMillisecondsInterval:=(fFrequency+250) div 500;
10473 fFourMillisecondsInterval:=(fFrequency+125) div 250;
10474 fQuarterSecondInterval:=(fFrequency+2) div 4;
10475 fHourInterval:=fFrequency*3600;
10476 end;
10477
10478 destructor TKraftHighResolutionTimer.Destroy;
10479 begin
10480 inherited Destroy;
10481 end;
10482
10483 procedure TKraftHighResolutionTimer.SetFrameRate(FrameRate:longint);
10484 begin
10485 fFrameInterval:=(fFrequency+((abs(FrameRate)+1) shr 1)) div abs(FrameRate);
10486 end;
10487
10488 function TKraftHighResolutionTimer.GetTime:int64;
10489 {$if defined(USE_CASTLE_TIME_UTILS)}
10490 // nothing needed to be declared
10491 {$elseif defined(linux) or defined(android)}
10492 var NowTimeSpec:TimeSpec;
10493 ia,ib:int64;
10494 {$elseif defined(unix)}
10495 var tv:timeval;
10496 tz:timezone;
10497 ia,ib:int64;
10498 {$ifend}
10499 begin
10500 {$if defined(USE_CASTLE_TIME_UTILS)}
10501 result:=Timer.InternalValue;
10502 {$elseif defined(windows)}
10503 if not QueryPerformanceCounter(result) then begin
10504 result:=timeGetTime;
10505 end;
10506 {$elseif defined(linux) or defined(android)}
10507 clock_gettime(CLOCK_MONOTONIC,@NowTimeSpec);
10508 ia:=int64(NowTimeSpec.tv_sec)*int64(1000000000);
10509 ib:=NowTimeSpec.tv_nsec;
10510 result:=ia+ib;
10511 {$elseif defined(unix)}
10512 tz.tz_minuteswest:=0;
10513 tz.tz_dsttime:=0;
10514 fpgettimeofday(@tv,@tz);
10515 ia:=int64(tv.tv_sec)*int64(1000000);
10516 ib:=tv.tv_usec;
10517 result:=ia+ib;
10518 {$else}
10519 result:=SDL_GetTicks;
10520 {$ifend}
10521 result:=result shr fFrequencyShift;
10522 end;
10523
10524 function TKraftHighResolutionTimer.GetEventTime:int64;
10525 begin
10526 result:=ToNanoseconds(GetTime);
10527 end;
10528
10529 procedure TKraftHighResolutionTimer.Sleep(Delay:int64);
10530 var EndTime,NowTime{$ifdef unix},SleepTime{$endif}:int64;
10531 {$ifdef unix}
10532 req,rem:timespec;
10533 {$endif}
10534 begin
10535 if Delay>0 then begin
10536 {$if defined(USE_CASTLE_TIME_UTILS)}
10537 { We don't have in CGE own Sleep, we found that SysUtils.Sleep
10538 works OK everywhere. }
10539 SysUtils.Sleep(Delay);
10540 {$elseif defined(windows)}
10541 NowTime:=GetTime;
10542 EndTime:=NowTime+Delay;
10543 while (NowTime+fTwoMillisecondsInterval)<EndTime do begin
10544 Sleep(1);
10545 NowTime:=GetTime;
10546 end;
10547 while (NowTime+fMillisecondInterval)<EndTime do begin
10548 Sleep(0);
10549 NowTime:=GetTime;
10550 end;
10551 while NowTime<EndTime do begin
10552 NowTime:=GetTime;
10553 end;
10554 {$elseif defined(linux) or defined(android)}
10555 NowTime:=GetTime;
10556 EndTime:=NowTime+Delay;
10557 while (NowTime+fFourMillisecondsInterval)<EndTime do begin
10558 SleepTime:=((EndTime-NowTime)+2) shr 2;
10559 if SleepTime>0 then begin
10560 req.tv_sec:=SleepTime div 1000000000;
10561 req.tv_nsec:=SleepTime mod 10000000000;
10562 fpNanoSleep(@req,@rem);
10563 NowTime:=GetTime;
10564 continue;
10565 end;
10566 break;
10567 end;
10568 while (NowTime+fTwoMillisecondsInterval)<EndTime do begin
10569 ThreadSwitch;
10570 NowTime:=GetTime;
10571 end;
10572 while NowTime<EndTime do begin
10573 NowTime:=GetTime;
10574 end;
10575 {$elseif defined(unix)}
10576 NowTime:=GetTime;
10577 EndTime:=NowTime+Delay;
10578 while (NowTime+fFourMillisecondsInterval)<EndTime do begin
10579 SleepTime:=((EndTime-NowTime)+2) shr 2;
10580 if SleepTime>0 then begin
10581 req.tv_sec:=SleepTime div 1000000;
10582 req.tv_nsec:=(SleepTime mod 1000000)*1000;
10583 fpNanoSleep(@req,@rem);
10584 NowTime:=GetTime;
10585 continue;
10586 end;
10587 break;
10588 end;
10589 while (NowTime+fTwoMillisecondsInterval)<EndTime do begin
10590 ThreadSwitch;
10591 NowTime:=GetTime;
10592 end;
10593 while NowTime<EndTime do begin
10594 NowTime:=GetTime;
10595 end;
10596 {$else}
10597 NowTime:=GetTime;
10598 EndTime:=NowTime+Delay;
10599 while (NowTime+4)<EndTime then begin
10600 SDL_Delay(1);
10601 NowTime:=GetTime;
10602 end;
10603 while (NowTime+2)<EndTime do begin
10604 SDL_Delay(0);
10605 NowTime:=GetTime;
10606 end;
10607 while NowTime<EndTime do begin
10608 NowTime:=GetTime;
10609 end;
10610 {$ifend}
10611 end;
10612 end;
10613
10614 function TKraftHighResolutionTimer.ToFixedPointSeconds(Time:int64):int64;
10615 var a,b:TUInt128;
10616 begin
10617 if fFrequency<>0 then begin
10618 if ((fFrequency or Time) and int64($ffffffff00000000))=0 then begin
10619 result:=int64(qword(qword(Time)*qword($100000000)) div qword(fFrequency));
10620 end else begin
10621 UInt128Mul64(a,Time,qword($100000000));
10622 UInt128Div64(b,a,fFrequency);
10623 result:=b.Lo;
10624 end;
10625 end else begin
10626 result:=0;
10627 end;
10628 end;
10629
10630 function TKraftHighResolutionTimer.ToFixedPointFrames(Time:int64):int64;
10631 var a,b:TUInt128;
10632 begin
10633 if fFrameInterval<>0 then begin
10634 if ((fFrameInterval or Time) and int64($ffffffff00000000))=0 then begin
10635 result:=int64(qword(qword(Time)*qword($100000000)) div qword(fFrameInterval));
10636 end else begin
10637 UInt128Mul64(a,Time,qword($100000000));
10638 UInt128Div64(b,a,fFrameInterval);
10639 result:=b.Lo;
10640 end;
10641 end else begin
10642 result:=0;
10643 end;
10644 end;
10645
10646 function TKraftHighResolutionTimer.ToFloatSeconds(Time:int64):double;
10647 begin
10648 if fFrequency<>0 then begin
10649 result:=Time/fFrequency;
10650 end else begin
10651 result:=0;
10652 end;
10653 end;
10654
10655 function TKraftHighResolutionTimer.FromFloatSeconds(Time:double):int64;
10656 begin
10657 if fFrequency<>0 then begin
10658 result:=trunc(Time*fFrequency);
10659 end else begin
10660 result:=0;
10661 end;
10662 end;
10663
10664 function TKraftHighResolutionTimer.ToMilliseconds(Time:int64):int64;
10665 begin
10666 result:=Time;
10667 if fFrequency<>1000 then begin
10668 result:=((Time*1000)+((fFrequency+1) shr 1)) div fFrequency;
10669 end;
10670 end;
10671
10672 function TKraftHighResolutionTimer.FromMilliseconds(Time:int64):int64;
10673 begin
10674 result:=Time;
10675 if fFrequency<>1000 then begin
10676 result:=((Time*fFrequency)+500) div 1000;
10677 end;
10678 end;
10679
10680 function TKraftHighResolutionTimer.ToMicroseconds(Time:int64):int64;
10681 begin
10682 result:=Time;
10683 if fFrequency<>1000000 then begin
10684 result:=((Time*1000000)+((fFrequency+1) shr 1)) div fFrequency;
10685 end;
10686 end;
10687
10688 function TKraftHighResolutionTimer.FromMicroseconds(Time:int64):int64;
10689 begin
10690 result:=Time;
10691 if fFrequency<>1000000 then begin
10692 result:=((Time*fFrequency)+500000) div 1000000;
10693 end;
10694 end;
10695
10696 function TKraftHighResolutionTimer.ToNanoseconds(Time:int64):int64;
10697 begin
10698 result:=Time;
10699 if fFrequency<>1000000000 then begin
10700 result:=((Time*1000000000)+((fFrequency+1) shr 1)) div fFrequency;
10701 end;
10702 end;
10703
10704 function TKraftHighResolutionTimer.FromNanoseconds(Time:int64):int64;
10705 begin
10706 result:=Time;
10707 if fFrequency<>1000000000 then begin
10708 result:=((Time*fFrequency)+500000000) div 1000000000;
10709 end;
10710 end;
10711
10712 function CalculateArea(const v0,v1,v2:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
10713 begin
10714 result:=Vector3LengthSquared(Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v2,v0)));
10715 end;
10716
10717 function CalculateVolume(const v0,v1,v2,v3:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
10718 var a,b,c:TKraftVector3;
10719 begin
10720 a:=Vector3Sub(v0,v3);
10721 b:=Vector3Sub(v1,v3);
10722 c:=Vector3Sub(v2,v3);
10723 result:=(a.x*((b.z*c.y)-(b.y*c.z)))+(a.y*((b.x*c.z)-(b.z*c.x)))+(a.z*((b.y*c.x)-(b.x*c.y)));
10724 end;
10725
10726 type TKraftShapeTriangle=class(TKraftShapeConvexHull)
10727 private
10728 fShapeConvexHull:TKraftConvexHull;
10729 procedure UpdateData;
10730 public
10731 constructor Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AVertex0,AVertex1,AVertex2:TKraftVector3); reintroduce;
10732 destructor Destroy; override;
10733 procedure UpdateShapeAABB; override;
10734 procedure CalculateMassData; override;
10735 function GetSignedDistance(const Position:TKraftVector3):TKraftScalar; override;
10736 function GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3; override;
10737 function GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3; override;
10738 function GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint; override;
10739 function GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3; override;
10740 function TestPoint(const p:TKraftVector3):boolean; override;
10741 function RayCast(var RayCastData:TKraftRaycastData):boolean; override;
10742 {$ifdef DebugDraw}
10743 procedure Draw(const CameraMatrix:TKraftMatrix4x4); override;
10744 {$endif}
10745 end;
10746
10747 function IsSameValue(const a,b:TKraftScalar):boolean;
10748 const FuzzFactor=1000.0;
10749 Resolution={$ifdef UseDouble}1e-15{$else}1e-7{$endif}*FuzzFactor;
10750 var EpsilonTolerance:double;
10751 begin
10752 EpsilonTolerance:=abs(a);
10753 if EpsilonTolerance>abs(b) then begin
10754 EpsilonTolerance:=abs(b);
10755 end;
10756 EpsilonTolerance:=EpsilonTolerance*Resolution;
10757 if EpsilonTolerance<Resolution then begin
10758 EpsilonTolerance:=Resolution;
10759 end;
10760 if a>b then begin
10761 result:=(a-b)<=EpsilonTolerance;
10762 end else begin
10763 result:=(b-a)<=EpsilonTolerance;
10764 end;
10765 end;
10766
10767 {$ifdef cpu386}
10768 {$ifndef ver130}
10769 function InterlockedCompareExchange64Ex(Target,NewValue,Comperand:pointer):boolean; assembler; register;
10770 asm
10771 push ebx
10772 push edi
10773 push esi
10774 mov edi,eax
10775 mov esi,edx
10776 mov edx,dword ptr [ecx+4]
10777 mov eax,dword ptr [ecx+0]
10778 mov ecx,dword ptr [esi+4]
10779 mov ebx,dword ptr [esi+0]
10780 lock cmpxchg8b [edi]
10781 setz al
10782 pop esi
10783 pop edi
10784 pop ebx
10785 end;
10786
10787 function InterlockedCompareExchange64(var Target:int64;NewValue:int64;Comperand:int64):int64; assembler; register;
10788 asm
10789 push ebx
10790 push edi
10791 mov edi,eax
10792 mov edx,dword ptr [Comperand+4]
10793 mov eax,dword ptr [Comperand+0]
10794 mov ecx,dword ptr [NewValue+4]
10795 mov ebx,dword ptr [NewValue+0]
10796 lock cmpxchg8b [edi]
10797 pop edi
10798 pop ebx
10799 end;
10800 {$endif}
10801 {$endif}
10802
10803 {$ifndef fpc}
10804 {$ifdef cpu386}
10805 function InterlockedDecrement(var Target:longint):longint; assembler; register;
10806 asm
10807 mov edx,$ffffffff
10808 xchg eax,edx
10809 lock xadd dword ptr [edx],eax
10810 dec eax
10811 end;
10812
10813 function InterlockedIncrement(var Target:longint):longint; assembler; register;
10814 asm
10815 mov edx,1
10816 xchg eax,edx
10817 lock xadd dword ptr [edx],eax
10818 inc eax
10819 end;
10820
10821 function InterlockedExchange(var Target:longint;Source:longint):longint; assembler; register;
10822 asm
10823 lock xchg dword ptr [eax],edx
10824 mov eax,edx
10825 end;
10826
10827 function InterlockedExchangeAdd(var Target:longint;Source:longint):longint; assembler; register;
10828 asm
10829 xchg edx,eax
10830 lock xadd dword ptr [edx],eax
10831 end;
10832
10833 function InterlockedCompareExchange(var Target:longint;NewValue,Comperand:longint):longint; assembler; register;
10834 asm
10835 xchg ecx,eax
10836 lock cmpxchg dword ptr [ecx],edx
10837 end;
10838 {$else}
10839 function InterlockedDecrement(var Target:longint):longint; {$ifdef caninline}inline;{$endif}
10840 begin
10841 result:=
10842 {$if (not defined(FPC)) and (not defined(MSWINDOWS))}
10843 AtomicDecrement
10844 {$else}
10845 Windows.InterlockedDecrement
10846 {$ifend}
10847 (Target);
10848 end;
10849
10850 function InterlockedIncrement(var Target:longint):longint; {$ifdef caninline}inline;{$endif}
10851 begin
10852 result:=
10853 {$if (not defined(FPC)) and (not defined(MSWINDOWS))}
10854 AtomicIncrement
10855 {$else}
10856 Windows.InterlockedIncrement
10857 {$ifend}
10858 (Target);
10859 end;
10860
10861 function InterlockedExchange(var Target:longint;Source:longint):longint; {$ifdef caninline}inline;{$endif}
10862 begin
10863 result:=
10864 {$if (not defined(FPC)) and (not defined(MSWINDOWS))}
10865 AtomicExchange
10866 {$else}
10867 Windows.InterlockedExchange
10868 {$ifend}
10869 (Target,Source);
10870 end;
10871
10872 {$if (not defined(FPC)) and (not defined(MSWINDOWS))}
10873 // No implementation of InterlockedExchangeAdd or InterlockedCompareExchange,
10874 // ... but actually nothing in Kraft uses this.
10875 {$else}
10876 function InterlockedExchangeAdd(var Target:longint;Source:longint):longint; {$ifdef caninline}inline;{$endif}
10877 begin
10878 result:=Windows.InterlockedExchangeAdd(Target,Source);
10879 end;
10880
10881 function InterlockedCompareExchange(var Target:longint;NewValue,Comperand:longint):longint; {$ifdef caninline}inline;{$endif}
10882 begin
10883 result:=Windows.InterlockedCompareExchange(Target,NewValue,Comperand);
10884 end;
10885 {$ifend}
10886
10887 {$endif}
10888 {$else}
10889 function InterlockedDecrement(var Target:longint):longint; {$ifdef caninline}inline;{$endif}
10890 begin
10891 result:=System.InterlockedDecrement(Target);
10892 end;
10893
10894 function InterlockedIncrement(var Target:longint):longint; {$ifdef caninline}inline;{$endif}
10895 begin
10896 result:=System.InterlockedIncrement(Target);
10897 end;
10898
10899 function InterlockedExchange(var Target:longint;Source:longint):longint; {$ifdef caninline}inline;{$endif}
10900 begin
10901 result:=System.InterlockedExchange(Target,Source);
10902 end;
10903
10904 function InterlockedExchangeAdd(var Target:longint;Source:longint):longint; {$ifdef caninline}inline;{$endif}
10905 begin
10906 result:=System.InterlockedExchangeAdd(Target,Source);
10907 end;
10908
10909 function InterlockedCompareExchange(var Target:longint;NewValue,Comperand:longint):longint; {$ifdef caninline}inline;{$endif}
10910 begin
10911 result:=System.InterlockedCompareExchange(Target,NewValue,Comperand);
10912 end;
10913 {$endif}
10914
10915 function HashPointer(p:pointer):longword; {$ifdef caninline}inline;{$endif}
10916 (*{$ifdef cpu64}
10917 var r:qword;
10918 begin
10919 r:=ptruint(p);
10920 r:=r xor (r shr 33);
10921 r:=r*qword($ff51afd7ed558ccd);
10922 r:=r xor (r shr 33);
10923 r:=r*qword($c4ceb9fe1a85ec53);
10924 result:=longword(ptruint(r xor (r shr 33)));
10925 end;
10926 {$else}
10927 begin
10928 result:=ptruint(p);
10929 result:=result xor (result shr 16);
10930 result:=result*$85ebca6b;
10931 result:=result xor (result shr 13);
10932 result:=result*$c2b2ae35;
10933 result:=result xor (result shr 16);
10934 end;
10935 {$endif}(**)
10936 {$ifdef cpu64}
10937 var r:ptruint;
10938 begin
10939 r:=ptruint(p);
10940 r:=(not r)+(r shl 18); // r:=((r shl 18)-r-)1;
10941 r:=r xor (r shr 31);
10942 r:=r*21; // r:=(r+(r shl 2))+(r shl 4);
10943 r:=r xor (r shr 11);
10944 r:=r+(r shl 6);
10945 result:=longword(ptruint(r xor (r shr 22)));
10946 end;
10947 {$else}
10948 begin
10949 result:=ptruint(p);
10950 result:=(not result)+(result shl 15);
10951 result:=result xor (result shr 15);
10952 inc(result,result shl 2);
10953 result:=(result xor (result shr 4))*2057;
10954 result:=result xor (result shr 16);
10955 end;
10956 {$endif}
10957
10958 function HashTwoLongWords(a,b:longword):longword; {$ifdef caninline}inline;{$endif}
10959 var r:qword;
10960 begin
10961 r:=(qword(a) shl 32) or b;
10962 r:=(not r)+(r shl 18); // r:=((r shl 18)-r-)1;
10963 r:=r xor (r shr 31);
10964 {$ifdef cpu64}
10965 r:=r*21;
10966 {$else}
10967 r:=(r+(r shl 2))+(r shl 4);
10968 {$endif}
10969 r:=r xor (r shr 11);
10970 r:=r+(r shl 6);
10971 result:=longword(ptruint(r xor (r shr 22)));
10972 end;
10973
10974 function HashTwoPointers(a,b:pointer):longword; {$ifdef caninline}inline;{$endif}
10975 begin
10976 result:=HashTwoLongWords(HashPointer(a),HashPointer(b));
10977 end;
10978
10979 function HashTwoPointersAndOneLongWord(a,b:pointer;c:longword):longword; {$ifdef caninline}inline;{$endif}
10980 begin
10981 result:=HashTwoLongWords(HashTwoLongWords(HashPointer(a),HashPointer(b)),c);
10982 end;
10983
10984 function AABBStretch(const AABB:TKraftAABB;const Displacement,BoundsExpansion:TKraftVector3):TKraftAABB; {$ifdef caninline}inline;{$endif}
10985 var d:TKraftVector3;
10986 begin
10987 d:=Vector3Add(AABBExtensionVector,BoundsExpansion);
10988 result.Min:=Vector3Sub(AABB.Min,d);
10989 result.Max:=Vector3Add(AABB.Max,d);
10990 d:=Vector3ScalarMul(Displacement,AABB_MULTIPLIER);
10991 if d.x<0.0 then begin
10992 result.Min.x:=result.Min.x+d.x;
10993 end else if d.x>0.0 then begin
10994 result.Max.x:=result.Max.x+d.x;
10995 end;
10996 if d.y<0.0 then begin
10997 result.Min.y:=result.Min.y+d.y;
10998 end else if d.y>0.0 then begin
10999 result.Max.y:=result.Max.y+d.y;
11000 end;
11001 if d.z<0.0 then begin
11002 result.Min.z:=result.Min.z+d.z;
11003 end else if d.z>0.0 then begin
11004 result.Max.z:=result.Max.z+d.z;
11005 end;
11006 end;
11007
11008 function CompareFloat(const a,b:pointer):longint;
11009 begin
11010 if TKraftScalar(a^)<TKraftScalar(b^) then begin
11011 result:=1;
11012 end else if TKraftScalar(a^)>TKraftScalar(b^) then begin
11013 result:=-1;
11014 end else begin
11015 result:=0;
11016 end;
11017 end;
11018
11019 function SweepTransform(const Sweep:TKraftSweep;const Beta:TKraftScalar):TKraftMatrix4x4; {$ifdef caninline}inline;{$endif}
11020 begin
11021 result:=QuaternionToMatrix4x4(QuaternionSlerp(Sweep.q0,Sweep.q,Beta));
11022 PKraftVector3(pointer(@result[3,0]))^:=Vector3Sub(Vector3Lerp(Sweep.c0,Sweep.c,Beta),Vector3TermMatrixMulBasis(Sweep.LocalCenter,result));
11023 end;
11024
11025 function SweepTermAdvance(const Sweep:TKraftSweep;const Alpha:TKraftScalar):TKraftSweep; {$ifdef caninline}inline;{$endif}
11026 var Beta:TKraftScalar;
11027 begin
11028 Assert(Sweep.Alpha0<1.0);
11029 Beta:=(Alpha-Sweep.Alpha0)/(1.0-Sweep.Alpha0);
11030 result.LocalCenter:=Sweep.LocalCenter;
11031 result.c0:=Vector3Lerp(Sweep.c0,Sweep.c,Beta);
11032 result.c:=Sweep.c;
11033 result.q0:=QuaternionSlerp(Sweep.q0,Sweep.q,Beta);
11034 result.q:=Sweep.q;
11035 result.Alpha0:=Alpha;
11036 end;
11037
11038 procedure SweepAdvance(var Sweep:TKraftSweep;const Alpha:TKraftScalar);
11039 var Beta:TKraftScalar;
11040 begin
11041 Beta:=(Alpha-Sweep.Alpha0)/(1.0-Sweep.Alpha0);
11042 Sweep.c0:=Vector3Lerp(Sweep.c0,Sweep.c,Beta);
11043 Sweep.q0:=QuaternionSlerp(Sweep.q0,Sweep.q,Beta);
11044 Sweep.Alpha0:=Alpha;
11045 end;
11046
11047 function SweepTermNormalize(const Sweep:TKraftSweep):TKraftSweep; {$ifdef caninline}inline;{$endif}
11048 begin
11049 result.LocalCenter:=Sweep.LocalCenter;
11050 result.c0:=Sweep.c0;
11051 result.c:=Sweep.c;
11052 result.q0:=QuaternionTermNormalize(Sweep.q0);
11053 result.q:=QuaternionTermNormalize(Sweep.q);
11054 result.Alpha0:=Sweep.Alpha0;
11055 end;
11056
11057 procedure SweepNormalize(var Sweep:TKraftSweep); {$ifdef caninline}inline;{$endif}
11058 begin
11059 QuaternionNormalize(Sweep.q0);
11060 QuaternionNormalize(Sweep.q);
11061 end;
11062
11063 procedure ClipFace(const InVertices,OutVertices:TKraftClipVertexList;const Plane:TKraftPlane;const ReferenceEdgeIndexOffset,ReferenceFaceIndex:longint);
11064 var Index,CountVertices:longint;
11065 PreviousClipVertexDistance,CurrentClipVertexDistance:TKraftScalar;
11066 PreviousClipVertex,CurrentClipVertex:PKraftClipVertex;
11067 FeatureID:TKraftContactFeatureID;
11068 begin
11069 CountVertices:=InVertices.fCount;
11070 if CountVertices>=2 then begin
11071 PreviousClipVertex:[email protected][InVertices.fCount-1];
11072 CurrentClipVertex:[email protected][0];
11073 PreviousClipVertexDistance:=PlaneVectorDistance(Plane,PreviousClipVertex^.Position);
11074 for Index:=0 to CountVertices-1 do begin
11075 CurrentClipVertex:[email protected][Index];
11076 CurrentClipVertexDistance:=PlaneVectorDistance(Plane,CurrentClipVertex^.Position);
11077 if PreviousClipVertexDistance<=0.0 then begin
11078 if CurrentClipVertexDistance<=0.0 then begin
11079 // Both vertices are behind the plane => keep CurrentClipVertex
11080 OutVertices.Add(CurrentClipVertex^);
11081 end else begin
11082 // PreviousClipVertex is behind the plane, CurrentClipVertex is in front => intersection point
11083 FeatureID.ElementA:=CurrentClipVertex^.FeatureID.ElementA;
11084 FeatureID.ElementB:=ReferenceEdgeIndexOffset+Index;
11085 OutVertices.Add(Vector3Lerp(PreviousClipVertex^.Position,CurrentClipVertex^.Position,PreviousClipVertexDistance/(PreviousClipVertexDistance-CurrentClipVertexDistance)),FeatureID);
11086 end;
11087 end else if CurrentClipVertexDistance<=0.0 then begin
11088 // CurrentClipVertex is behind the plane, PreviousClipVertex is in front => intersection point
11089 FeatureID.ElementA:=ReferenceEdgeIndexOffset+Index;
11090 FeatureID.ElementB:=CurrentClipVertex^.FeatureID.ElementA;
11091 OutVertices.Add(Vector3Lerp(PreviousClipVertex^.Position,CurrentClipVertex^.Position,PreviousClipVertexDistance/(PreviousClipVertexDistance-CurrentClipVertexDistance)),FeatureID);
11092 OutVertices.Add(CurrentClipVertex^);
11093 end;
11094 PreviousClipVertex:=CurrentClipVertex;
11095 PreviousClipVertexDistance:=CurrentClipVertexDistance;
11096 end;
11097 end;
11098 end;
11099
11100 function GetSkewSymmetricMatrixPlus(const v:TKraftVector3):TKraftMatrix3x3; overload; {$ifdef caninline}inline;{$endif}
11101 begin
11102 result[0,0]:=0.0;
11103 result[0,1]:=-v.z;
11104 result[0,2]:=v.y;
11105 {$ifdef SIMD}
11106 result[0,3]:=0.0;
11107 {$endif}
11108 result[1,0]:=v.z;
11109 result[1,1]:=0.0;
11110 result[1,2]:=-v.x;
11111 {$ifdef SIMD}
11112 result[1,3]:=0.0;
11113 {$endif}
11114 result[2,0]:=-v.y;
11115 result[2,1]:=v.x;
11116 result[2,2]:=0.0;
11117 {$ifdef SIMD}
11118 result[2,3]:=0.0;
11119 {$endif}
11120 end;
11121
11122 function GetSkewSymmetricMatrixMinus(const v:TKraftVector3):TKraftMatrix3x3; overload; {$ifdef caninline}inline;{$endif}
11123 begin
11124 result[0,0]:=0.0;
11125 result[0,1]:=v.z;
11126 result[0,2]:=-v.y;
11127 {$ifdef SIMD}
11128 result[0,3]:=0.0;
11129 {$endif}
11130 result[1,0]:=-v.z;
11131 result[1,1]:=0.0;
11132 result[1,2]:=v.x;
11133 {$ifdef SIMD}
11134 result[1,3]:=0.0;
11135 {$endif}
11136 result[2,0]:=v.y;
11137 result[2,1]:=-v.x;
11138 result[2,2]:=0.0;
11139 {$ifdef SIMD}
11140 result[2,3]:=0.0;
11141 {$endif}
11142 end;
11143
11144 function EvaluateEulerEquation(const w1,w0,T:TKraftVector3;const dt:TKraftScalar;const I:TKraftMatrix3x3):TKraftVector3; {$ifdef caninline}inline;{$endif}
11145 var w1xI:TKraftVector3;
11146 begin
11147 w1xI:=Vector3TermMatrixMul(w1,I);
11148 result:=Vector3Sub(Vector3Add(w1xI,Vector3ScalarMul(Vector3Cross(w1,w1xI),dt)),Vector3Add(Vector3ScalarMul(T,dt),Vector3TermMatrixMul(w0,I)));
11149 end;
11150
11151 function EvaluateEulerEquationDerivation(const w1,w0:TKraftVector3;const dt:TKraftScalar;const I:TKraftMatrix3x3):TKraftMatrix3x3; {$ifdef caninline}inline;{$endif}
11152 var w1x,Iw1x:TKraftMatrix3x3;
11153 begin
11154 w1x:=GetSkewSymmetricMatrixMinus(w1);
11155 Iw1x:=GetSkewSymmetricMatrixMinus(Vector3TermMatrixMul(w1,I));
11156 result:=Matrix3x3TermAdd(I,Matrix3x3TermScalarMul(Matrix3x3TermSub(Matrix3x3TermMul(w1x,I),Iw1x),dt));
11157 end;
11158
11159 constructor TKraftClipVertexList.Create;
11160 begin
11161 inherited Create;
11162 fVertices:=nil;
11163 fCapacity:=0;
11164 fCount:=0;
11165 fColor.r:=1.0;
11166 fColor.b:=1.0;
11167 fColor.g:=1.0;
11168 fColor.a:=1.0;
11169 end;
11170
11171 destructor TKraftClipVertexList.Destroy;
11172 begin
11173 SetLength(fVertices,0);
11174 end;
11175
11176 procedure TKraftClipVertexList.Clear;
11177 begin
11178 fCount:=0;
11179 end;
11180
11181 procedure TKraftClipVertexList.Add(const v:TKraftVector3;const fp:TKraftContactFeatureID);
11182 var i:longint;
11183 begin
11184 i:=fCount;
11185 inc(fCount);
11186 if fCount>fCapacity then begin
11187 fCapacity:=fCount*2;
11188 SetLength(fVertices,fCapacity);
11189 end;
11190 fVertices[i].Position:=v;
11191 fVertices[i].FeatureID:=fp;
11192 end;
11193
11194 procedure TKraftClipVertexList.Add(const v:TKraftClipVertex);
11195 var i:longint;
11196 begin
11197 i:=fCount;
11198 inc(fCount);
11199 if fCount>fCapacity then begin
11200 fCapacity:=fCount*2;
11201 SetLength(fVertices,fCapacity);
11202 end;
11203 fVertices[i]:=v;
11204 end;
11205
11206 procedure GetPlaneSpace(const n:TKraftVector3;out p,q:TKraftVector3); {$ifdef caninline}inline;{$endif}
11207 var a,k:TKraftScalar;
11208 begin
11209 if abs(n.z)>0.70710678 then begin
11210 a:=sqr(n.y)+sqr(n.z);
11211 k:=1.0/sqrt(a);
11212 p.x:=0.0;
11213 p.y:=-(n.z*k);
11214 p.z:=n.y*k;
11215 q.x:=a*k;
11216 q.y:=-(n.x*p.z);
11217 q.z:=n.x*p.y;
11218 end else begin
11219 a:=sqr(n.x)+sqr(n.y);
11220 k:=1.0/sqrt(a);
11221 p.x:=-(n.y*k);
11222 p.y:=n.x*k;
11223 p.z:=0.0;
11224 q.x:=-(n.z*p.y);
11225 q.y:=n.z*p.x;
11226 q.z:=a*k;
11227 end;
11228 end;
11229
11230 procedure ComputeBasis(var a:TKraftVector3;out b,c:TKraftVector3); overload; {$ifdef caninline}inline;{$endif}
11231 begin
11232 // Suppose vector a has all equal components and is a unit vector: a = (s, s, s)
11233 // Then 3*s*s = 1, s = sqrt(1/3) = 0.57735027. This means that at least one component of a
11234 // unit vector must be greater or equal to 0.57735027. Can use SIMD select operation.
11235 if abs(a.x)>=0.57735027 then begin
11236 b.x:=a.y;
11237 b.y:=-a.x;
11238 b.z:=0.0;
11239 end else begin
11240 b.x:=0.0;
11241 b.y:=a.z;
11242 b.z:=-a.y;
11243 end;
11244 Vector3NormalizeEx(a);
11245 Vector3NormalizeEx(b);
11246 c:=Vector3NormEx(Vector3Cross(a,b));
11247 end;
11248
11249 procedure ComputeBasis(const Normal:TKraftVector3;out Matrix:TKraftMatrix3x3;const IndexA:longint=0;const IndexB:longint=1;const IndexC:longint=2); overload; {$ifdef caninline}inline;{$endif}
11250 var a,b,c:TKraftVector3;
11251 begin
11252 a:=Normal;
11253 ComputeBasis(a,b,c);
11254 Matrix[IndexA,0]:=a.x;
11255 Matrix[IndexA,1]:=a.y;
11256 Matrix[IndexA,2]:=a.z;
11257 {$ifdef SIMD}
11258 Matrix[IndexA,3]:=0.0;
11259 {$endif}
11260 Matrix[IndexB,0]:=b.x;
11261 Matrix[IndexB,1]:=b.y;
11262 Matrix[IndexB,2]:=b.z;
11263 {$ifdef SIMD}
11264 Matrix[IndexB,3]:=0.0;
11265 {$endif}
11266 Matrix[IndexC,0]:=c.x;
11267 Matrix[IndexC,1]:=c.y;
11268 Matrix[IndexC,2]:=c.z;
11269 {$ifdef SIMD}
11270 Matrix[IndexC,3]:=0.0;
11271 {$endif}
11272 end;
11273
11274 function RayCastSphere(const RayOrigin,RayDirection,SpherePosition:TKraftVector3;const Radius,MaxTime:TKraftScalar;var HitTime:TKraftScalar):boolean; overload; {$ifdef caninline}inline;{$endif}
11275 var Origin,Direction,m:TKraftVector3;
11276 b,c,d,t:TKraftScalar;
11277 begin
11278 result:=false;
11279 Origin:=RayOrigin;
11280 Direction:=RayDirection;
11281 m:=Vector3Sub(Origin,SpherePosition);
11282 b:=Vector3Dot(m,Direction);
11283 c:=Vector3LengthSquared(m)-sqr(Radius);
11284 if (c<=0.0) or (b<=0.0) then begin
11285 d:=sqr(b)-c;
11286 if d>=EPSILON then begin
11287 t:=(-b)-sqrt(d);
11288 if (t>=0.0) and (t<=MaxTime) then begin
11289 HitTime:=t;
11290 result:=true;
11291 end;
11292 end;
11293 end;
11294 end;
11295
11296 function RayCastSphere(const RayOrigin,RayDirection,SpherePosition:TKraftVector3;const Radius,MaxTime:TKraftScalar;var HitTime:TKraftScalar;var HitPosition,HitNormal:TKraftVector3):boolean; overload; {$ifdef caninline}inline;{$endif}
11297 var Origin,Direction,m:TKraftVector3;
11298 b,c,d,t:TKraftScalar;
11299 begin
11300 result:=false;
11301 Origin:=RayOrigin;
11302 Direction:=RayDirection;
11303 m:=Vector3Sub(Origin,SpherePosition);
11304 b:=Vector3Dot(m,Direction);
11305 c:=Vector3LengthSquared(m)-sqr(Radius);
11306 if (c<=0.0) or (b<=0.0) then begin
11307 d:=sqr(b)-c;
11308 if d>=EPSILON then begin
11309 t:=(-b)-sqrt(d);
11310 if (t>=0.0) and (t<=MaxTime) then begin
11311 HitTime:=t;
11312 HitPosition:=Vector3Add(Origin,Vector3ScalarMul(Direction,t));
11313 HitNormal:=Vector3NormEx(Vector3Sub(HitPosition,SpherePosition));
11314 result:=true;
11315 end;
11316 end;
11317 end;
11318 end;
11319
11320 function CalculateAreaFromThreePoints(const p0,p1,p2:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
11321 begin
11322 result:=Vector3LengthSquared(Vector3Cross(Vector3Sub(p1,p0),Vector3Sub(p2,p0)));
11323 end;
11324
11325 function CalculateAreaFromFourPoints(const p0,p1,p2,p3:TKraftVector3):TKraftScalar; overload; {$ifdef caninline}inline;{$endif}
11326 begin
11327 result:=Max(Max(Vector3LengthSquared(Vector3Cross(Vector3Sub(p0,p1),Vector3Sub(p3,p3))),
11328 Vector3LengthSquared(Vector3Cross(Vector3Sub(p0,p2),Vector3Sub(p1,p3)))),
11329 Vector3LengthSquared(Vector3Cross(Vector3Sub(p0,p3),Vector3Sub(p1,p2))));
11330 end;
11331
11332 function BoxGetDistanceToPoint(Point:TKraftVector3;const Extents:TKraftVector3;const InverseTransformMatrix,TransformMatrix:TKraftMatrix4x4;var ClosestBoxPoint:TKraftVector3):TKraftScalar;
11333 var Temp,Direction:TKraftVector3;
11334 Overlap:longint;
11335 begin
11336 result:=0;
11337 ClosestBoxPoint:=Vector3TermMatrixMul(Point,InverseTransformMatrix);
11338 if ClosestBoxPoint.x<-Extents.x then begin
11339 result:=result+sqr(ClosestBoxPoint.x-(-Extents.x));
11340 ClosestBoxPoint.x:=-Extents.x;
11341 Overlap:=0;
11342 end else if ClosestBoxPoint.x>Extents.x then begin
11343 result:=result+sqr(ClosestBoxPoint.x-Extents.x);
11344 ClosestBoxPoint.x:=Extents.x;
11345 Overlap:=0;
11346 end else begin
11347 Overlap:=1;
11348 end;
11349 if ClosestBoxPoint.y<-Extents.y then begin
11350 result:=result+sqr(ClosestBoxPoint.y-(-Extents.y));
11351 ClosestBoxPoint.y:=-Extents.y;
11352 end else if ClosestBoxPoint.y>Extents.y then begin
11353 result:=result+sqr(ClosestBoxPoint.y-Extents.y);
11354 ClosestBoxPoint.y:=Extents.y;
11355 end else begin
11356 Overlap:=Overlap or 2;
11357 end;
11358 if ClosestBoxPoint.z<-Extents.z then begin
11359 result:=result+sqr(ClosestBoxPoint.z-(-Extents.z));
11360 ClosestBoxPoint.z:=-Extents.z;
11361 end else if ClosestBoxPoint.z>Extents.z then begin
11362 result:=result+sqr(ClosestBoxPoint.z-Extents.z);
11363 ClosestBoxPoint.z:=Extents.z;
11364 end else begin
11365 Overlap:=Overlap or 3;
11366 end;
11367 if Overlap<>7 then begin
11368 result:=sqrt(result);
11369 end else begin
11370 Temp:=ClosestBoxPoint;
11371 Direction.x:=ClosestBoxPoint.x/Extents.x;
11372 Direction.y:=ClosestBoxPoint.y/Extents.y;
11373 Direction.z:=ClosestBoxPoint.z/Extents.z;
11374 if (abs(Direction.x)>abs(Direction.y)) and (abs(Direction.x)>abs(Direction.z)) then begin
11375 if Direction.x<0.0 then begin
11376 ClosestBoxPoint.x:=-Extents.x;
11377 end else begin
11378 ClosestBoxPoint.x:=Extents.x;
11379 end;
11380 end else if (abs(Direction.y)>abs(Direction.x)) and (abs(Direction.y)>abs(Direction.z)) then begin
11381 if Direction.y<0.0 then begin
11382 ClosestBoxPoint.y:=-Extents.y;
11383 end else begin
11384 ClosestBoxPoint.y:=Extents.y;
11385 end;
11386 end else begin
11387 if Direction.z<0.0 then begin
11388 ClosestBoxPoint.z:=-Extents.z;
11389 end else begin
11390 ClosestBoxPoint.z:=Extents.z;
11391 end;
11392 end;
11393 result:=-Vector3Dist(ClosestBoxPoint,Temp);
11394 end;
11395 ClosestBoxPoint:=Vector3TermMatrixMul(ClosestBoxPoint,TransformMatrix);
11396 end;
11397
11398 type TSortCompareFunction=function(const a,b:pointer):longint;
11399
11400 function IntLog2(x:longword):longword; {$ifdef cpu386}assembler; register;
11401 asm
11402 test eax,eax
11403 jz @Done
11404 bsr eax,eax
11405 @Done:
11406 end;
11407 {$else}
11408 begin
11409 x:=x or (x shr 1);
11410 x:=x or (x shr 2);
11411 x:=x or (x shr 4);
11412 x:=x or (x shr 8);
11413 x:=x or (x shr 16);
11414 x:=x shr 1;
11415 x:=x-((x shr 1) and $55555555);
11416 x:=((x shr 2) and $33333333)+(x and $33333333);
11417 x:=((x shr 4)+x) and $0f0f0f0f;
11418 x:=x+(x shr 8);
11419 x:=x+(x shr 16);
11420 result:=x and $3f;
11421 end;
11422 {$endif}
11423
11424 procedure MemorySwap(a,b:pointer;Size:longint);
11425 var Temp:longint;
11426 begin
11427 while Size>=SizeOf(longint) do begin
11428 Temp:=longword(a^);
11429 longword(a^):=longword(b^);
11430 longword(b^):=Temp;
11431 inc(PtrUInt(a),SizeOf(longword));
11432 inc(PtrUInt(b),SizeOf(longword));
11433 dec(Size,SizeOf(longword));
11434 end;
11435 while Size>=SizeOf(byte) do begin
11436 Temp:=byte(a^);
11437 byte(a^):=byte(b^);
11438 byte(b^):=Temp;
11439 inc(PtrUInt(a),SizeOf(byte));
11440 inc(PtrUInt(b),SizeOf(byte));
11441 dec(Size,SizeOf(byte));
11442 end;
11443 end;
11444
11445 procedure DirectIntroSort(Items:pointer;Left,Right,ElementSize:longint;CompareFunc:TSortCompareFunction);
11446 type PByteArray=^TByteArray;
11447 TByteArray=array[0..$3fffffff] of byte;
11448 PStackItem=^TStackItem;
11449 TStackItem=record
11450 Left,Right,Depth:longint;
11451 end;
11452 var Depth,i,j,Middle,Size,Parent,Child,Pivot,iA,iB,iC:longint;
11453 StackItem:PStackItem;
11454 Stack:array[0..31] of TStackItem;
11455 begin
11456 if Left<Right then begin
11457 StackItem:=@Stack[0];
11458 StackItem^.Left:=Left;
11459 StackItem^.Right:=Right;
11460 StackItem^.Depth:=IntLog2((Right-Left)+1) shl 1;
11461 inc(StackItem);
11462 while ptruint(pointer(StackItem))>ptruint(pointer(@Stack[0])) do begin
11463 dec(StackItem);
11464 Left:=StackItem^.Left;
11465 Right:=StackItem^.Right;
11466 Depth:=StackItem^.Depth;
11467 Size:=(Right-Left)+1;
11468 if Size<16 then begin
11469 // Insertion sort
11470 iA:=Left;
11471 iB:=iA+1;
11472 while iB<=Right do begin
11473 iC:=iB;
11474 while (iA>=Left) and
11475 (iC>=Left) and
11476 (CompareFunc(pointer(@PByteArray(Items)^[iA*ElementSize]),pointer(@PByteArray(Items)^[iC*ElementSize]))>0) do begin
11477 MemorySwap(@PByteArray(Items)^[iA*ElementSize],@PByteArray(Items)^[iC*ElementSize],ElementSize);
11478 dec(iA);
11479 dec(iC);
11480 end;
11481 iA:=iB;
11482 inc(iB);
11483 end;
11484 end else begin
11485 if (Depth=0) or (ptruint(pointer(StackItem))>=ptruint(pointer(@Stack[high(Stack)-1]))) then begin
11486 // Heap sort
11487 i:=Size div 2;
11488 repeat
11489 if i>0 then begin
11490 dec(i);
11491 end else begin
11492 dec(Size);
11493 if Size>0 then begin
11494 MemorySwap(@PByteArray(Items)^[(Left+Size)*ElementSize],@PByteArray(Items)^[Left*ElementSize],ElementSize);
11495 end else begin
11496 break;
11497 end;
11498 end;
11499 Parent:=i;
11500 repeat
11501 Child:=(Parent*2)+1;
11502 if Child<Size then begin
11503 if (Child<(Size-1)) and (CompareFunc(pointer(@PByteArray(Items)^[(Left+Child)*ElementSize]),pointer(@PByteArray(Items)^[(Left+Child+1)*ElementSize]))<0) then begin
11504 inc(Child);
11505 end;
11506 if CompareFunc(pointer(@PByteArray(Items)^[(Left+Parent)*ElementSize]),pointer(@PByteArray(Items)^[(Left+Child)*ElementSize]))<0 then begin
11507 MemorySwap(@PByteArray(Items)^[(Left+Parent)*ElementSize],@PByteArray(Items)^[(Left+Child)*ElementSize],ElementSize);
11508 Parent:=Child;
11509 continue;
11510 end;
11511 end;
11512 break;
11513 until false;
11514 until false;
11515 end else begin
11516 // Quick sort width median-of-three optimization
11517 Middle:=Left+((Right-Left) shr 1);
11518 if (Right-Left)>3 then begin
11519 if CompareFunc(pointer(@PByteArray(Items)^[Left*ElementSize]),pointer(@PByteArray(Items)^[Middle*ElementSize]))>0 then begin
11520 MemorySwap(@PByteArray(Items)^[Left*ElementSize],@PByteArray(Items)^[Middle*ElementSize],ElementSize);
11521 end;
11522 if CompareFunc(pointer(@PByteArray(Items)^[Left*ElementSize]),pointer(@PByteArray(Items)^[Right*ElementSize]))>0 then begin
11523 MemorySwap(@PByteArray(Items)^[Left*ElementSize],@PByteArray(Items)^[Right*ElementSize],ElementSize);
11524 end;
11525 if CompareFunc(pointer(@PByteArray(Items)^[Middle*ElementSize]),pointer(@PByteArray(Items)^[Right*ElementSize]))>0 then begin
11526 MemorySwap(@PByteArray(Items)^[Middle*ElementSize],@PByteArray(Items)^[Right*ElementSize],ElementSize);
11527 end;
11528 end;
11529 Pivot:=Middle;
11530 i:=Left;
11531 j:=Right;
11532 repeat
11533 while (i<Right) and (CompareFunc(pointer(@PByteArray(Items)^[i*ElementSize]),pointer(@PByteArray(Items)^[Pivot*ElementSize]))<0) do begin
11534 inc(i);
11535 end;
11536 while (j>=i) and (CompareFunc(pointer(@PByteArray(Items)^[j*ElementSize]),pointer(@PByteArray(Items)^[Pivot*ElementSize]))>0) do begin
11537 dec(j);
11538 end;
11539 if i>j then begin
11540 break;
11541 end else begin
11542 if i<>j then begin
11543 MemorySwap(@PByteArray(Items)^[i*ElementSize],@PByteArray(Items)^[j*ElementSize],ElementSize);
11544 if Pivot=i then begin
11545 Pivot:=j;
11546 end else if Pivot=j then begin
11547 Pivot:=i;
11548 end;
11549 end;
11550 inc(i);
11551 dec(j);
11552 end;
11553 until false;
11554 if i<Right then begin
11555 StackItem^.Left:=i;
11556 StackItem^.Right:=Right;
11557 StackItem^.Depth:=Depth-1;
11558 inc(StackItem);
11559 end;
11560 if Left<j then begin
11561 StackItem^.Left:=Left;
11562 StackItem^.Right:=j;
11563 StackItem^.Depth:=Depth-1;
11564 inc(StackItem);
11565 end;
11566 end;
11567 end;
11568 end;
11569 end;
11570 end;
11571
11572 procedure IndirectIntroSort(Items:pointer;Left,Right:longint;CompareFunc:TSortCompareFunction);
11573 type PPointers=^TPointers;
11574 TPointers=array[0..$ffff] of pointer;
11575 PStackItem=^TStackItem;
11576 TStackItem=record
11577 Left,Right,Depth:longint;
11578 end;
11579 var Depth,i,j,Middle,Size,Parent,Child:longint;
11580 Pivot,Temp:pointer;
11581 StackItem:PStackItem;
11582 Stack:array[0..31] of TStackItem;
11583 begin
11584 if Left<Right then begin
11585 StackItem:=@Stack[0];
11586 StackItem^.Left:=Left;
11587 StackItem^.Right:=Right;
11588 StackItem^.Depth:=IntLog2((Right-Left)+1) shl 1;
11589 inc(StackItem);
11590 while ptruint(pointer(StackItem))>ptruint(pointer(@Stack[0])) do begin
11591 dec(StackItem);
11592 Left:=StackItem^.Left;
11593 Right:=StackItem^.Right;
11594 Depth:=StackItem^.Depth;
11595 Size:=(Right-Left)+1;
11596 if Size<16 then begin
11597 // Insertion sort
11598 for i:=Left+1 to Right do begin
11599 Temp:=PPointers(Items)^[i];
11600 j:=i-1;
11601 if (j>=Left) and (CompareFunc(PPointers(Items)^[j],Temp)>0) then begin
11602 repeat
11603 PPointers(Items)^[j+1]:=PPointers(Items)^[j];
11604 dec(j);
11605 until not ((j>=Left) and (CompareFunc(PPointers(Items)^[j],Temp)>0));
11606 PPointers(Items)^[j+1]:=Temp;
11607 end;
11608 end;
11609 end else begin
11610 if (Depth=0) or (ptruint(pointer(StackItem))>=ptruint(pointer(@Stack[high(Stack)-1]))) then begin
11611 // Heap sort
11612 i:=Size div 2;
11613 Temp:=nil;
11614 repeat
11615 if i>Left then begin
11616 dec(i);
11617 Temp:=PPointers(Items)^[Left+i];
11618 end else begin
11619 dec(Size);
11620 if Size>0 then begin
11621 Temp:=PPointers(Items)^[Left+Size];
11622 PPointers(Items)^[Left+Size]:=PPointers(Items)^[Left];
11623 end else begin
11624 break;
11625 end;
11626 end;
11627 Parent:=i;
11628 Child:=(i*2)+1;
11629 while Child<Size do begin
11630 if ((Child+1)<Size) and (CompareFunc(PPointers(Items)^[Left+Child+1],PPointers(Items)^[Left+Child])>0) then begin
11631 inc(Child);
11632 end;
11633 if CompareFunc(PPointers(Items)^[Left+Child],Temp)>0 then begin
11634 PPointers(Items)^[Left+Parent]:=PPointers(Items)^[Left+Child];
11635 Parent:=Child;
11636 Child:=(Parent*2)+1;
11637 end else begin
11638 break;
11639 end;
11640 end;
11641 PPointers(Items)^[Left+Parent]:=Temp;
11642 until false;
11643 end else begin
11644 // Quick sort width median-of-three optimization
11645 Middle:=Left+((Right-Left) shr 1);
11646 if (Right-Left)>3 then begin
11647 if CompareFunc(PPointers(Items)^[Left],PPointers(Items)^[Middle])>0 then begin
11648 Temp:=PPointers(Items)^[Left];
11649 PPointers(Items)^[Left]:=PPointers(Items)^[Middle];
11650 PPointers(Items)^[Middle]:=Temp;
11651 end;
11652 if CompareFunc(PPointers(Items)^[Left],PPointers(Items)^[Right])>0 then begin
11653 Temp:=PPointers(Items)^[Left];
11654 PPointers(Items)^[Left]:=PPointers(Items)^[Right];
11655 PPointers(Items)^[Right]:=Temp;
11656 end;
11657 if CompareFunc(PPointers(Items)^[Middle],PPointers(Items)^[Right])>0 then begin
11658 Temp:=PPointers(Items)^[Middle];
11659 PPointers(Items)^[Middle]:=PPointers(Items)^[Right];
11660 PPointers(Items)^[Right]:=Temp;
11661 end;
11662 end;
11663 Pivot:=PPointers(Items)^[Middle];
11664 i:=Left;
11665 j:=Right;
11666 repeat
11667 while (i<Right) and (CompareFunc(PPointers(Items)^[i],Pivot)<0) do begin
11668 inc(i);
11669 end;
11670 while (j>=i) and (CompareFunc(PPointers(Items)^[j],Pivot)>0) do begin
11671 dec(j);
11672 end;
11673 if i>j then begin
11674 break;
11675 end else begin
11676 if i<>j then begin
11677 Temp:=PPointers(Items)^[i];
11678 PPointers(Items)^[i]:=PPointers(Items)^[j];
11679 PPointers(Items)^[j]:=Temp;
11680 end;
11681 inc(i);
11682 dec(j);
11683 end;
11684 until false;
11685 if i<Right then begin
11686 StackItem^.Left:=i;
11687 StackItem^.Right:=Right;
11688 StackItem^.Depth:=Depth-1;
11689 inc(StackItem);
11690 end;
11691 if Left<j then begin
11692 StackItem^.Left:=Left;
11693 StackItem^.Right:=j;
11694 StackItem^.Depth:=Depth-1;
11695 inc(StackItem);
11696 end;
11697 end;
11698 end;
11699 end;
11700 end;
11701 end;
11702
11703 function SolveQuadraticRoots(const a,b,c:TKraftScalar;out t1,t2:TKraftScalar):boolean; {$ifdef caninline}inline;{$endif}
11704 var d,InverseDenominator:TKraftScalar;
11705 begin
11706 result:=false;
11707 d:=sqr(b)-(4.0*(a*c));
11708 if d>=0.0 then begin
11709 InverseDenominator:=1.0/(2.0*a);
11710 if abs(d)<EPSILON then begin
11711 t1:=(-b)*InverseDenominator;
11712 t2:=t1;
11713 end else begin
11714 d:=sqrt(d);
11715 t1:=((-b)-d)*InverseDenominator;
11716 t2:=((-b)+d)*InverseDenominator;
11717 end;
11718 result:=true;
11719 end;
11720 end;
11721
11722 function SweepSphereSphere(const pa0,pa1:TKraftVector3;const ra:TKraftScalar;const pb0,pb1:TKraftVector3;const rb:TKraftScalar;out t0,t1:TKraftScalar):boolean; overload; {$ifdef caninline}inline;{$endif}
11723 var va,vb,ab,vab:TKraftVector3;
11724 rab,a,b,c:TKraftScalar;
11725 begin
11726 va:=Vector3Sub(pa1,pa0);
11727 vb:=Vector3Sub(pb1,pb0);
11728 ab:=Vector3Sub(pb0,pa0);
11729 vab:=Vector3Sub(vb,va);
11730 rab:=ra+rb;
11731 a:=Vector3LengthSquared(vab);
11732 c:=Vector3LengthSquared(ab)-sqr(rab);
11733 if (abs(a)<EPSILON) or (c<=0.0) then begin
11734 t0:=0.0;
11735 t1:=0.0;
11736 result:=true;
11737 end else begin
11738 b:=2.0*Vector3Dot(vab,ab);
11739 if SolveQuadraticRoots(a,b,c,t0,t1) then begin
11740 if t1>t0 then begin
11741 a:=t0;
11742 t0:=t1;
11743 t1:=a;
11744 end;
11745 result:=(t1>=0.0) and (t0<=1.0);
11746 end else begin
11747 result:=false;
11748 end;
11749 end;
11750 end;
11751
11752 function SweepSphereSphere(const pa0,pa1:TKraftVector3;const ra:TKraftScalar;const pb0,pb1:TKraftVector3;const rb:TKraftScalar;out Time,Distance:TKraftScalar;out Normal:TKraftVector3):boolean; overload; {$ifdef caninline}inline;{$endif}
11753 var t0,t1:TKraftScalar;
11754 begin
11755 result:=SweepSphereSphere(pa0,pa1,ra,pb0,pb1,rb,t0,t1);
11756 if result then begin
11757 Time:=t0;
11758 Normal:=Vector3Sub(Vector3Lerp(pb0,pb1,t0),Vector3Lerp(pa0,pa1,t0));
11759 Distance:=Vector3LengthNormalize(Normal);
11760 if Distance<EPSILON then begin
11761 Normal:=Vector3Sub(pb0,pb1);
11762 if Vector3LengthNormalize(Normal)<EPSILON then begin
11763 Normal:=Vector3Sub(pa1,pa0);
11764 end;
11765 end;
11766 end;
11767 end;
11768
11769 function MPRIntersection(const ShapeA,ShapeB:TKraftShape;const TransformA,TransformB:TKraftMatrix4x4):boolean;
11770 var Phase1Iteration,Phase2Iterations:longint;
11771 v0,v1,v2,v3,v4,t,n:TKraftVector3;
11772 begin
11773 result:=false;
11774
11775 v0:=Vector3Sub(ShapeB.GetCenter(TransformB),ShapeA.GetCenter(TransformA));
11776
11777 if Vector3LengthSquared(v0)<1e-5 then begin
11778 v0.x:=1e-5;
11779 end;
11780
11781 n:=Vector3Neg(v0);
11782 v1:=Vector3Sub(Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB),
11783 Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(v0,TransformA)),TransformA));
11784 if Vector3Dot(v1,n)<=0.0 then begin
11785 exit;
11786 end;
11787
11788 n:=Vector3Cross(v1,v0);
11789 if Vector3LengthSquared(n)<EPSILON then begin
11790 result:=true;
11791 exit;
11792 end;
11793
11794 v2:=Vector3Sub(Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB),
11795 Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Vector3Neg(n),TransformA)),TransformA));
11796 if Vector3Dot(v2,n)<=0.0 then begin
11797 exit;
11798 end;
11799
11800 n:=Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v2,v0));
11801 if Vector3Dot(n,v0)>0.0 then begin
11802 t:=v1;
11803 v1:=v2;
11804 v2:=t;
11805 n:=Vector3Neg(n);
11806 end;
11807
11808 for Phase1Iteration:=1 to MPRMaximumIterations do begin
11809
11810 v3:=Vector3Sub(Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB),
11811 Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Vector3Neg(n),TransformA)),TransformA));
11812 if Vector3Dot(v3,n)<=0.0 then begin
11813 exit;
11814 end;
11815
11816 { t:=Vector3Cross(v3,v0);
11817
11818 if Vector3Dot(t,v1)<0.0 then begin}
11819 if Vector3Dot(v0,Vector3Cross(v3,v1))>0.0 then begin
11820 v2:=v3;
11821 n:=Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v3,v0));
11822 continue;
11823 end;
11824
11825 //if Vector3Dot(t,v2)>0.0 then begin
11826 if Vector3Dot(v0,Vector3Cross(v2,v3))>0.0 then begin
11827 v1:=v3;
11828 n:=Vector3Cross(Vector3Sub(v3,v0),Vector3Sub(v2,v0));
11829 continue;
11830 end;
11831
11832 Phase2Iterations:=0;
11833
11834 repeat
11835 inc(Phase2Iterations);
11836 n:=Vector3Cross(Vector3Sub(v2,v1),Vector3Sub(v3,v1));
11837 if Vector3LengthSquared(n)<EPSILON then begin
11838 result:=true;
11839 exit;
11840 end;
11841 Vector3Normalize(n);
11842 if (Vector3Dot(v1,n)>=0.0) and not result then begin
11843 result:=true;
11844 end;
11845 v4:=Vector3Sub(Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB),
11846 Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Vector3Neg(n),TransformA)),TransformA));
11847 if (Vector3Dot(Vector3Sub(v4,v3),n)<=MPRTolerance) or
11848 (Vector3Dot(v4,n)<=0.0) or
11849 (Phase2Iterations>MPRMaximumIterations) then begin
11850 exit;
11851 end;
11852 t:=Vector3Cross(v4,v0);
11853 if Vector3Dot(t,v1)>0.0 then begin
11854 if Vector3Dot(t,v2)>0.0 then begin
11855 v1:=v4;
11856 end else begin
11857 v3:=v4;
11858 end;
11859 end else begin
11860 if Vector3Dot(t,v3)>0.0 then begin
11861 v2:=v4;
11862 end else begin
11863 v1:=v4;
11864 end;
11865 end;
11866 until false;
11867
11868 end;
11869
11870 end;
11871
11872 function MPRPenetration(const ShapeA,ShapeB:TKraftShape;const TransformA,TransformB:TKraftMatrix4x4;out PositionA,PositionB,Normal:TKraftVector3;out PenetrationDepth:TKraftScalar):boolean;
11873 var Phase1Iteration,Phase2Iterations:longint;
11874 b0,b1,b2,b3,Sum,Inv:TKraftScalar;
11875 v0,v0a,v0b,v1,v1a,v1b,v2,v2a,v2b,v3,v3a,v3b,v4,v4a,v4b,t,n:TKraftVector3;
11876 begin
11877 result:=false;
11878
11879 PositionA:=Vector3Origin;
11880 PositionB:=Vector3Origin;
11881 PenetrationDepth:=0.0;
11882
11883 v0a:=ShapeA.GetCenter(TransformA);
11884 v0b:=ShapeB.GetCenter(TransformB);
11885 v0:=Vector3Sub(v0b,v0a);
11886
11887 if Vector3LengthSquared(v0)<1e-5 then begin
11888 v0.x:=1e-5;
11889 end;
11890
11891 n:=Vector3Neg(v0);
11892 v1a:=Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(v0,TransformA)),TransformA);
11893 v1b:=Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB);
11894 v1:=Vector3Sub(v1b,v1a);
11895 if Vector3Dot(v1,n)<=0.0 then begin
11896 Normal:=n;
11897 exit;
11898 end;
11899
11900 n:=Vector3Cross(v1,v0);
11901 if Vector3LengthSquared(n)<EPSILON then begin
11902 PositionA:=v1a;
11903 PositionB:=v1b;
11904 Normal:=Vector3Norm(Vector3Sub(v1,v0));
11905 PenetrationDepth:=Vector3Dot(Vector3Sub(v1b,v1a),Normal);
11906 result:=true;
11907 exit;
11908 end;
11909
11910 v2a:=Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Vector3Neg(n),TransformA)),TransformA);
11911 v2b:=Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB);
11912 v2:=Vector3Sub(v2b,v2a);
11913 if Vector3Dot(v2,n)<=0.0 then begin
11914 Normal:=n;
11915 exit;
11916 end;
11917
11918 n:=Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v2,v0));
11919 if Vector3Dot(n,v0)>0.0 then begin
11920 t:=v1;
11921 v1:=v2;
11922 v2:=t;
11923 t:=v1a;
11924 v1a:=v2a;
11925 v2a:=t;
11926 t:=v1b;
11927 v1b:=v2b;
11928 v2b:=t;
11929 n:=Vector3Neg(n);
11930 end;
11931
11932 for Phase1Iteration:=1 to MPRMaximumIterations do begin
11933
11934 v3a:=Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Vector3Neg(n),TransformA)),TransformA);
11935 v3b:=Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB);
11936 v3:=Vector3Sub(v3b,v3a);
11937 if Vector3Dot(v3,n)<=0.0 then begin
11938 Normal:=n;
11939 exit;
11940 end;
11941
11942 { t:=Vector3Cross(v3,v0);
11943
11944 if Vector3Dot(t,v1)<0.0 then begin}
11945 if Vector3Dot(v0,Vector3Cross(v3,v1))>0.0 then begin
11946 v2:=v3;
11947 v2a:=v3a;
11948 v2b:=v3b;
11949 n:=Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v3,v0));
11950 continue;
11951 end;
11952
11953 //if Vector3Dot(t,v2)>0.0 then begin
11954 if Vector3Dot(v0,Vector3Cross(v2,v3))>0.0 then begin
11955 v1:=v3;
11956 v1a:=v3a;
11957 v1b:=v3b;
11958 n:=Vector3Cross(Vector3Sub(v3,v0),Vector3Sub(v2,v0));
11959 continue;
11960 end;
11961
11962 Phase2Iterations:=0;
11963
11964 repeat
11965
11966 inc(Phase2Iterations);
11967
11968 n:=Vector3Cross(Vector3Sub(v2,v1),Vector3Sub(v3,v1));
11969
11970 if Vector3LengthSquared(n)<EPSILON then begin
11971 PositionA:=v1a;
11972 PositionB:=v1b;
11973 Normal:=Vector3Norm(Vector3Sub(v1,v0));
11974 PenetrationDepth:=Vector3Dot(Vector3Sub(v1b,v1a),Normal);
11975 result:=true;
11976 exit;
11977 end;
11978
11979 Vector3Normalize(n);
11980
11981 if (Vector3Dot(v1,n)>=0.0) and not result then begin
11982 result:=true;
11983 end;
11984
11985 v4a:=Vector3TermMatrixMul(ShapeA.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Vector3Neg(n),TransformA)),TransformA);
11986 v4b:=Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(n,TransformB)),TransformB);
11987 v4:=Vector3Sub(v4b,v4a);
11988
11989 PenetrationDepth:=Vector3Dot(v4,n);
11990
11991 if (Vector3Dot(Vector3Sub(v4,v3),n)<=MPRTolerance) or
11992 (PenetrationDepth<=0.0) or
11993 (Phase2Iterations>MPRMaximumIterations) then begin
11994
11995 if result then begin
11996
11997 Normal:=n;
11998
11999 b0:=Vector3Dot(Vector3Cross(v1,v2),v3);
12000 b1:=Vector3Dot(Vector3Cross(v3,v2),v0);
12001 b2:=Vector3Dot(Vector3Cross(v0,v1),v3);
12002 b3:=Vector3Dot(Vector3Cross(v2,v1),v0);
12003
12004 Sum:=b0+b1+b2+b3;
12005
12006 if Sum<=0.0 then begin
12007
12008 b0:=0.0;
12009 b1:=Vector3Dot(Vector3Cross(v2,v3),n);
12010 b2:=Vector3Dot(Vector3Cross(v3,v1),n);
12011 b3:=Vector3Dot(Vector3Cross(v1,v2),n);
12012
12013 Sum:=b1+b2+b3;
12014
12015 end;
12016
12017 Inv:=1.0/Sum;
12018
12019 PositionA.x:=((v0a.x*b0)+(v1a.x*b1)+(v2a.x*b2)+(v3a.x*b3))*Inv;
12020 PositionA.y:=((v0a.y*b0)+(v1a.y*b1)+(v2a.y*b2)+(v3a.y*b3))*Inv;
12021 PositionA.z:=((v0a.z*b0)+(v1a.z*b1)+(v2a.z*b2)+(v3a.z*b3))*Inv;
12022
12023 PositionB.x:=((v0b.x*b0)+(v1b.x*b1)+(v2b.x*b2)+(v3b.x*b3))*Inv;
12024 PositionB.y:=((v0b.y*b0)+(v1b.y*b1)+(v2b.y*b2)+(v3b.y*b3))*Inv;
12025 PositionB.z:=((v0b.z*b0)+(v1b.z*b1)+(v2b.z*b2)+(v3b.z*b3))*Inv;
12026
12027 end;
12028
12029 exit;
12030
12031 end;
12032
12033 t:=Vector3Cross(v4,v0);
12034
12035 if Vector3Dot(t,v1)>0.0 then begin
12036
12037 if Vector3Dot(t,v2)>0.0 then begin
12038
12039 v1:=v4;
12040 v1a:=v4a;
12041 v1b:=v4b;
12042
12043 end else begin
12044
12045 v3:=v4;
12046 v3a:=v4a;
12047 v3b:=v4b;
12048
12049 end;
12050
12051 end else begin
12052
12053 if Vector3Dot(t,v3)>0.0 then begin
12054
12055 v2:=v4;
12056 v2a:=v4a;
12057 v2b:=v4b;
12058
12059 end else begin
12060
12061 v1:=v4;
12062 v1a:=v4a;
12063 v1b:=v4b;
12064
12065 end;
12066
12067 end;
12068
12069 until false;
12070
12071 end;
12072
12073 end;
12074
12075 function MPRAreSweptShapesIntersecting(const ShapeA,ShapeB:TKraftShape;const Sweep:TKraftVector3;const Transform:TKraftMatrix4x4;var HitPosition:TKraftVector3):boolean;
12076 function GetSweptExtremePoint(const Direction:TKraftVector3;out ExtremePointA:TKraftVector3):TKraftVector3;
12077 begin
12078 ExtremePointA:=ShapeA.GetLocalFullSupport(Direction);
12079 result:=Vector3Sub(ExtremePointA,Vector3TermMatrixMul(ShapeB.GetLocalFullSupport(Vector3TermMatrixMulTransposedBasis(Direction,Transform)),Transform));
12080 if Vector3Dot(Direction,Sweep)>0.0 then begin
12081 result:=Vector3Add(result,Sweep);
12082 end;
12083 end;
12084 var Count:longint;
12085 LocalPoint,v0,v1,v1a,v2,v2a,v3,v3a,v4,v4a,v1v0,v2v0,v3v0,t,n:TKraftVector3;
12086 Dot,DotV0,BarycentricCoordinate,v0v1v2v3Volume,v1v2v3Volume,v0v2v3Volume,v0v1v3Volume,
12087 InverseTotalVolume,v0Weight,v1Weight,v2Weight,v3Weight,Dot2:TKraftScalar;
12088 begin
12089 result:=false;
12090
12091 LocalPoint.x:=Transform[3,0];
12092 LocalPoint.y:=Transform[3,1];
12093 LocalPoint.z:=Transform[3,2];
12094
12095 if Vector3LengthSquared(LocalPoint)<EPSILON then begin
12096 HitPosition:=LocalPoint;
12097 result:=true;
12098 exit;
12099 end;
12100
12101 v0:=Vector3Neg(LocalPoint);
12102
12103 n:=LocalPoint;
12104 v1:=GetSweptExtremePoint(n,v1a);
12105
12106 n:=Vector3Cross(v1,v0);
12107 if Vector3LengthSquared(n)<EPSILON then begin
12108 Dot:=Vector3Dot(v1,LocalPoint);
12109 if Dot<0.0 then begin
12110 result:=false;
12111 end else begin
12112 DotV0:=Vector3Dot(v0,LocalPoint);
12113 BarycentricCoordinate:=-(Dotv0/(Dot-DotV0));
12114 HitPosition:=Vector3ScalarMul(v1a,BarycentricCoordinate);
12115 result:=true;
12116 end;
12117 exit;
12118 end;
12119
12120 v2:=GetSweptExtremePoint(n,v2a);
12121
12122 n:=Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v2,v0));
12123
12124 for Count:=1 to MPRMaximumIterations do begin
12125 v3:=GetSweptExtremePoint(n,v3a);
12126 if Vector3Dot(v0,Vector3Cross(v1,v3))<0.0 then begin
12127 v2:=v3;
12128 v2a:=v3a;
12129 n:=Vector3Cross(Vector3Sub(v1,v0),Vector3Sub(v3,v0));
12130 end else if Vector3Dot(v0,Vector3Cross(v3,v2))<0.0 then begin
12131 v1:=v3;
12132 v1a:=v3a;
12133 n:=Vector3Cross(Vector3Sub(v2,v0),Vector3Sub(v3,v0));
12134 end else begin
12135 break;
12136 end;
12137 end;
12138
12139 Count:=0;
12140 while true do begin
12141
12142 n:=Vector3Cross(Vector3Sub(v3,v2),Vector3Sub(v1,v2));
12143
12144 Dot:=Vector3Dot(v1,n);
12145 if Dot>=0.0 then begin
12146
12147 v1v0:=Vector3Sub(v1,v0);
12148 v2v0:=Vector3Sub(v2,v0);
12149 v3v0:=Vector3Sub(v3,v0);
12150
12151 v0v1v2v3Volume:=Vector3Dot(Vector3Cross(v1v0,v2v0),v3v0);
12152 v1v2v3Volume:=Vector3Dot(Vector3Cross(v1,v2),v3);
12153 v0v2v3Volume:=Vector3Dot(Vector3Cross(LocalPoint,v2v0),v3v0);
12154 v0v1v3Volume:=Vector3Dot(Vector3Cross(v1v0,LocalPoint),v3v0);
12155
12156 InverseTotalVolume:=1.0/v0v1v2v3Volume;
12157 v0Weight:=v1v2v3volume*InverseTotalVolume;
12158 v1Weight:=v0v2v3volume*InverseTotalVolume;
12159 v2Weight:=v0v1v3volume*InverseTotalVolume;
12160 v3Weight:=1.0-(v0Weight+v1Weight+v2Weight);
12161 HitPosition:=Vector3Add(Vector3Add(Vector3ScalarMul(v1a,v1Weight),Vector3ScalarMul(v2a,v2Weight)),Vector3ScalarMul(v3a,v3Weight));
12162 result:=true;
12163 exit;
12164 end;
12165
12166 v4:=GetSweptExtremePoint(n,v4a);
12167 Dot2:=Vector3Dot(v4,n);
12168 if (Dot2<0.0) or
12169 ((Dot2-Dot)<MPRTolerance) or
12170 (Count>MPRSweepCastMaximumIterations) then begin
12171 HitPosition:=LocalPoint;
12172 exit;
12173 end;
12174
12175 t:=Vector3Cross(v4,v0);
12176 if Vector3Dot(t,v1)>=0.0 then begin
12177 if Vector3Dot(t,v2)>=0.0 then begin
12178 v1:=v4;
12179 v1a:=v4a;
12180 end else begin
12181 v3:=v4;
12182 v3a:=v4a;
12183 end;
12184 end else begin
12185 if Vector3Dot(t,v3)>=0.0 then begin
12186 v2:=v4;
12187 v2a:=v4a;
12188 end else begin
12189 v1:=v4;
12190 v1a:=v4a;
12191 end;
12192 end;
12193 inc(Count);
12194 end;
12195
12196 end;
12197
12198 function MPRSweep(const ShapeA,ShapeB:TKraftShape;const SweepA,SweepB:TKraftSweep):boolean; overload;
12199 var RayLengthSquared,SweepLength,MaximumRadius,t0,t1:TKraftScalar;
12200 VelocityWorld,LocalOrigin,LocalDirection,Sweep,HitPosition,VelocityA,VelocityB:TKraftVector3;
12201 NegativeSweepLength:boolean;
12202 LocalTransformBinA:TKraftMatrix4x4;
12203 Positions:array[0..1,0..1] of TKraftVector3;
12204 Transforms:array[0..1,0..1] of TKraftMatrix4x4;
12205 begin
12206 result:=false;
12207
12208 Transforms[0,0]:=Matrix4x4TermMul(ShapeA.fLocalTransform,SweepTransform(SweepA,0.0));
12209 Transforms[0,1]:=Matrix4x4TermMul(ShapeA.fLocalTransform,SweepTransform(SweepA,1.0));
12210 Transforms[1,0]:=Matrix4x4TermMul(ShapeB.fLocalTransform,SweepTransform(SweepB,0.0));
12211 Transforms[1,1]:=Matrix4x4TermMul(ShapeB.fLocalTransform,SweepTransform(SweepB,1.0));
12212
12213 Positions[0,0]:=Vector3TermMatrixMul(ShapeA.fLocalCenterOfMass,Transforms[0,0]);
12214 Positions[0,1]:=Vector3TermMatrixMul(ShapeA.fLocalCenterOfMass,Transforms[0,1]);
12215 Positions[1,0]:=Vector3TermMatrixMul(ShapeB.fLocalCenterOfMass,Transforms[1,0]);
12216 Positions[1,1]:=Vector3TermMatrixMul(ShapeB.fLocalCenterOfMass,Transforms[1,1]);
12217
12218 if not SweepSphereSphere(Positions[0,0],Positions[0,1],ShapeA.fShapeSphere.Radius,Positions[1,0],Positions[1,1],ShapeB.fShapeSphere.Radius,t0,t1) then begin
12219 exit;
12220 end;
12221
12222 VelocityA:=Vector3Sub(Positions[0,1],Positions[0,0]);
12223 VelocityB:=Vector3Sub(Positions[1,1],Positions[1,0]);
12224
12225 VelocityWorld:=Vector3Sub(VelocityB,VelocityA);
12226
12227 LocalDirection:=Vector3SafeNorm(Vector3TermMatrixMulTransposedBasis(VelocityWorld,Transforms[0,0]));
12228
12229 LocalTransformBinA:=Matrix4x4TermMulInverted(Transforms[1,0],Transforms[0,0]);
12230
12231 MaximumRadius:=ShapeA.fShapeSphere.Radius+ShapeB.fShapeSphere.Radius;
12232
12233 LocalOrigin.x:=LocalTransformBinA[3,0];
12234 LocalOrigin.y:=LocalTransformBinA[3,1];
12235 LocalOrigin.z:=LocalTransformBinA[3,2];
12236
12237 // This sweep amount needs to expand the minkowski difference to fully intersect the plane defined by the sweep direction and origin.
12238 RayLengthSquared:=Vector3LengthSquared(LocalDirection);
12239 if RayLengthSquared>EPSILON then begin
12240 // Scale the sweep length by the margins. Divide by the length to pull the margin into terms of the length of the ray.
12241 SweepLength:=(Vector3Dot(LocalOrigin,LocalDirection)+MaximumRadius)/sqrt(RayLengthSquared);
12242 end else begin
12243 SweepLength:=0.0;
12244 end;
12245
12246 // If the sweep direction is found to be negative, the ray can be thought of as pointing away from the shape, so then do not sweep backward.
12247 NegativeSweepLength:=SweepLength<0.0;
12248 if NegativeSweepLength then begin
12249 SweepLength:=0.0;
12250 end;
12251
12252 Sweep:=Vector3ScalarMul(LocalDirection,SweepLength);
12253
12254 result:=MPRAreSweptShapesIntersecting(ShapeA,ShapeB,Sweep,LocalTransformBinA,HitPosition);
12255 end;
12256
12257 function TKraftGJK.Run:boolean;
12258 var CountSaved,Index,iA,iB:longint;
12259 Initialized,Duplicate:boolean;
12260 SimplexVertex:PKraftGJKSimplexVertex;
12261 CachedSimplexVertex:PKraftGJKCachedSimplexVertex;
12262 Metrics,SquaredDistances:array[0..1] of TKraftScalar;
12263 Saved:array[0..3,0..1] of longint;
12264 Direction,a,b,c,d,ba,ab,cb,bc,ac,ca,db,bd,cd,dc,da,ad,baxca,daxba,bcxdc,caxda:TKraftVector3;
12265 uAB,vAB,uBC,vBC,uCA,vCA,uBD,vBD,uDC,vDC,uAD,vAD,uADB,vADB,wADB,uACD,vACD,wACD,uCBD,vCBD,wCBD,
12266 uABC,vABC,wABC,uABCD,vABCD,wABCD,xABCD,Denominator:TKraftScalar;
12267 TempVertex:PKraftGJKSimplexVertex;
12268 begin
12269
12270 Failed:=false;
12271
12272 Initialized:=false;
12273
12274 // Initialize simplex vertex permutation order
12275 Simplex.Vertices[0]:[email protected][0];
12276 Simplex.Vertices[1]:[email protected][1];
12277 Simplex.Vertices[2]:[email protected][2];
12278 Simplex.Vertices[3]:[email protected][3];
12279
12280 // Try refill from cache
12281 if assigned(CachedSimplex) then begin
12282 Simplex.Count:=CachedSimplex^.Count;
12283 if Simplex.Count>0 then begin
12284 for Index:=0 to Simplex.Count-1 do begin
12285 CachedSimplexVertex:=@CachedSimplex^.Vertices[Index];
12286 SimplexVertex:=Simplex.Vertices[Index];
12287 SimplexVertex^.iA:=CachedSimplexVertex^.iA;
12288 SimplexVertex^.iB:=CachedSimplexVertex^.iB;
12289 SimplexVertex^.sA:=Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(SimplexVertex^.iA),Transforms[0]^);
12290 SimplexVertex^.sB:=Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(SimplexVertex^.iB),Transforms[1]^);
12291 SimplexVertex^.w:=Vector3Sub(SimplexVertex^.sB,SimplexVertex^.sA);
12292 SimplexVertex^.a:=CachedSimplexVertex^.a;
12293 end;
12294 Metrics[0]:=CachedSimplex^.Metric;
12295 case Simplex.Count of
12296 1:begin
12297 Metrics[1]:=0.0;
12298 end;
12299 2:begin
12300 Metrics[1]:=Vector3Dist(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w);
12301 end;
12302 3:begin
12303 Metrics[1]:=CalculateArea(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w,Simplex.Vertices[2]^.w);
12304 end;
12305 4:begin
12306 Metrics[1]:=CalculateVolume(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w,Simplex.Vertices[2]^.w,Simplex.Vertices[3]^.w);
12307 end;
12308 else begin
12309 Assert(false);
12310 Metrics[1]:=0.0;
12311 end;
12312 end;
12313 if not ((Metrics[1]<(Metrics[0]*0.5)) or ((Metrics[0]*2.0)<Metrics[1]) or (Metrics[1]<EPSILON)) then begin
12314 Initialized:=true;
12315 end;
12316 end;
12317 end;
12318
12319 // Initialize simplex if the cache was empty or its content was invalid
12320 if not Initialized then begin
12321 SimplexVertex:=Simplex.Vertices[0];
12322 SimplexVertex^.iA:=0;
12323 SimplexVertex^.iB:=0;
12324 SimplexVertex^.sA:=Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(0),Transforms[0]^);
12325 SimplexVertex^.sB:=Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(0),Transforms[1]^);
12326 SimplexVertex^.w:=Vector3Sub(SimplexVertex^.sB,SimplexVertex^.sA);
12327 SimplexVertex^.a:=1.0;
12328 Simplex.Count:=1;
12329 end;
12330
12331 SquaredDistances[0]:=MAX_SCALAR;
12332 SquaredDistances[1]:=MAX_SCALAR;
12333
12334 Iterations:=0;
12335
12336 // The main loop
12337 repeat
12338
12339 // Remember old simplex vertex indices
12340 CountSaved:=Simplex.Count;
12341 for Index:=0 to CountSaved-1 do begin
12342 Saved[Index,0]:=Simplex.Vertices[Index]^.iA;
12343 Saved[Index,1]:=Simplex.Vertices[Index]^.iB;
12344 end;
12345
12346 // Reduce simplex
12347 case Simplex.Count of
12348 1:begin
12349 // Point
12350 end;
12351 2:begin
12352 // Line
12353 a:=Simplex.Vertices[0]^.w;
12354 b:=Simplex.Vertices[1]^.w;
12355 vAB:=Vector3Dot(a,Vector3Sub(a,b));
12356 if vAB<=0.0 then begin
12357 // Region A
12358 Simplex.Vertices[0].a:=1.0;
12359 Simplex.Divisor:=1.0;
12360 Simplex.Count:=1;
12361 end else begin
12362 uAB:=Vector3Dot(b,Vector3Sub(b,a));
12363 if uAB<=0.0 then begin
12364 // Region B
12365 TempVertex:=Simplex.Vertices[0];
12366 Simplex.Vertices[0]:=Simplex.Vertices[1];
12367 Simplex.Vertices[1]:=TempVertex;
12368 Simplex.Vertices[0]^.a:=1.0;
12369 Simplex.Divisor:=1.0;
12370 Simplex.Count:=1;
12371 end else begin
12372 if abs(uAB+vAB)<EPSILON then begin
12373 // Terminate on affinely dependent points in the set (if uAB+vAB is (nearly) zero, we can never use point B)
12374 Simplex.Vertices[0]^.a:=1.0;
12375 Simplex.Divisor:=1.0;
12376 Simplex.Count:=1;
12377 end else begin
12378 // Region AB
12379 Simplex.Vertices[0]^.a:=uAB;
12380 Simplex.Vertices[1]^.a:=vAB;
12381 Simplex.Divisor:=uAB+vAB;
12382 Simplex.Count:=2;
12383 end;
12384 end;
12385 end;
12386 end;
12387 3:begin
12388 // Triangle
12389 a:=Simplex.Vertices[0]^.w;
12390 b:=Simplex.Vertices[1]^.w;
12391 c:=Simplex.Vertices[2]^.w;
12392 vAB:=Vector3Dot(a,Vector3Sub(a,b));
12393 uCA:=Vector3Dot(a,Vector3Sub(a,c));
12394 if (vAB<=0.0) and (uCA<=0.0) then begin
12395 // Region A
12396 Simplex.Vertices[0]^.a:=1.0;
12397 Simplex.Divisor:=1.0;
12398 Simplex.Count:=1;
12399 end else begin
12400 ba:=Vector3Sub(b,a);
12401 uAB:=Vector3Dot(b,ba);
12402 vBC:=Vector3Dot(b,Vector3Sub(b,c));
12403 if (uAB<=0.0) and (vBC<=0.0) then begin
12404 // Region B
12405 TempVertex:=Simplex.Vertices[0];
12406 Simplex.Vertices[0]:=Simplex.Vertices[1];
12407 Simplex.Vertices[1]:=TempVertex;
12408 Simplex.Vertices[0]^.a:=1.0;
12409 Simplex.Divisor:=1.0;
12410 Simplex.Count:=1;
12411 end else begin
12412 uBC:=Vector3Dot(c,Vector3Sub(c,b));
12413 ca:=Vector3Sub(c,a);
12414 vCA:=Vector3Dot(c,ca);
12415 if (uBC<=0.0) and (vCA<=0.0) then begin
12416 // Region C
12417 TempVertex:=Simplex.Vertices[0];
12418 Simplex.Vertices[0]:=Simplex.Vertices[2];
12419 Simplex.Vertices[2]:=TempVertex;
12420 Simplex.Vertices[0]^.a:=1.0;
12421 Simplex.Divisor:=1.0;
12422 Simplex.Count:=1;
12423 end else begin
12424 baxca:=Vector3Cross(ba,ca);
12425 wABC:=Vector3Dot(Vector3Cross(a,b),baxca);
12426 if (uAB>0.0) and (vAB>0.0) and (wABC<=0.0) then begin
12427 // Region AB
12428 Simplex.Vertices[0]^.a:=uAB;
12429 Simplex.Vertices[1]^.a:=vAB;
12430 Simplex.Divisor:=uAB+vAB;
12431 Simplex.Count:=2;
12432 end else begin
12433 uABC:=Vector3Dot(Vector3Cross(b,c),baxca);
12434 if (uBC>0.0) and (vBC>0.0) and (uABC<=0.0) then begin
12435 // Region BC
12436 TempVertex:=Simplex.Vertices[0];
12437 Simplex.Vertices[0]:=Simplex.Vertices[1];
12438 Simplex.Vertices[1]:=Simplex.Vertices[2];
12439 Simplex.Vertices[2]:=TempVertex;
12440 Simplex.Vertices[0]^.a:=uBC;
12441 Simplex.Vertices[1]^.a:=vBC;
12442 Simplex.Divisor:=uBC+vBC;
12443 Simplex.Count:=2;
12444 end else begin
12445 vABC:=Vector3Dot(Vector3Cross(c,a),baxca);
12446 if (uCA>0.0) and (vCA>0.0) and (vABC<=0.0) then begin
12447 // Region CA
12448 TempVertex:=Simplex.Vertices[1];
12449 Simplex.Vertices[1]:=Simplex.Vertices[0];
12450 Simplex.Vertices[0]:=Simplex.Vertices[2];
12451 Simplex.Vertices[2]:=TempVertex;
12452 Simplex.Vertices[0]^.a:=uCA;
12453 Simplex.Vertices[1]^.a:=vCA;
12454 Simplex.Divisor:=uCA+vCA;
12455 Simplex.Count:=2;
12456 end else begin
12457 if (uABC>0.0) and (vABC>0.0) and (wABC>0.0) then begin
12458 // Region ABC
12459 Simplex.Vertices[0]^.a:=uABC;
12460 Simplex.Vertices[1]^.a:=vABC;
12461 Simplex.Vertices[2]^.a:=wABC;
12462 Simplex.Divisor:=uABC+vABC+wABC;
12463 Simplex.Count:=3;
12464 end else begin
12465 Assert(false);
12466 end;
12467 end;
12468 end;
12469 end;
12470 end;
12471 end;
12472 end;
12473 end;
12474 4:begin
12475 // Tetrahedron
12476 a:=Simplex.Vertices[0]^.w;
12477 b:=Simplex.Vertices[1]^.w;
12478 c:=Simplex.Vertices[2]^.w;
12479 d:=Simplex.Vertices[3]^.w;
12480 ab:=Vector3Sub(a,b);
12481 ac:=Vector3Sub(a,c);
12482 ad:=Vector3Sub(a,d);
12483 vAB:=Vector3Dot(a,ab);
12484 uCA:=Vector3Dot(a,ac);
12485 vAD:=Vector3Dot(a,ad);
12486 if (vAB<=0.0) and (uCA<=0.0) and (vAD<=0.0) then begin
12487 // Region A
12488 Simplex.Vertices[0]^.a:=1.0;
12489 Simplex.Divisor:=1.0;
12490 Simplex.Count:=1;
12491 end else begin
12492 ba:=Vector3Sub(b,a);
12493 bc:=Vector3Sub(b,c);
12494 bd:=Vector3Sub(b,d);
12495 uAB:=Vector3Dot(b,ba);
12496 vBC:=Vector3Dot(b,bc);
12497 vBD:=Vector3Dot(b,bd);
12498 if (uAB<=0.0) and (vBC<=0.0) and (vBD<=0.0) then begin
12499 // Region B
12500 TempVertex:=Simplex.Vertices[0];
12501 Simplex.Vertices[0]:=Simplex.Vertices[1];
12502 Simplex.Vertices[1]:=TempVertex;
12503 Simplex.Vertices[0]^.a:=1.0;
12504 Simplex.Divisor:=1.0;
12505 Simplex.Count:=1;
12506 end else begin
12507 cb:=Vector3Sub(c,b);
12508 ca:=Vector3Sub(c,a);
12509 cd:=Vector3Sub(c,d);
12510 uBC:=Vector3Dot(c,cb);
12511 vCA:=Vector3Dot(c,ca);
12512 uDC:=Vector3Dot(c,cd);
12513 if (uBC<=0.0) and (vCA<=0.0) and (uDC<=0.0) then begin
12514 // Region C
12515 TempVertex:=Simplex.Vertices[0];
12516 Simplex.Vertices[0]:=Simplex.Vertices[2];
12517 Simplex.Vertices[2]:=TempVertex;
12518 Simplex.Vertices[0]^.a:=1.0;
12519 Simplex.Divisor:=1.0;
12520 Simplex.Count:=1;
12521 end else begin
12522 db:=Vector3Sub(d,b);
12523 dc:=Vector3Sub(d,c);
12524 da:=Vector3Sub(d,a);
12525 uBD:=Vector3Dot(d,db);
12526 vDC:=Vector3Dot(d,dc);
12527 uAD:=Vector3Dot(d,da);
12528 if (uBD<=0.0) and (vDC<=0.0) and (uAD<=0.0) then begin
12529 // Region D
12530 TempVertex:=Simplex.Vertices[0];
12531 Simplex.Vertices[0]:=Simplex.Vertices[3];
12532 Simplex.Vertices[3]:=TempVertex;
12533 Simplex.Vertices[0]^.a:=1.0;
12534 Simplex.Divisor:=1.0;
12535 Simplex.Count:=1;
12536 end else begin
12537 baxca:=Vector3Cross(ba,ca);
12538 daxba:=Vector3Cross(da,ba);
12539 wABC:=Vector3Dot(Vector3Cross(a,b),baxca);
12540 vADB:=Vector3Dot(Vector3Cross(b,a),daxba);
12541 if (wABC<=0.0) and (vADB<=0.0) and (uAB>0.0) and (vAB>0.0) then begin
12542 // Region AB
12543 Simplex.Vertices[0]^.a:=uAB;
12544 Simplex.Vertices[1]^.a:=vAB;
12545 Simplex.Divisor:=uAB+vAB;
12546 Simplex.Count:=2;
12547 end else begin
12548 bcxdc:=Vector3Cross(bc,dc);
12549 uABC:=Vector3Dot(Vector3Cross(b,c),baxca);
12550 wCBD:=Vector3Dot(Vector3Cross(c,b),bcxdc);
12551 if (uABC<=0.0) and (wCBD<=0.0) and (uBC>0.0) and (vBC>0.0) then begin
12552 // Region BC
12553 TempVertex:=Simplex.Vertices[0];
12554 Simplex.Vertices[0]:=Simplex.Vertices[1];
12555 Simplex.Vertices[1]:=Simplex.Vertices[2];
12556 Simplex.Vertices[2]:=TempVertex;
12557 Simplex.Vertices[0]^.a:=uBC;
12558 Simplex.Vertices[1]^.a:=vBC;
12559 Simplex.Divisor:=uBC+vBC;
12560 Simplex.Count:=2;
12561 end else begin
12562 caxda:=Vector3Cross(ca,da);
12563 vABC:=Vector3Dot(Vector3Cross(c,a),baxca);
12564 wACD:=Vector3Dot(Vector3Cross(a,c),caxda);
12565 if (vABC<=0.0) and (wACD<=0.0) and (uCA>0.0) and (vCA>0.0) then begin
12566 // Region CA
12567 TempVertex:=Simplex.Vertices[1];
12568 Simplex.Vertices[1]:=Simplex.Vertices[0];
12569 Simplex.Vertices[0]:=Simplex.Vertices[2];
12570 Simplex.Vertices[2]:=TempVertex;
12571 Simplex.Vertices[0]^.a:=uCA;
12572 Simplex.Vertices[1]^.a:=vCA;
12573 Simplex.Divisor:=uCA+vCA;
12574 Simplex.Count:=2;
12575 end else begin
12576 vCBD:=Vector3Dot(Vector3Cross(d,c),bcxdc);
12577 uACD:=Vector3Dot(Vector3Cross(c,d),caxda);
12578 if (vCBD<=0.0) and (uACD<=0.0) and (uDC>0.0) and (vDC>0.0) then begin
12579 // Region DC
12580 TempVertex:=Simplex.Vertices[0];
12581 Simplex.Vertices[0]:=Simplex.Vertices[3];
12582 Simplex.Vertices[3]:=TempVertex;
12583 TempVertex:=Simplex.Vertices[1];
12584 Simplex.Vertices[1]:=Simplex.Vertices[2];
12585 Simplex.Vertices[2]:=TempVertex;
12586 Simplex.Vertices[0]^.a:=uDC;
12587 Simplex.Vertices[1]^.a:=vDC;
12588 Simplex.Divisor:=uDC+vDC;
12589 Simplex.Count:=2;
12590 end else begin
12591 vACD:=Vector3Dot(Vector3Cross(d,a),caxda);
12592 wADB:=Vector3Dot(Vector3Cross(a,d),daxba);
12593 if (vACD<=0.0) and (wADB<=0.0) and (uAD>0.0) and (vAD>0.0) then begin
12594 // Region AD
12595 TempVertex:=Simplex.Vertices[1];
12596 Simplex.Vertices[1]:=Simplex.Vertices[3];
12597 Simplex.Vertices[3]:=TempVertex;
12598 Simplex.Vertices[0]^.a:=uAD;
12599 Simplex.Vertices[1]^.a:=vAD;
12600 Simplex.Divisor:=uAD+vAD;
12601 Simplex.Count:=2;
12602 end else begin
12603 uADB:=Vector3Dot(Vector3Cross(d,b),daxba);
12604 uCBD:=Vector3Dot(Vector3Cross(b,d),bcxdc);
12605 if (uCBD<=0.0) and (uADB<=0.0) and (uBD>0.0) and (vBD>0.0) then begin
12606 // Region BD
12607 TempVertex:=Simplex.Vertices[0];
12608 Simplex.Vertices[0]:=Simplex.Vertices[1];
12609 Simplex.Vertices[1]:=Simplex.Vertices[3];
12610 Simplex.Vertices[3]:=TempVertex;
12611 Simplex.Vertices[0]^.a:=uBD;
12612 Simplex.Vertices[1]^.a:=vBD;
12613 Simplex.Divisor:=uBD+vBD;
12614 Simplex.Count:=2;
12615 end else begin
12616 Denominator:=Vector3Dot(cb,Vector3Cross(ab,db));
12617 if abs(Denominator)<EPSILON then begin
12618 Denominator:=1.0;
12619 end else begin
12620 Denominator:=1.0/Denominator;
12621 end;
12622 xABCD:=Vector3Dot(b,Vector3Cross(a,c))*Denominator;
12623 if (xABCD<=0.0) and (uABC>0.0) and (vABC>0.0) and (wABC>0.0) then begin
12624 // Region ABC
12625 Simplex.Vertices[0]^.a:=uABC;
12626 Simplex.Vertices[1]^.a:=vABC;
12627 Simplex.Vertices[2]^.a:=wABC;
12628 Simplex.Divisor:=uABC+vABC+wABC;
12629 Simplex.Count:=3;
12630 end else begin
12631 uABCD:=Vector3Dot(c,Vector3Cross(d,b))*Denominator;
12632 if (uABCD<=0.0) and (uCBD>0.0) and (vCBD>0.0) and (vCBD>0.0) then begin
12633 // Region CBD
12634 TempVertex:=Simplex.Vertices[0];
12635 Simplex.Vertices[0]:=Simplex.Vertices[2];
12636 Simplex.Vertices[2]:=Simplex.Vertices[3];
12637 Simplex.Vertices[3]:=TempVertex;
12638 Simplex.Vertices[0]^.a:=uCBD;
12639 Simplex.Vertices[1]^.a:=vCBD;
12640 Simplex.Vertices[2]^.a:=wCBD;
12641 Simplex.Divisor:=uCBD+vCBD+wCBD;
12642 Simplex.Count:=3;
12643 end else begin
12644 vABCD:=Vector3Dot(c,Vector3Cross(a,d))*Denominator;
12645 if (vABCD<=0.0) and (uACD>0.0) and (vACD>0.0) and (wACD>0.0) then begin
12646 // Region ACD
12647 TempVertex:=Simplex.Vertices[1];
12648 Simplex.Vertices[1]:=Simplex.Vertices[2];
12649 Simplex.Vertices[2]:=Simplex.Vertices[3];
12650 Simplex.Vertices[3]:=TempVertex;
12651 Simplex.Vertices[0]^.a:=uACD;
12652 Simplex.Vertices[1]^.a:=vACD;
12653 Simplex.Vertices[2]^.a:=wACD;
12654 Simplex.Divisor:=uACD+vACD+wACD;
12655 Simplex.Count:=3;
12656 end else begin
12657 wABCD:=Vector3Dot(d,Vector3Cross(a,b))*Denominator;
12658 if (wABCD<=0.0) and (uADB>0.0) and (vADB>0.0) and (wADB>0.0) then begin
12659 // Region ADB
12660 TempVertex:=Simplex.Vertices[2];
12661 Simplex.Vertices[2]:=Simplex.Vertices[1];
12662 Simplex.Vertices[1]:=Simplex.Vertices[3];
12663 Simplex.Vertices[3]:=TempVertex;
12664 Simplex.Vertices[0]^.a:=uADB;
12665 Simplex.Vertices[1]^.a:=vADB;
12666 Simplex.Vertices[2]^.a:=wADB;
12667 Simplex.Divisor:=uADB+vADB+wADB;
12668 Simplex.Count:=3;
12669 end else begin
12670 if (uABCD>0.0) and (vABCD>0.0) and (wABCD>0.0) and (xABCD>0.0) then begin
12671 // Region ABCD
12672 Simplex.Vertices[0]^.a:=uABCD;
12673 Simplex.Vertices[1]^.a:=vABCD;
12674 Simplex.Vertices[2]^.a:=wABCD;
12675 Simplex.Vertices[3]^.a:=xABCD;
12676 Simplex.Divisor:=uABCD+vABCD+wABCD+xABCD;
12677 Simplex.Count:=4;
12678 // Tetrahedron simplex contained the origin, so we can break the loop here
12679 break;
12680 end else begin
12681 // The algorithm was unable to determine the subset, return the last best known subset
12682 Simplex.Vertices[0]^.a:=uABC;
12683 Simplex.Vertices[1]^.a:=vABC;
12684 Simplex.Vertices[2]^.a:=wABC;
12685 Simplex.Divisor:=uABC+vABC+wABC;
12686 Simplex.Count:=3;
12687 end;
12688 end;
12689 end;
12690 end;
12691 end;
12692 end;
12693 end;
12694 end;
12695 end;
12696 end;
12697 end;
12698 end;
12699 end;
12700 end;
12701 end;
12702 end;
12703 else begin
12704 Assert(false);
12705 end;
12706 end;
12707
12708 Assert(((Simplex.Vertices[0]<>Simplex.Vertices[1]) and (Simplex.Vertices[0]<>Simplex.Vertices[2]) and (Simplex.Vertices[0]<>Simplex.Vertices[3])) and ((Simplex.Vertices[1]<>Simplex.Vertices[2]) and (Simplex.Vertices[1]<>Simplex.Vertices[3])) and (Simplex.Vertices[2]<>Simplex.Vertices[3]));
12709
12710 // Get closest point
12711 Denominator:=1.0/Simplex.Divisor;
12712 case Simplex.Count of
12713 1:begin
12714 a:=Simplex.Vertices[0]^.w;
12715 end;
12716 2:begin
12717 a:=Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.w,Simplex.Vertices[0]^.a*Denominator),
12718 Vector3ScalarMul(Simplex.Vertices[1]^.w,Simplex.Vertices[1]^.a*Denominator));
12719 end;
12720 3:begin
12721 a:=Vector3Add(Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.w,Simplex.Vertices[0]^.a*Denominator),
12722 Vector3ScalarMul(Simplex.Vertices[1]^.w,Simplex.Vertices[1]^.a*Denominator)),
12723 Vector3ScalarMul(Simplex.Vertices[2]^.w,Simplex.Vertices[2]^.a*Denominator));
12724 end;
12725 4:begin
12726 a:=Vector3Add(Vector3Add(Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.w,Simplex.Vertices[0]^.a*Denominator),
12727 Vector3ScalarMul(Simplex.Vertices[1]^.w,Simplex.Vertices[1]^.a*Denominator)),
12728 Vector3ScalarMul(Simplex.Vertices[2]^.w,Simplex.Vertices[2]^.a*Denominator)),
12729 Vector3ScalarMul(Simplex.Vertices[3]^.w,Simplex.Vertices[3]^.a*Denominator));
12730 end;
12731 else begin
12732 Assert(false);
12733 a:=Vector3Origin;
12734 end;
12735 end;
12736
12737 // Ensure progress. This prevents complex multi-step cycling between simplex evolutions (this is possible in 3D, but not in 2D).
12738 SquaredDistances[1]:=Vector3LengthSquared(a);
12739 if SquaredDistances[1]>SquaredDistances[0] then begin
12740 break;
12741 end;
12742 SquaredDistances[0]:=SquaredDistances[1];
12743
12744 // Get next direction
12745 case Simplex.Count of
12746 1:begin
12747 Direction:=Vector3Neg(Simplex.Vertices[0]^.w);
12748 end;
12749 2:begin
12750 Direction:=Vector3Sub(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w);
12751 Direction:=Vector3Cross(Vector3Cross(Direction,Vector3Neg(Simplex.Vertices[0]^.w)),Direction);
12752 end;
12753 3:begin
12754 Direction:=Vector3Cross(Vector3Sub(Simplex.Vertices[1]^.w,Simplex.Vertices[0]^.w),Vector3Sub(Simplex.Vertices[2]^.w,Simplex.Vertices[0]^.w));
12755 if Vector3Dot(Direction,Simplex.Vertices[0]^.w)>0.0 then begin
12756 Direction:=Vector3Neg(Direction);
12757 end;
12758 end;
12759 else begin
12760 Assert(false);
12761 Direction:=Vector3Origin;
12762 end;
12763 end;
12764
12765 if Vector3LengthSquared(Direction)<EPSILON then begin
12766 // The origin is probably contained by a line segment or triangle. Thus the shapes are overlapped.
12767 // We can't return zero here even though there may be overlap.
12768 // In case the simplex is a point, segment, or triangle it is difficult to determine if the origin is
12769 // contained in the CSO or very close to it.
12770 break;
12771 end;
12772
12773 // Get new support simplex vertex indices
12774 iA:=Shapes[0].GetLocalFeatureSupportIndex(Vector3TermMatrixMulTransposedBasis(Vector3Neg(Direction),Transforms[0]^));
12775 iB:=Shapes[1].GetLocalFeatureSupportIndex(Vector3TermMatrixMulTransposedBasis(Direction,Transforms[1]^));
12776
12777 inc(Iterations);
12778
12779 // Check for duplicate support points
12780 Duplicate:=false;
12781 for Index:=0 to CountSaved-1 do begin
12782 if (Saved[Index,0]=iA) and (Saved[Index,1]=iB) then begin
12783 Duplicate:=true;
12784 break;
12785 end;
12786 end;
12787 if Duplicate then begin
12788 // If yes, then break the loop
12789 break;
12790 end;
12791
12792 // Store the new stuff
12793 SimplexVertex:=Simplex.Vertices[Simplex.Count];
12794 SimplexVertex^.iA:=iA;
12795 SimplexVertex^.iB:=iB;
12796 SimplexVertex^.sA:=Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(iA),Transforms[0]^);
12797 SimplexVertex^.sB:=Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(iB),Transforms[1]^);
12798 SimplexVertex^.w:=Vector3Sub(SimplexVertex^.sB,SimplexVertex^.sA);
12799 inc(Simplex.Count);
12800
12801 until Iterations=GJKMaximumIterations;
12802
12803 // Write the simplex information into the cache
12804 if assigned(CachedSimplex) then begin
12805 CachedSimplex^.Count:=Simplex.Count;
12806 if CachedSimplex^.Count>0 then begin
12807 for Index:=0 to CachedSimplex^.Count-1 do begin
12808 CachedSimplexVertex:=@CachedSimplex^.Vertices[Index];
12809 SimplexVertex:=Simplex.Vertices[Index];
12810 CachedSimplexVertex^.iA:=SimplexVertex^.iA;
12811 CachedSimplexVertex^.iB:=SimplexVertex^.iB;
12812 CachedSimplexVertex^.a:=SimplexVertex^.a;
12813 end;
12814 case Simplex.Count of
12815 1:begin
12816 CachedSimplex^.Metric:=0.0;
12817 end;
12818 2:begin
12819 CachedSimplex^.Metric:=Vector3Dist(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w);
12820 end;
12821 3:begin
12822 CachedSimplex^.Metric:=CalculateArea(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w,Simplex.Vertices[2]^.w);
12823 end;
12824 4:begin
12825 CachedSimplex^.Metric:=CalculateVolume(Simplex.Vertices[0]^.w,Simplex.Vertices[1]^.w,Simplex.Vertices[2]^.w,Simplex.Vertices[3]^.w);
12826 end;
12827 else begin
12828 Assert(false);
12829 CachedSimplex^.Metric:=0.0;
12830 end;
12831 end;
12832 end;
12833 end;
12834
12835 // Get closest points
12836 Denominator:=1.0/Simplex.Divisor;
12837 case Simplex.Count of
12838 1:begin
12839 ClosestPoints[0]:=Simplex.Vertices[0]^.sA;
12840 ClosestPoints[1]:=Simplex.Vertices[0]^.sB;
12841 end;
12842 2:begin
12843 ClosestPoints[0]:=Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.sA,Simplex.Vertices[0]^.a*Denominator),
12844 Vector3ScalarMul(Simplex.Vertices[1]^.sA,Simplex.Vertices[1]^.a*Denominator));
12845 ClosestPoints[1]:=Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.sB,Simplex.Vertices[0]^.a*Denominator),
12846 Vector3ScalarMul(Simplex.Vertices[1]^.sB,Simplex.Vertices[1]^.a*Denominator));
12847 end;
12848 3:begin
12849 ClosestPoints[0]:=Vector3Add(Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.sA,Simplex.Vertices[0]^.a*Denominator),
12850 Vector3ScalarMul(Simplex.Vertices[1]^.sA,Simplex.Vertices[1]^.a*Denominator)),
12851 Vector3ScalarMul(Simplex.Vertices[2]^.sA,Simplex.Vertices[2]^.a*Denominator));
12852 ClosestPoints[1]:=Vector3Add(Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.sB,Simplex.Vertices[0]^.a*Denominator),
12853 Vector3ScalarMul(Simplex.Vertices[1]^.sB,Simplex.Vertices[1]^.a*Denominator)),
12854 Vector3ScalarMul(Simplex.Vertices[2]^.sB,Simplex.Vertices[2]^.a*Denominator));
12855 end;
12856 4:begin
12857 ClosestPoints[0]:=Vector3Add(Vector3Add(Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.sA,Simplex.Vertices[0]^.a*Denominator),
12858 Vector3ScalarMul(Simplex.Vertices[1]^.sA,Simplex.Vertices[1]^.a*Denominator)),
12859 Vector3ScalarMul(Simplex.Vertices[2]^.sA,Simplex.Vertices[2]^.a*Denominator)),
12860 Vector3ScalarMul(Simplex.Vertices[3]^.sA,Simplex.Vertices[3]^.a*Denominator));
12861 ClosestPoints[1]:=Vector3Add(Vector3Add(Vector3Add(Vector3ScalarMul(Simplex.Vertices[0]^.sB,Simplex.Vertices[0]^.a*Denominator),
12862 Vector3ScalarMul(Simplex.Vertices[1]^.sB,Simplex.Vertices[1]^.a*Denominator)),
12863 Vector3ScalarMul(Simplex.Vertices[2]^.sB,Simplex.Vertices[2]^.a*Denominator)),
12864 Vector3ScalarMul(Simplex.Vertices[3]^.sB,Simplex.Vertices[3]^.a*Denominator));
12865 end;
12866 else begin
12867 Assert(false);
12868 ClosestPoints[0]:=Vector3Origin;
12869 ClosestPoints[1]:=Vector3Origin;
12870 end;
12871 end;
12872
12873 // Get the normal direction
12874 Normal:=Vector3Sub(ClosestPoints[0],ClosestPoints[1]);
12875
12876 // Normalize normal direction to a normalized normal vector, and get the distance at the same time
12877 Distance:=Vector3LengthNormalize(Normal);
12878
12879 // Apply the radius stuff, if requested and needed
12880 if UseRadii then begin
12881 if (Distance>(Shapes[0].fFeatureRadius+Shapes[1].fFeatureRadius)) and (Distance>EPSILON) then begin
12882 Distance:=Distance-(Shapes[0].fFeatureRadius+Shapes[1].fFeatureRadius);
12883 ClosestPoints[0]:=Vector3Sub(ClosestPoints[0],Vector3ScalarMul(Normal,Shapes[0].fFeatureRadius));
12884 ClosestPoints[1]:=Vector3Add(ClosestPoints[1],Vector3ScalarMul(Normal,Shapes[1].fFeatureRadius));
12885 end else begin
12886 Distance:=0.0;
12887 ClosestPoints[0]:=Vector3Avg(ClosestPoints[0],ClosestPoints[1]);
12888 ClosestPoints[1]:=ClosestPoints[0];
12889 end;
12890 end;
12891
12892 Failed:=((Simplex.Count<1) or (Simplex.Count>3)) or (Iterations=GJKMaximumIterations);
12893
12894 result:=not Failed;
12895
12896 end;
12897
12898 procedure CalculateVelocity(const cA:TKraftVector3;const qA:TKraftQuaternion;const cB:TKraftVector3;const qB:TKraftQuaternion;const DeltaTime:TKraftScalar;out LinearVelocity,AngularVelocity:TKraftVector3); {$ifdef caninline}inline;{$endif}
12899 var InverseDeltaTime,Angle:TKraftScalar;
12900 Axis:TKraftVector3;
12901 qD,qS,qB0:TKraftQuaternion;
12902 begin
12903 InverseDeltaTime:=1.0/DeltaTime;
12904 LinearVelocity:=Vector3ScalarMul(Vector3Sub(cB,cA),InverseDeltaTime);
12905 if (abs(qA.x-qB.x)<EPSILON) and (abs(qA.y-qB.y)<EPSILON) and (abs(qA.z-qB.z)<EPSILON) and (abs(qA.w-qB.w)<EPSILON) then begin
12906 AngularVelocity:=Vector3Origin;
12907 end else begin
12908 qD:=QuaternionSub(qA,qB);
12909 qS:=QuaternionAdd(qA,qB);
12910 if QuaternionLengthSquared(qD)<QuaternionLengthSquared(qS) then begin
12911 qB0:=qD;
12912 end else begin
12913 qB0:=QuaternionNeg(qD);
12914 end;
12915 qD:=QuaternionMul(qB0,QuaternionInverse(qA));
12916 QuaternionToAxisAngle(qD,Axis,Angle);
12917 AngularVelocity:=Vector3ScalarMul(Vector3SafeNorm(Axis),Angle*InverseDeltaTime);
12918 end;
12919 end;
12920
12921 constructor TKraftVector3Property.Create(AVector:PKraftVector3);
12922 begin
12923 inherited Create;
12924 fVector:=AVector;
12925 end;
12926
12927 destructor TKraftVector3Property.Destroy;
12928 begin
12929 inherited Destroy;
12930 end;
12931
12932 function TKraftVector3Property.GetX:TKraftScalar;
12933 begin
12934 result:=fVector^.x;
12935 end;
12936
12937 function TKraftVector3Property.GetY:TKraftScalar;
12938 begin
12939 result:=fVector^.y;
12940 end;
12941
12942 function TKraftVector3Property.GetZ:TKraftScalar;
12943 begin
12944 result:=fVector^.z;
12945 end;
12946
12947 function TKraftVector3Property.GetVector:TKraftVector3;
12948 begin
12949 result:=fVector^;
12950 end;
12951
12952 procedure TKraftVector3Property.SetX(const NewValue:TKraftScalar);
12953 begin
12954 fVector^.x:=NewValue;
12955 end;
12956
12957 procedure TKraftVector3Property.SetY(const NewValue:TKraftScalar);
12958 begin
12959 fVector^.y:=NewValue;
12960 end;
12961
12962 procedure TKraftVector3Property.SetZ(const NewValue:TKraftScalar);
12963 begin
12964 fVector^.z:=NewValue;
12965 end;
12966
12967 procedure TKraftVector3Property.SetVector(const NewVector:TKraftVector3);
12968 begin
12969 fVector^:=NewVector;
12970 end;
12971
12972 constructor TKraftDynamicAABBTree.Create;
12973 var i:longint;
12974 begin
12975 inherited Create;
12976 fRoot:=daabbtNULLNODE;
12977 fNodeCount:=0;
12978 fNodeCapacity:=16;
12979 GetMem(fNodes,fNodeCapacity*SizeOf(TKraftDynamicAABBTreeNode));
12980 FillChar(fNodes^,fNodeCapacity*SizeOf(TKraftDynamicAABBTreeNode),#0);
12981 for i:=0 to fNodeCapacity-2 do begin
12982 fNodes^[i].Next:=i+1;
12983 fNodes^[i].Height:=-1;
12984 end;
12985 fNodes^[fNodeCapacity-1].Next:=daabbtNULLNODE;
12986 fNodes^[fNodeCapacity-1].Height:=-1;
12987 fFreeList:=0;
12988 fPath:=0;
12989 fInsertionCount:=0;
12990 fStackCapacity:=16;
12991 GetMem(fStack,fStackCapacity*SizeOf(longint));
12992 end;
12993
12994 destructor TKraftDynamicAABBTree.Destroy;
12995 begin
12996 FreeMem(fNodes);
12997 FreeMem(fStack);
12998 inherited Destroy;
12999 end;
13000
13001 function TKraftDynamicAABBTree.AllocateNode:longint;
13002 var Node:PKraftDynamicAABBTreeNode;
13003 i:longint;
13004 begin
13005 if fFreeList=daabbtNULLNODE then begin
13006 inc(fNodeCapacity,fNodeCapacity);
13007 ReallocMem(fNodes,fNodeCapacity*SizeOf(TKraftDynamicAABBTreeNode));
13008 FillChar(fNodes^[fNodeCount],(fNodeCapacity-fNodeCount)*SizeOf(TKraftDynamicAABBTreeNode),#0);
13009 for i:=fNodeCount to fNodeCapacity-2 do begin
13010 fNodes^[i].Next:=i+1;
13011 fNodes^[i].Height:=-1;
13012 end;
13013 fNodes^[fNodeCapacity-1].Next:=daabbtNULLNODE;
13014 fNodes^[fNodeCapacity-1].Height:=-1;
13015 fFreeList:=fNodeCount;
13016 end;
13017 result:=fFreeList;
13018 fFreeList:=fNodes^[result].Next;
13019 Node:=@fNodes^[result];
13020 Node^.Parent:=daabbtNULLNODE;
13021 Node^.Children[0]:=daabbtNULLNODE;
13022 Node^.Children[1]:=daabbtNULLNODE;
13023 Node^.Height:=0;
13024 Node^.UserData:=nil;
13025 inc(fNodeCount);
13026 end;
13027
13028 procedure TKraftDynamicAABBTree.FreeNode(NodeID:longint);
13029 var Node:PKraftDynamicAABBTreeNode;
13030 begin
13031 Node:=@fNodes^[NodeID];
13032 Node^.Next:=fFreeList;
13033 Node^.Height:=-1;
13034 fFreeList:=NodeID;
13035 dec(fNodeCount);
13036 end;
13037
13038 function TKraftDynamicAABBTree.Balance(NodeAID:longint):longint;
13039 var NodeA,NodeB,NodeC,NodeD,NodeE,NodeF,NodeG:PKraftDynamicAABBTreeNode;
13040 NodeBID,NodeCID,NodeDID,NodeEID,NodeFID,NodeGID,NodeBalance:longint;
13041 begin
13042 NodeA:=@fNodes^[NodeAID];
13043 if (NodeA.Children[0]<0) or (NodeA^.Height<2) then begin
13044 result:=NodeAID;
13045 end else begin
13046 NodeBID:=NodeA^.Children[0];
13047 NodeCID:=NodeA^.Children[1];
13048 NodeB:=@fNodes^[NodeBID];
13049 NodeC:=@fNodes^[NodeCID];
13050 NodeBalance:=NodeC^.Height-NodeB^.Height;
13051 if NodeBalance>1 then begin
13052 NodeFID:=NodeC^.Children[0];
13053 NodeGID:=NodeC^.Children[1];
13054 NodeF:=@fNodes^[NodeFID];
13055 NodeG:=@fNodes^[NodeGID];
13056 NodeC^.Children[0]:=NodeAID;
13057 NodeC^.Parent:=NodeA^.Parent;
13058 NodeA^.Parent:=NodeCID;
13059 if NodeC^.Parent>=0 then begin
13060 if fNodes^[NodeC^.Parent].Children[0]=NodeAID then begin
13061 fNodes^[NodeC^.Parent].Children[0]:=NodeCID;
13062 end else begin
13063 fNodes^[NodeC^.Parent].Children[1]:=NodeCID;
13064 end;
13065 end else begin
13066 fRoot:=NodeCID;
13067 end;
13068 if NodeF^.Height>NodeG^.Height then begin
13069 NodeC^.Children[1]:=NodeFID;
13070 NodeA^.Children[1]:=NodeGID;
13071 NodeG^.Parent:=NodeAID;
13072 NodeA^.AABB:=AABBCombine(NodeB^.AABB,NodeG^.AABB);
13073 NodeC^.AABB:=AABBCombine(NodeA^.AABB,NodeF^.AABB);
13074 NodeA^.Height:=1+Max(NodeB^.Height,NodeG^.Height);
13075 NodeC^.Height:=1+Max(NodeA^.Height,NodeF^.Height);
13076 end else begin
13077 NodeC^.Children[1]:=NodeGID;
13078 NodeA^.Children[1]:=NodeFID;
13079 NodeF^.Parent:=NodeAID;
13080 NodeA^.AABB:=AABBCombine(NodeB^.AABB,NodeF^.AABB);
13081 NodeC^.AABB:=AABBCombine(NodeA^.AABB,NodeG^.AABB);
13082 NodeA^.Height:=1+Max(NodeB^.Height,NodeF^.Height);
13083 NodeC^.Height:=1+Max(NodeA^.Height,NodeG^.Height);
13084 end;
13085 result:=NodeCID;
13086 end else if NodeBalance<-1 then begin
13087 NodeDID:=NodeB^.Children[0];
13088 NodeEID:=NodeB^.Children[1];
13089 NodeD:=@fNodes^[NodeDID];
13090 NodeE:=@fNodes^[NodeEID];
13091 NodeB^.Children[0]:=NodeAID;
13092 NodeB^.Parent:=NodeA^.Parent;
13093 NodeA^.Parent:=NodeBID;
13094 if NodeB^.Parent>=0 then begin
13095 if fNodes^[NodeB^.Parent].Children[0]=NodeAID then begin
13096 fNodes^[NodeB^.Parent].Children[0]:=NodeBID;
13097 end else begin
13098 fNodes^[NodeB^.Parent].Children[1]:=NodeBID;
13099 end;
13100 end else begin
13101 fRoot:=NodeBID;
13102 end;
13103 if NodeD^.Height>NodeE^.Height then begin
13104 NodeB^.Children[1]:=NodeDID;
13105 NodeA^.Children[0]:=NodeEID;
13106 NodeE^.Parent:=NodeAID;
13107 NodeA^.AABB:=AABBCombine(NodeC^.AABB,NodeE^.AABB);
13108 NodeB^.AABB:=AABBCombine(NodeA^.AABB,NodeD^.AABB);
13109 NodeA^.Height:=1+Max(NodeC^.Height,NodeE^.Height);
13110 NodeB^.Height:=1+Max(NodeA^.Height,NodeD^.Height);
13111 end else begin
13112 NodeB^.Children[1]:=NodeEID;
13113 NodeA^.Children[0]:=NodeDID;
13114 NodeD^.Parent:=NodeAID;
13115 NodeA^.AABB:=AABBCombine(NodeC^.AABB,NodeD^.AABB);
13116 NodeB^.AABB:=AABBCombine(NodeA^.AABB,NodeE^.AABB);
13117 NodeA^.Height:=1+Max(NodeC^.Height,NodeD^.Height);
13118 NodeB^.Height:=1+Max(NodeA^.Height,NodeE^.Height);
13119 end;
13120 result:=NodeBID;
13121 end else begin
13122 result:=NodeAID;
13123 end;
13124 end;
13125 end;
13126
13127 procedure TKraftDynamicAABBTree.InsertLeaf(Leaf:longint);
13128 var Node:PKraftDynamicAABBTreeNode;
13129 LeafAABB,CombinedAABB,AABB:TKraftAABB;
13130 Index,Sibling,OldParent,NewParent:longint;
13131 Children:array[0..1] of longint;
13132 CombinedCost,Cost,InheritanceCost:TKraftScalar;
13133 Costs:array[0..1] of TKraftScalar;
13134 begin
13135 inc(fInsertionCount);
13136 if fRoot<0 then begin
13137 fRoot:=Leaf;
13138 fNodes^[Leaf].Parent:=daabbtNULLNODE;
13139 end else begin
13140 LeafAABB:=fNodes^[Leaf].AABB;
13141 Index:=fRoot;
13142 while fNodes^[Index].Children[0]>=0 do begin
13143 Children[0]:=fNodes^[Index].Children[0];
13144 Children[1]:=fNodes^[Index].Children[1];
13145
13146 CombinedAABB:=AABBCombine(fNodes^[Index].AABB,LeafAABB);
13147 CombinedCost:=AABBCost(CombinedAABB);
13148 Cost:=CombinedCost*2.0;
13149 InheritanceCost:=2.0*(CombinedCost-AABBCost(fNodes^[Index].AABB));
13150
13151 AABB:=AABBCombine(LeafAABB,fNodes^[Children[0]].AABB);
13152 if fNodes^[Children[0]].Children[0]<0 then begin
13153 Costs[0]:=AABBCost(AABB)+InheritanceCost;
13154 end else begin
13155 Costs[0]:=(AABBCost(AABB)-AABBCost(fNodes^[Children[0]].AABB))+InheritanceCost;
13156 end;
13157
13158 AABB:=AABBCombine(LeafAABB,fNodes^[Children[1]].AABB);
13159 if fNodes^[Children[1]].Children[1]<0 then begin
13160 Costs[1]:=AABBCost(AABB)+InheritanceCost;
13161 end else begin
13162 Costs[1]:=(AABBCost(AABB)-AABBCost(fNodes^[Children[1]].AABB))+InheritanceCost;
13163 end;
13164
13165 if (Cost<Costs[0]) and (Cost<Costs[1]) then begin
13166 break;
13167 end else begin
13168 if Costs[0]<Costs[1] then begin
13169 Index:=Children[0];
13170 end else begin
13171 Index:=Children[1];
13172 end;
13173 end;
13174
13175 end;
13176
13177 Sibling:=Index;
13178
13179 OldParent:=fNodes^[Sibling].Parent;
13180 NewParent:=AllocateNode;
13181 fNodes^[NewParent].Parent:=OldParent;
13182 fNodes^[NewParent].UserData:=nil;
13183 fNodes^[NewParent].AABB:=AABBCombine(LeafAABB,fNodes^[Sibling].AABB);
13184 fNodes^[NewParent].Height:=fNodes^[Sibling].Height+1;
13185
13186 if OldParent>=0 then begin
13187 if fNodes^[OldParent].Children[0]=Sibling then begin
13188 fNodes^[OldParent].Children[0]:=NewParent;
13189 end else begin
13190 fNodes^[OldParent].Children[1]:=NewParent;
13191 end;
13192 fNodes^[NewParent].Children[0]:=Sibling;
13193 fNodes^[NewParent].Children[1]:=Leaf;
13194 fNodes^[Sibling].Parent:=NewParent;
13195 fNodes^[Leaf].Parent:=NewParent;
13196 end else begin
13197 fNodes^[NewParent].Children[0]:=Sibling;
13198 fNodes^[NewParent].Children[1]:=Leaf;
13199 fNodes^[Sibling].Parent:=NewParent;
13200 fNodes^[Leaf].Parent:=NewParent;
13201 fRoot:=NewParent;
13202 end;
13203
13204 Index:=fNodes^[Leaf].Parent;
13205 while Index>=0 do begin
13206 Index:=Balance(Index);
13207 Node:=@fNodes^[Index];
13208 Node^.AABB:=AABBCombine(fNodes^[Node^.Children[0]].AABB,fNodes^[Node^.Children[1]].AABB);
13209 Node^.Height:=1+Max(fNodes^[Node^.Children[0]].Height,fNodes^[Node^.Children[1]].Height);
13210 Index:=Node^.Parent;
13211 end;
13212
13213 end;
13214 end;
13215
13216 procedure TKraftDynamicAABBTree.RemoveLeaf(Leaf:longint);
13217 var Node:PKraftDynamicAABBTreeNode;
13218 Parent,GrandParent,Sibling,Index:longint;
13219 begin
13220 if fRoot=Leaf then begin
13221 fRoot:=daabbtNULLNODE;
13222 end else begin
13223 Parent:=fNodes^[Leaf].Parent;
13224 GrandParent:=fNodes^[Parent].Parent;
13225 if fNodes^[Parent].Children[0]=Leaf then begin
13226 Sibling:=fNodes^[Parent].Children[1];
13227 end else begin
13228 Sibling:=fNodes^[Parent].Children[0];
13229 end;
13230 if GrandParent>=0 then begin
13231 if fNodes^[GrandParent].Children[0]=Parent then begin
13232 fNodes^[GrandParent].Children[0]:=Sibling;
13233 end else begin
13234 fNodes^[GrandParent].Children[1]:=Sibling;
13235 end;
13236 fNodes^[Sibling].Parent:=GrandParent;
13237 FreeNode(Parent);
13238 Index:=GrandParent;
13239 while Index>=0 do begin
13240 Index:=Balance(Index);
13241 Node:=@fNodes^[Index];
13242 Node^.AABB:=AABBCombine(fNodes^[Node^.Children[0]].AABB,fNodes^[Node^.Children[1]].AABB);
13243 Node^.Height:=1+Max(fNodes^[Node^.Children[0]].Height,fNodes^[Node^.Children[1]].Height);
13244 Index:=Node^.Parent;
13245 end;
13246 end else begin
13247 fRoot:=Sibling;
13248 fNodes^[Sibling].Parent:=daabbtNULLNODE;
13249 FreeNode(Parent);
13250 end;
13251 end;
13252 end;
13253
13254 function TKraftDynamicAABBTree.CreateProxy(const AABB:TKraftAABB;UserData:pointer):longint;
13255 var Node:PKraftDynamicAABBTreeNode;
13256 begin
13257 result:=AllocateNode;
13258 Node:=@fNodes^[result];
13259 Node^.AABB.Min:=Vector3Sub(AABB.Min,AABBExtensionVector);
13260 Node^.AABB.Max:=Vector3Add(AABB.Max,AABBExtensionVector);
13261 Node^.UserData:=UserData;
13262 Node^.Height:=0;
13263 InsertLeaf(result);
13264 end;
13265
13266 procedure TKraftDynamicAABBTree.DestroyProxy(NodeID:longint);
13267 begin
13268 RemoveLeaf(NodeID);
13269 FreeNode(NodeID);
13270 end;
13271
13272 function TKraftDynamicAABBTree.MoveProxy(NodeID:longint;const AABB:TKraftAABB;const Displacement,BoundsExpansion:TKraftVector3):boolean;
13273 var Node:PKraftDynamicAABBTreeNode;
13274 begin
13275 Node:=@fNodes^[NodeID];
13276 result:=not AABBContains(Node^.AABB,AABB);
13277 if result then begin
13278 RemoveLeaf(NodeID);
13279 Node^.AABB:=AABBStretch(AABB,Displacement,BoundsExpansion);
13280 InsertLeaf(NodeID);
13281 end;
13282 end;
13283
13284 procedure TKraftDynamicAABBTree.Rebalance(Iterations:longint);
13285 var Counter,Node:longint;
13286 Bit:longword;
13287 // Children:PKraftDynamicAABBTreeLongintArray;
13288 begin
13289 if (fRoot>=0) and (fRoot<fNodeCount) then begin
13290 for Counter:=1 to Iterations do begin
13291 Bit:=0;
13292 Node:=fRoot;
13293 while fNodes[Node].Children[0]>=0 do begin
13294 Node:=fNodes[Node].Children[(fPath shr Bit) and 1];
13295 Bit:=(Bit+1) and 31;
13296 end;
13297 inc(fPath);
13298 if ((Node>=0) and (Node<fNodeCount)) and (fNodes[Node].Children[0]<0) then begin
13299 RemoveLeaf(Node);
13300 InsertLeaf(Node);
13301 end else begin
13302 break;
13303 end;
13304 end;
13305 end;
13306 end;
13307
13308 procedure TKraftDynamicAABBTree.Rebuild;
13309 var NewNodes:PKraftDynamicAABBTreeLongintArray;
13310 Children:array[0..1] of PKraftDynamicAABBTreeNode;
13311 Parent:PKraftDynamicAABBTreeNode;
13312 Count,i,j,iMin,jMin,Index1,Index2,ParentIndex:longint;
13313 MinCost,Cost:TKraftScalar;
13314 AABBi,AABBj:PKraftAABB;
13315 AABB:TKraftAABB;
13316 First:boolean;
13317 begin
13318 if fNodeCount>0 then begin
13319 NewNodes:=nil;
13320 GetMem(NewNodes,fNodeCount*SizeOf(longint));
13321 FillChar(NewNodes^,fNodeCount*SizeOf(longint),#0);
13322 Count:=0;
13323 for i:=0 to fNodeCapacity-1 do begin
13324 if fNodes^[i].Height>=0 then begin
13325 if fNodes^[i].Children[0]<0 then begin
13326 fNodes^[i].Parent:=daabbtNULLNODE;
13327 NewNodes^[Count]:=i;
13328 inc(Count);
13329 end else begin
13330 FreeNode(i);
13331 end;
13332 end;
13333 end;
13334 while Count>1 do begin
13335 First:=true;
13336 MinCost:=MAX_SCALAR;
13337 iMin:=-1;
13338 jMin:=-1;
13339 {}/////////////////TOOPTIMIZE///////////////////
13340 {}for i:=0 to Count-1 do begin //
13341 {} AABBi:=@fNodes^[NewNodes^[i]].AABB; //
13342 {} for j:=i+1 to Count-1 do begin //
13343 {} AABBj:=@fNodes^[NewNodes^[j]].AABB; //
13344 {} AABB:=AABBCombine(AABBi^,AABBj^); //
13345 {} Cost:=AABBCost(AABB); //
13346 {} if First or (Cost<MinCost) then begin //
13347 {} First:=false; //
13348 {} MinCost:=Cost; //
13349 {} iMin:=i; //
13350 {} jMin:=j; //
13351 {} end; //
13352 {} end; //
13353 {}end; //
13354 {}/////////////////TOOPTIMIZE///////////////////
13355 Index1:=NewNodes^[iMin];
13356 Index2:=NewNodes^[jMin];
13357 Children[0]:=@fNodes^[Index1];
13358 Children[1]:=@fNodes^[Index2];
13359 ParentIndex:=AllocateNode;
13360 Parent:=@fNodes^[ParentIndex];
13361 Parent^.Children[0]:=Index1;
13362 Parent^.Children[1]:=Index2;
13363 Parent^.Height:=1+Max(Children[0]^.Height,Children[1]^.Height);
13364 Parent^.AABB:=AABBCombine(Children[0]^.AABB,Children[1]^.AABB);
13365 Parent^.Parent:=daabbtNULLNODE;
13366 Children[0]^.Parent:=ParentIndex;
13367 Children[1]^.Parent:=ParentIndex;
13368 NewNodes^[jMin]:=NewNodes^[Count-1];
13369 NewNodes^[iMin]:=ParentIndex;
13370 dec(Count);
13371 end;
13372 fRoot:=NewNodes^[0];
13373 FreeMem(NewNodes);
13374 end;
13375 end;
13376
13377 function TKraftDynamicAABBTree.ComputeHeight:longint;
13378 {$ifdef KraftSingleThreadedUsage}
13379 var LocalStack:PKraftDynamicAABBTreeLongintArray;
13380 LocalStackPointer,NodeID,Height:longint;
13381 Node:PKraftDynamicAABBTreeNode;
13382 begin
13383 result:=0;
13384 if fRoot>=0 then begin
13385 LocalStack:=fStack;
13386 LocalStack^[0]:=fRoot;
13387 LocalStack^[1]:=1;
13388 LocalStackPointer:=2;
13389 while LocalStackPointer>0 do begin
13390 dec(LocalStackPointer,2);
13391 NodeID:=LocalStack^[LocalStackPointer];
13392 Height:=LocalStack^[LocalStackPointer+1];
13393 if result<Height then begin
13394 result:=Height;
13395 end;
13396 if NodeID>=0 then begin
13397 Node:=@fNodes^[NodeID];
13398 if Node^.Children[0]>=0 then begin
13399 if fStackCapacity<=(LocalStackPointer+4) then begin
13400 fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+4);
13401 ReallocMem(fStack,fStackCapacity*SizeOf(longint));
13402 LocalStack:=fStack;
13403 end;
13404 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
13405 LocalStack^[LocalStackPointer+1]:=Height+1;
13406 LocalStack^[LocalStackPointer+2]:=Node^.Children[1];
13407 LocalStack^[LocalStackPointer+3]:=Height+1;
13408 inc(LocalStackPointer,4);
13409 end;
13410 end;
13411 end;
13412 end;
13413 end;
13414 {$else}
13415 var MaximalHeight:longint;
13416 procedure ProcessNode(const NodeID,Height:longint);
13417 var Node:PKraftDynamicAABBTreeNode;
13418 begin
13419 if result<Height then begin
13420 result:=Height;
13421 end;
13422 if NodeID>=0 then begin
13423 Node:=@fNodes^[NodeID];
13424 ProcessNode(Node^.Children[0],Height+1);
13425 ProcessNode(Node^.Children[1],Height+1);
13426 end;
13427 end;
13428 begin
13429 MaximalHeight:=0;
13430 ProcessNode(fRoot,1);
13431 result:=MaximalHeight;
13432 end;
13433 {$endif}
13434
13435 function TKraftDynamicAABBTree.GetHeight:longint;
13436 begin
13437 if fRoot>=0 then begin
13438 result:=fNodes[fRoot].Height;
13439 end else begin
13440 result:=0;
13441 end;
13442 end;
13443
13444 function TKraftDynamicAABBTree.GetAreaRatio:TKraftScalar;
13445 var NodeID:longint;
13446 Node:PKraftDynamicAABBTreeNode;
13447 begin
13448 result:=0;
13449 if fRoot>=0 then begin
13450 for NodeID:=0 to fNodeCount-1 do begin
13451 Node:=@fNodes[NodeID];
13452 if Node^.Height>=0 then begin
13453 result:=result+AABBCost(Node^.AABB);
13454 end;
13455 end;
13456 result:=result/AABBCost(fNodes[fRoot].AABB);
13457 end;
13458 end;
13459
13460 function TKraftDynamicAABBTree.GetMaxBalance:longint;
13461 var NodeID,Balance:longint;
13462 Node:PKraftDynamicAABBTreeNode;
13463 begin
13464 result:=0;
13465 for NodeID:=0 to fNodeCount-1 do begin
13466 Node:=@fNodes[NodeID];
13467 if (Node^.Height>1) and (Node^.Children[0]>=0) then begin
13468 Balance:=abs(fNodes[Node^.Children[1]].Height-fNodes[Node^.Children[0]].Height);
13469 if result<Balance then begin
13470 result:=Balance;
13471 end;
13472 end;
13473 end;
13474 end;
13475
13476 function TKraftDynamicAABBTree.ValidateStructure:boolean;
13477 {$ifdef KraftSingleThreadedUsage}
13478 var LocalStack:PKraftDynamicAABBTreeLongintArray;
13479 LocalStackPointer,NodeID,Parent:longint;
13480 Node:PKraftDynamicAABBTreeNode;
13481 begin
13482 result:=true;
13483 if fRoot>=0 then begin
13484 LocalStack:=fStack;
13485 LocalStack^[0]:=fRoot;
13486 LocalStack^[1]:=-1;
13487 LocalStackPointer:=2;
13488 while LocalStackPointer>0 do begin
13489 dec(LocalStackPointer,2);
13490 NodeID:=LocalStack^[LocalStackPointer];
13491 Parent:=LocalStack^[LocalStackPointer+1];
13492 if (NodeID>=0) and (NodeID<fNodeCount) then begin
13493 Node:=@fNodes^[NodeID];
13494 if Node^.Parent<>Parent then begin
13495 result:=false;
13496 break;
13497 end;
13498 if Node^.Children[0]<0 then begin
13499 if (Node^.Children[1]>=0) or (Node^.Height<>0) then begin
13500 result:=false;
13501 break;
13502 end;
13503 end else begin
13504 if fStackCapacity<=(LocalStackPointer+4) then begin
13505 fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+4);
13506 ReallocMem(fStack,fStackCapacity*SizeOf(longint));
13507 LocalStack:=fStack;
13508 end;
13509 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
13510 LocalStack^[LocalStackPointer+1]:=NodeID;
13511 LocalStack^[LocalStackPointer+2]:=Node^.Children[1];
13512 LocalStack^[LocalStackPointer+3]:=NodeID;
13513 inc(LocalStackPointer,4);
13514 end;
13515 end else begin
13516 result:=false;
13517 break;
13518 end;
13519 end;
13520 end;
13521 end;
13522 {$else}
13523 var OK:boolean;
13524 procedure ProcessNode(const NodeID,Parent:longint);
13525 var Node:PKraftDynamicAABBTreeNode;
13526 begin
13527 if (NodeID>=0) and (NodeID<fNodeCount) and OK then begin
13528 Node:=@fNodes^[NodeID];
13529 if Node^.Parent<>Parent then begin
13530 OK:=false;
13531 end else begin
13532 ProcessNode(Node^.Children[0],NodeID);
13533 ProcessNode(Node^.Children[1],NodeID);
13534 end;
13535 end;
13536 end;
13537 begin
13538 OK:=true;
13539 ProcessNode(fRoot,-1);
13540 result:=OK;
13541 end;
13542 {$endif}
13543
13544 function TKraftDynamicAABBTree.ValidateMetrics:boolean;
13545 {$ifdef KraftSingleThreadedUsage}
13546 var LocalStack:PKraftDynamicAABBTreeLongintArray;
13547 LocalStackPointer,NodeID{,Height}:longint;
13548 Node:PKraftDynamicAABBTreeNode;
13549 AABB:TKraftAABB;
13550 begin
13551 result:=true;
13552 if fRoot>=0 then begin
13553 LocalStack:=fStack;
13554 LocalStack^[0]:=fRoot;
13555 LocalStackPointer:=1;
13556 while LocalStackPointer>0 do begin
13557 dec(LocalStackPointer);
13558 NodeID:=LocalStack^[LocalStackPointer];
13559 if (NodeID>=0) and (NodeID<fNodeCount) then begin
13560 Node:=@fNodes^[NodeID];
13561 if Node^.Children[0]>=0 then begin
13562 if (((Node^.Children[0]<0) or (Node^.Children[0]>=fNodeCount)) or
13563 ((Node^.Children[1]<0) or (Node^.Children[1]>=fNodeCount))) or
13564 (Node^.Height<>(1+Max(fNodes[Node^.Children[0]].Height,fNodes[Node^.Children[1]].Height))) then begin
13565 result:=false;
13566 break;
13567 end;
13568 AABB:=AABBCombine(fNodes[Node^.Children[0]].AABB,fNodes[Node^.Children[1]].AABB);
13569 if not (Vector3Compare(Node^.AABB.Min,AABB.Min) and Vector3Compare(Node^.AABB.Max,AABB.Max)) then begin
13570 result:=false;
13571 break;
13572 end;
13573 if fStackCapacity<=(LocalStackPointer+2) then begin
13574 fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+2);
13575 ReallocMem(fStack,fStackCapacity*SizeOf(longint));
13576 LocalStack:=fStack;
13577 end;
13578 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
13579 LocalStack^[LocalStackPointer+1]:=Node^.Children[1];
13580 inc(LocalStackPointer,2);
13581 end;
13582 end else begin
13583 result:=false;
13584 break;
13585 end;
13586 end;
13587 end;
13588 end;
13589 {$else}
13590 var OK:boolean;
13591 procedure ProcessNode(const NodeID:longint);
13592 var Node:PKraftDynamicAABBTreeNode;
13593 begin
13594 if (NodeID>=0) and OK then begin
13595 Node:=@fNodes^[NodeID];
13596 if (((Node^.Children[0]<0) or (Node^.Children[0]>=fNodeCount)) or
13597 ((Node^.Children[1]<0) or (Node^.Children[1]>=fNodeCount))) or
13598 (Node^.Height<>(1+Max(fNodes[Node^.Children[0]].Height,fNodes[Node^.Children[1]].Height))) then begin
13599 OK:=false;
13600 end else begin
13601 ProcessNode(Node^.Children[0]);
13602 ProcessNode(Node^.Children[1]);
13603 end;
13604 end;
13605 end;
13606 begin
13607 OK:=true;
13608 ProcessNode(fRoot);
13609 result:=OK;
13610 end;
13611 {$endif}
13612
13613 function TKraftDynamicAABBTree.Validate:boolean;
13614 var NodeID,FreeCount:longint;
13615 begin
13616 result:=ValidateStructure;
13617 if result then begin
13618 result:=ValidateMetrics;
13619 if result then begin
13620 result:=ComputeHeight=GetHeight;
13621 if result then begin
13622 NodeID:=fFreeList;
13623 FreeCount:=0;
13624 while NodeID>=0 do begin
13625 NodeID:=fNodes[NodeID].Next;
13626 inc(FreeCount);
13627 end;
13628 result:=(fNodeCount+FreeCount)=fNodeCapacity;
13629 end;
13630 end;
13631 end;
13632 end;
13633
13634 function TKraftDynamicAABBTree.GetIntersectionProxy(const AABB:TKraftAABB):pointer;
13635 {$ifdef KraftSingleThreadedUsage}
13636 var LocalStack:PKraftDynamicAABBTreeLongintArray;
13637 LocalStackPointer,NodeID:longint;
13638 Node:PKraftDynamicAABBTreeNode;
13639 begin
13640 result:=nil;
13641 if fRoot>=0 then begin
13642 LocalStack:=fStack;
13643 LocalStack^[0]:=fRoot;
13644 LocalStackPointer:=1;
13645 while LocalStackPointer>0 do begin
13646 dec(LocalStackPointer);
13647 NodeID:=LocalStack^[LocalStackPointer];
13648 if NodeID>=0 then begin
13649 Node:=@fNodes[NodeID];
13650 if AABBIntersect(Node^.AABB,AABB) then begin
13651 if Node^.Children[0]<0 then begin
13652 result:=Node^.UserData;
13653 exit;
13654 end else begin
13655 if fStackCapacity<=(LocalStackPointer+2) then begin
13656 fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+2);
13657 ReallocMem(fStack,fStackCapacity*SizeOf(longint));
13658 LocalStack:=fStack;
13659 end;
13660 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
13661 LocalStack^[LocalStackPointer+1]:=Node^.Children[1];
13662 inc(LocalStackPointer,2);
13663 end;
13664 end;
13665 end;
13666 end;
13667 end;
13668 end;
13669 {$else}
13670 var Data:pointer;
13671 Done:boolean;
13672 procedure ProcessNode(const NodeID:longint);
13673 var Node:PKraftDynamicAABBTreeNode;
13674 begin
13675 if (NodeID>=0) and not Done then begin
13676 Node:=@fNodes^[NodeID];
13677 if AABBIntersect(Node^.AABB,AABB) then begin
13678 if Node^.Children[0]<0 then begin
13679 Data:=Node^.UserData;
13680 Done:=true;
13681 end else begin
13682 ProcessNode(Node^.Children[0]);
13683 ProcessNode(Node^.Children[1]);
13684 end;
13685 end;
13686 end;
13687 end;
13688 begin
13689 Data:=nil;
13690 Done:=false;
13691 ProcessNode(fRoot);
13692 result:=Data;
13693 end;
13694 {$endif}
13695
13696 type PConvexHullVector=^TConvexHullVector;
13697 TConvexHullVector=record
13698 x,y,z:double;
13699 HashNext:longint;
13700 end;
13701
13702 TConvexHullVectors=array of TConvexHullVector;
13703
13704 PConvexHullTriangle=^TConvexHullTriangle;
13705 TConvexHullTriangle=array[0..2] of longint;
13706
13707 TConvexHullTriangles=array of TConvexHullTriangle;
13708
13709 PConvexHullPlane=^TConvexHullPlane;
13710 TConvexHullPlane=record
13711 Normal:TConvexHullVector;
13712 Distance:double;
13713 end;
13714
13715 TConvexHullPlanes=array of TConvexHullPlane;
13716
13717 PConvexHullPolygon=^TConvexHullPolygon;
13718 TConvexHullPolygon=record
13719 Indices:array of longint;
13720 Count:longint;
13721 Plane:TConvexHullPlane;
13722 end;
13723
13724 TConvexHullPolygons=record
13725 Items:array of TConvexHullPolygon;
13726 Count:longint;
13727 end;
13728
13729 function CompareConvexHullPoints(const a,b:pointer):longint;
13730 function IsSameValue(const a,b:double):boolean;
13731 const FuzzFactor=1000;
13732 DoubleResolution=1e-15*FuzzFactor;
13733 var EpsilonTolerance:double;
13734 begin
13735 EpsilonTolerance:=abs(a);
13736 if EpsilonTolerance>abs(b) then begin
13737 EpsilonTolerance:=abs(b);
13738 end;
13739 EpsilonTolerance:=EpsilonTolerance*DoubleResolution;
13740 if EpsilonTolerance<DoubleResolution then begin
13741 EpsilonTolerance:=DoubleResolution;
13742 end;
13743 if a>b then begin
13744 result:=(a-b)<=EpsilonTolerance;
13745 end else begin
13746 result:=(b-a)<=EpsilonTolerance;
13747 end;
13748 end;
13749 var va,vb:PConvexHullVector;
13750 begin
13751 va:=a;
13752 vb:=b;
13753 if (IsSameValue(va^.x,vb^.x) and ((IsSameValue(va^.y,vb^.y) and (va^.z>vb^.z)) or (va^.y>vb^.y))) or (va^.x>vb^.x) then begin
13754 result:=-1;
13755 end else if (IsSameValue(va^.x,vb^.x) and ((IsSameValue(va^.y,vb^.y) and (va^.z<vb^.z)) or (va^.y<vb^.y))) or (va^.x<vb^.x) then begin
13756 result:=1;
13757 end else begin
13758 result:=0;
13759 end;
13760 end;
13761
13762 function ConvexHullIsSameValue(const a,b:double):boolean;
13763 const FuzzFactor=1000;
13764 DoubleResolution=1e-15*FuzzFactor;
13765 var EpsilonTolerance:double;
13766 begin
13767 EpsilonTolerance:=abs(a);
13768 if EpsilonTolerance>abs(b) then begin
13769 EpsilonTolerance:=abs(b);
13770 end;
13771 EpsilonTolerance:=EpsilonTolerance*DoubleResolution;
13772 if EpsilonTolerance<DoubleResolution then begin
13773 EpsilonTolerance:=DoubleResolution;
13774 end;
13775 if a>b then begin
13776 result:=(a-b)<=EpsilonTolerance;
13777 end else begin
13778 result:=(b-a)<=EpsilonTolerance;
13779 end;
13780 end;
13781
13782 function ConvexHullVectorCompare(const v1,v2:TConvexHullVector):boolean;
13783 begin
13784 result:=ConvexHullIsSameValue(v1.x,v2.x) and ConvexHullIsSameValue(v1.y,v2.y) and ConvexHullIsSameValue(v1.z,v2.z);
13785 end;
13786
13787 function ConvexHullVectorNeg(const v:TConvexHullVector):TConvexHullVector;
13788 begin
13789 result.x:=-v.x;
13790 result.y:=-v.y;
13791 result.z:=-v.z;
13792 end;
13793
13794 function ConvexHullVectorSub(const v1,v2:TConvexHullVector):TConvexHullVector;
13795 begin
13796 result.x:=v1.x-v2.x;
13797 result.y:=v1.y-v2.y;
13798 result.z:=v1.z-v2.z;
13799 end;
13800
13801 function ConvexHullVectorAdd(const v1,v2:TConvexHullVector):TConvexHullVector;
13802 begin
13803 result.x:=v1.x+v2.x;
13804 result.y:=v1.y+v2.y;
13805 result.z:=v1.z+v2.z;
13806 end;
13807
13808 function ConvexHullVectorCross(const v1,v2:TConvexHullVector):TConvexHullVector;
13809 begin
13810 result.x:=(v1.y*v2.z)-(v1.z*v2.y);
13811 result.y:=(v1.z*v2.x)-(v1.x*v2.z);
13812 result.z:=(v1.x*v2.y)-(v1.y*v2.x);
13813 end;
13814
13815 function ConvexHullVectorScale(const v:TConvexHullVector;const Scale:double):TConvexHullVector;
13816 begin
13817 result.x:=v.x*Scale;
13818 result.y:=v.y*Scale;
13819 result.z:=v.z*Scale;
13820 end;
13821
13822 function ConvexHullVectorDivide(const v:TConvexHullVector;const Divisor:double):TConvexHullVector;
13823 begin
13824 result.x:=v.x/Divisor;
13825 result.y:=v.y/Divisor;
13826 result.z:=v.z/Divisor;
13827 end;
13828
13829 function ConvexHullVectorLengthSquared(const v:TConvexHullVector):double;
13830 begin
13831 result:=sqr(v.x)+sqr(v.y)+sqr(v.z);
13832 end;
13833
13834 function ConvexHullVectorLength(const v:TConvexHullVector):double;
13835 begin
13836 result:=sqrt(sqr(v.x)+sqr(v.y)+sqr(v.z));
13837 end;
13838
13839 function ConvexHullVectorDot(const v1,v2:TConvexHullVector):double;
13840 begin
13841 result:=(v1.x*v2.x)+(v1.y*v2.y)+(v1.z*v2.z);
13842 end;
13843
13844 function ConvexHullVectorNormalize(const v:TConvexHullVector):TConvexHullVector;
13845 var l:double;
13846 begin
13847 l:=sqr(v.x)+sqr(v.y)+sqr(v.z);
13848 if l>EPSILON then begin
13849 l:=sqrt(l);
13850 result.x:=v.x/l;
13851 result.y:=v.y/l;
13852 result.z:=v.z/l;
13853 end else begin
13854 result.x:=0.0;
13855 result.y:=1.0;
13856 result.z:=0.0;
13857 end;
13858 end;
13859
13860 function ConvexHullVectorLerp(const v1,v2:TConvexHullVector;const w:double):TConvexHullVector;
13861 var iw:double;
13862 begin
13863 if w<0.0 then begin
13864 result:=v1;
13865 end else if w>1.0 then begin
13866 result:=v2;
13867 end else begin
13868 iw:=1.0-w;
13869 result.x:=(iw*v1.x)+(w*v2.x);
13870 result.y:=(iw*v1.y)+(w*v2.y);
13871 result.z:=(iw*v1.z)+(w*v2.z);
13872 end;
13873 end;
13874
13875 procedure ConvexHullGetPlaneSpace(const n:TConvexHullVector;var p,q:TConvexHullVector); {$ifdef caninline}inline;{$endif}
13876 var a,k:double;
13877 begin
13878 if abs(n.z)>0.70710678118 then begin
13879 a:=sqr(n.y)+sqr(n.z);
13880 k:=1.0/sqrt(a);
13881 p.x:=0.0;
13882 p.y:=-(n.z*k);
13883 p.z:=n.y*k;
13884 q.x:=a*k;
13885 q.y:=-(n.x*p.z);
13886 q.z:=n.x*p.y;
13887 end else begin
13888 a:=sqr(n.x)+sqr(n.y);
13889 k:=1.0/sqrt(a);
13890 p.x:=-(n.y*k);
13891 p.y:=n.x*k;
13892 p.z:=0.0;
13893 q.x:=-(n.z*p.y);
13894 q.y:=n.z*p.x;
13895 q.z:=a*k;
13896 end;
13897 end;
13898
13899 function ConvexHullCalculateArea(const v0,v1,v2:TConvexHullVector):double;
13900 begin
13901 result:=ConvexHullVectorLengthSquared(ConvexHullVectorCross(ConvexHullVectorSub(v1,v0),ConvexHullVectorSub(v2,v0)));
13902 end;
13903
13904 function ConvexHullCalculateVolume(const v0,v1,v2,v3:TConvexHullVector):double;
13905 var a,b,c:TConvexHullVector;
13906 begin
13907 a:=ConvexHullVectorSub(v0,v3);
13908 b:=ConvexHullVectorSub(v1,v3);
13909 c:=ConvexHullVectorSub(v2,v3);
13910 result:=(a.x*((b.z*c.y)-(b.y*c.z)))+(a.y*((b.x*c.z)-(b.z*c.x)))+(a.z*((b.y*c.x)-(b.x*c.y)));
13911 end;
13912
13913 procedure ConvexHullComputePolygonNewellPlane(const Vertices:TConvexHullVectors;var Polygon:TConvexHullPolygon);
13914 var VertexIndex:longint;
13915 Last,Current:PConvexHullVector;
13916 Plane:PConvexHullPlane;
13917 Centroid,Normal:TConvexHullVector;
13918 begin
13919 if Polygon.Count>0 then begin
13920 Centroid.x:=0.0;
13921 Centroid.y:=0.0;
13922 Centroid.z:=0.0;
13923 Normal.x:=0.0;
13924 Normal.y:=0.0;
13925 Normal.z:=0.0;
13926 Last:=@Vertices[Polygon.Indices[Polygon.Count-1]];
13927 for VertexIndex:=0 to Polygon.Count-1 do begin
13928 Current:=@Vertices[Polygon.Indices[VertexIndex]];
13929 Normal.x:=Normal.x+((Last^.y-Current^.y)*(Last^.z+Current^.z));
13930 Normal.y:=Normal.y+((Last^.z-Current^.z)*(Last^.x+Current^.x));
13931 Normal.z:=Normal.z+((Last^.x-Current^.x)*(Last^.y+Current^.y));
13932 Centroid.x:=Centroid.x+Current^.x;
13933 Centroid.y:=Centroid.y+Current^.y;
13934 Centroid.z:=Centroid.z+Current^.z;
13935 Last:=Current;
13936 end;
13937 if ConvexHullIsSameValue(Normal.x,0.0) and ConvexHullIsSameValue(Normal.y,0.0) and ConvexHullIsSameValue(Normal.z,0.0) then begin
13938 Normal.x:=0.0;
13939 Normal.y:=1.0;
13940 Normal.z:=0.0;
13941 end;
13942 Plane:[email protected];
13943 Plane^.Normal:=ConvexHullVectorNormalize(Normal);
13944 Plane^.Distance:=-ConvexHullVectorDot(Plane^.Normal,ConvexHullVectorDivide(Centroid,Polygon.Count));
13945 end else begin
13946 Plane:[email protected];
13947 Plane^.Normal.x:=0.0;
13948 Plane^.Normal.y:=0.0;
13949 Plane^.Normal.z:=0.0;
13950 Plane^.Distance:=0.0;
13951 end;
13952 end;
13953
13954 function StanHullProcess(var Points:TConvexHullVectors;var OutTriangles:TConvexHullTriangles;const MaximumOutputPoints:longint=-1;const UserDefinedTolerance:double=-1.0):boolean;
13955 const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
13956 DOUBLE_PREC:double=2.2204460492503131e-16;
13957 EPSILON=1e-10;
13958 type PInt3=^TInt3;
13959 TInt3=array[0..2] of longint;
13960 TInt3s=array of TInt3;
13961 PInt4=^TInt4;
13962 TInt4=array[0..3] of longint;
13963 PTri=^TTri;
13964 TTri=record
13965 v:TInt3;
13966 n:TInt3;
13967 ID:longint;
13968 vmax:longint;
13969 Rise:double;
13970 end;
13971 TTris=array of TTri;
13972 var CountPoints:longint;
13973 MinPoint,MaxPoint:TConvexHullVector;
13974 Tolerance:double;
13975 function Roll3(const a:TInt3):TInt3;
13976 begin
13977 result[0]:=a[1];
13978 result[1]:=a[2];
13979 result[2]:=a[0];
13980 end;
13981 function Equal3(const a,b:TInt3):boolean;
13982 begin
13983 result:=((a[0]=b[0]) and (a[1]=b[1]) and (a[2]=b[2]));
13984 end;
13985 function IsA(const a,b:TInt3):boolean;
13986 begin
13987 result:=Equal3(a,b) or Equal3(Roll3(a),b) or Equal3(a,Roll3(b));
13988 end;
13989 function B2B(const a,b:TInt3):boolean;
13990 var c:TInt3;
13991 begin
13992 c[0]:=b[2];
13993 c[1]:=b[1];
13994 c[2]:=b[0];
13995 result:=IsA(a,c);
13996 end;
13997 function TriNormal(const v0,v1,v2:TConvexHullVector):TConvexHullVector;
13998 var cp:TConvexHullVector;
13999 m:double;
14000 begin
14001 cp:=ConvexHullVectorCross(ConvexHullVectorSub(v1,v0),ConvexHullVectorSub(v2,v0));
14002 m:=ConvexHullVectorLength(cp);
14003 if m=0.0 then begin
14004 result.x:=0.0;
14005 result.y:=0.0;
14006 result.z:=1.0;
14007 end else begin
14008 result.x:=cp.x/m;
14009 result.y:=cp.y/m;
14010 result.z:=cp.z/m;
14011 end;
14012 end;
14013 function Above(const Vertices:TConvexHullVectors;const t:TInt3;const p:TConvexHullVector;const Epsilon:double):boolean;
14014 var n:TConvexHullVector;
14015 begin
14016 n:=TriNormal(Vertices[t[0]],Vertices[t[1]],Vertices[t[2]]);
14017 result:=ConvexHullVectorDot(n,ConvexHullVectorSub(p,Vertices[t[0]]))>Epsilon;
14018 end;
14019 function HasEdges(const t:TInt3;const a,b:longint):boolean;
14020 var i,i1:longint;
14021 begin
14022 for i:=0 to 2 do begin
14023 i1:=ModuloThree[i+1];
14024 if (t[i]=a) and (t[i1]=b) then begin
14025 result:=true;
14026 exit;
14027 end;
14028 end;
14029 result:=false;
14030 end;
14031 function HasVertex(const t:TInt3;const v:longint):boolean;
14032 begin
14033 result:=(t[0]=v) or (t[1]=v) or (t[2]=v);
14034 end;
14035 function HasSharedEdge(const a,b:TInt3):boolean;
14036 var i,i1:longint;
14037 begin
14038 for i:=0 to 2 do begin
14039 i1:=ModuloThree[i+1];
14040 if HasEdges(a,b[i1],b[i]) then begin
14041 result:=true;
14042 exit;
14043 end;
14044 end;
14045 result:=false;
14046 end;
14047 function Tri(const a,b,c,id:longint;const na:longint=-1;const nb:longint=-1;const nc:longint=-1):TTri;
14048 begin
14049 FillChar(result,SizeOf(TTri),#0);
14050 result.v[0]:=a;
14051 result.v[1]:=b;
14052 result.v[2]:=c;
14053 result.n[0]:=na;
14054 result.n[1]:=nb;
14055 result.n[2]:=nc;
14056 result.ID:=ID;
14057 result.vmax:=-1;
14058 result.Rise:=0.0;
14059 end;
14060 function TriDead(const Tri:TTri):boolean;
14061 begin
14062 result:=Tri.n[0]<0;
14063 end;
14064 function TriNEIB(const Tri:TTri;const va,vb:longint):plongint;
14065 var i,i1,i2:longint;
14066 begin
14067 for i:=0 to 2 do begin
14068 i1:=ModuloThree[i+1];
14069 i2:=ModuloThree[i+2];
14070 if (Tri.v[i]=va) and (Tri.v[i1]=vb) then begin
14071 result:[email protected][i2];
14072 exit;
14073 end;
14074 if (Tri.v[i]=vb) and (Tri.v[i1]=va) then begin
14075 result:[email protected][i2];
14076 exit;
14077 end;
14078 end;
14079 result:=nil;
14080 raise EKraftDegeneratedConvexHull.Create('Degenerated convex hull');
14081 end;
14082 procedure NNFix(var Tris:TTris;const CountTris,k:longint);
14083 var i,i1,i2:longint;
14084 nn:plongint;
14085 begin
14086 if Tris[k].ID>=0 then begin
14087 Assert(Tris[k].ID=k);
14088 for i:=0 to 2 do begin
14089 i1:=ModuloThree[i+1];
14090 i2:=ModuloThree[i+2];
14091 if Tris[k].n[i]>=0 then begin
14092 nn:=TriNEIB(Tris[Tris[k].n[i]],Tris[k].v[i2],Tris[k].v[i1]);
14093 nn^:=k;
14094 end;
14095 end;
14096 end;
14097 end;
14098 procedure SwapN(var Tris:TTris;const CountTris,a,b:longint);
14099 var TempTri:TTri;
14100 TempID:longint;
14101 begin
14102 TempTri:=Tris[a];
14103 Tris[a]:=Tris[b];
14104 Tris[b]:=TempTri;
14105 TempID:=Tris[a].ID;
14106 Tris[a].ID:=Tris[b].ID;
14107 Tris[b].ID:=TempID;
14108 NNFix(Tris,CountTris,a);
14109 NNFix(Tris,CountTris,b);
14110 end;
14111 procedure B2BFix(var Tris:TTris;const CountTris,s,t:longint);
14112 var i,i1,i2,va,vb:longint;
14113 begin
14114 for i:=0 to 2 do begin
14115 i1:=ModuloThree[i+1];
14116 i2:=ModuloThree[i+2];
14117 va:=Tris[s].v[i1];
14118 vb:=Tris[s].v[i2];
14119 Assert(TriNEIB(Tris[TriNEIB(Tris[s],va,vb)^],vb,va)^=Tris[s].ID);
14120 Assert(TriNEIB(Tris[TriNEIB(Tris[t],va,vb)^],vb,va)^=Tris[t].ID);
14121 TriNEIB(Tris[TriNEIB(Tris[s],va,vb)^],vb,va)^:=TriNEIB(Tris[t],vb,va)^;
14122 TriNEIB(Tris[TriNEIB(Tris[t],vb,va)^],va,vb)^:=TriNEIB(Tris[s],va,vb)^;
14123 end;
14124 Tris[s].n[0]:=-1;
14125 Tris[s].n[1]:=-1;
14126 Tris[s].n[2]:=-1;
14127 Tris[t].n[0]:=-1;
14128 Tris[t].n[1]:=-1;
14129 Tris[t].n[2]:=-1;
14130 end;
14131 procedure CheckIt(const Tris:TTris;const CountTris:longint;const t:TTri);
14132 var i,i1,i2,a,b:longint;
14133 begin
14134 Assert(Tris[t.ID].ID=t.ID);
14135 Assert(@Tris[t.ID]=@t);
14136 for i:=0 to 2 do begin
14137 i1:=ModuloThree[i+1];
14138 i2:=ModuloThree[i+2];
14139 a:=t.v[i1];
14140 b:=t.v[i2];
14141 Assert(a<>b);
14142 Assert(TriNEIB(Tris[t.n[i]],b,a)^=t.ID);
14143 end;
14144 end;
14145 function Extrudable(const Tris:TTris;const CountTris:longint;const Epsilon:double):longint;
14146 var t,i:longint;
14147 begin
14148 t:=-1;
14149 for i:=0 to CountTris-1 do begin
14150 Assert(Tris[i].ID>=0);
14151 Assert(Tris[i].ID=i);
14152 Assert(not TriDead(Tris[i]));
14153 if (t<0) or (Tris[t].Rise<Tris[i].Rise) then begin
14154 t:=i;
14155 end;
14156 end;
14157 if Tris[t].Rise>Epsilon then begin
14158 result:=t;
14159 end else begin
14160 result:=-1;
14161 end;
14162 end;
14163 function MaxDir(const Vertices:TConvexHullVectors;const CountVertices:longint;const Direction:TConvexHullVector):longint;
14164 var i:longint;
14165 Best,Current:double;
14166 begin
14167 result:=-1;
14168 Best:=-3.4e+28;
14169 for i:=0 to CountVertices-1 do begin
14170 Current:=ConvexHullVectorDot(Direction,Vertices[i]);
14171 if (i=0) or (Best<Current) then begin
14172 result:=i;
14173 Best:=Current;
14174 end;
14175 end;
14176 end;
14177 function FindSimplex(const Vertices:TConvexHullVectors;const CountVertices:longint):TInt4;
14178 const v000:TConvexHullVector=(x:0.0;y:0.0;z:0.0);
14179 v100:TConvexHullVector=(x:1.0;y:0.0;z:0.0);
14180 v010:TConvexHullVector=(x:0.0;y:1.0;z:0.0);
14181 var p0,p1,p2,p3,TempIndex:longint;
14182 Basis:array[0..2] of TConvexHullVector;
14183 begin
14184 Basis[0].x:=0.01;
14185 Basis[0].y:=0.02;
14186 Basis[0].z:=1.0;
14187 p0:=MaxDir(Vertices,CountVertices,Basis[0]);
14188 p1:=MaxDir(Vertices,CountVertices,ConvexHullVectorNeg(Basis[0]));
14189 Basis[0]:=ConvexHullVectorSub(Vertices[p0],Vertices[p1]);
14190 if (p0=p1) or ConvexHullVectorCompare(Basis[0],v000) then begin
14191 result[0]:=-1;
14192 result[1]:=-1;
14193 result[2]:=-1;
14194 result[3]:=-1;
14195 exit;
14196 end;
14197 Basis[1]:=ConvexHullVectorCross(v100,Basis[0]);
14198 Basis[2]:=ConvexHullVectorCross(v010,Basis[0]);
14199 if ConvexHullVectorLengthSquared(Basis[1])>ConvexHullVectorLengthSquared(Basis[2]) then begin
14200 Basis[1]:=ConvexHullVectorNormalize(Basis[1]);
14201 end else begin
14202 Basis[1]:=ConvexHullVectorNormalize(Basis[2]);
14203 end;
14204 p2:=MaxDir(Vertices,CountVertices,Basis[1]);
14205 if (p2=p0) or (p2=p1) then begin
14206 p2:=MaxDir(Vertices,CountVertices,ConvexHullVectorNeg(Basis[1]));
14207 if (p2=p0) or (p2=p1) then begin
14208 result[0]:=-1;
14209 result[1]:=-1;
14210 result[2]:=-1;
14211 result[3]:=-1;
14212 exit;
14213 end;
14214 end;
14215 Basis[1]:=ConvexHullVectorSub(Vertices[p2],Vertices[p0]);
14216 Basis[2]:=ConvexHullVectorCross(Basis[1],Basis[0]);
14217 p3:=MaxDir(Vertices,CountVertices,Basis[2]);
14218 if (p3=p0) or (p3=p1) or (p3=p2) then begin
14219 p3:=MaxDir(Vertices,CountVertices,ConvexHullVectorNeg(Basis[2]));
14220 if (p3=p0) or (p3=p1) or (p3=p2) then begin
14221 result[0]:=-1;
14222 result[1]:=-1;
14223 result[2]:=-1;
14224 result[3]:=-1;
14225 exit;
14226 end;
14227 end;
14228 Assert(not ((p0=p1) or (p0=p2) or (p0=p3) or (p1=p2) or (p1=p3) or (p2=p3)));
14229 if ConvexHullVectorDot(ConvexHullVectorSub(Vertices[p3],Vertices[p0]),
14230 ConvexHullVectorCross(ConvexHullVectorSub(Vertices[p1],Vertices[p0]),
14231 ConvexHullVectorSub(Vertices[p2],Vertices[p0])))<0.0 then begin
14232 TempIndex:=p2;
14233 p2:=p3;
14234 p3:=TempIndex;
14235 end;
14236 result[0]:=p0;
14237 result[1]:=p1;
14238 result[2]:=p2;
14239 result[3]:=p3;
14240 end;
14241 {$warnings off}
14242 function CalcHull(const Vertices:TConvexHullVectors;var CountVertices:longint;VerticesLimit:longint):TInt3s;
14243 var bmin,bmax,Center,n,TempVertex:TConvexHullVector;
14244 isextreme:array of boolean;
14245 CountTris,i,j,k,te,v,{NewStart,}nb:longint;
14246 Epsilon:double;
14247 {ti,}t,nt:TInt3;
14248 p:TInt4;
14249 Tris:TTris;
14250 tt:PTri;
14251 {TempTri:TTri;}
14252 Map,Used:array of longint;
14253 procedure TrisPushBack(const NewTri:TTri);
14254 begin
14255 if (CountTris+1)>=length(Tris) then begin
14256 SetLength(Tris,(CountTris+1)*2);
14257 end;
14258 Tris[CountTris]:=NewTri;
14259 inc(CountTris);
14260 end;
14261 procedure Extrude(const t0,v:longint);
14262 var t,n:TInt3;
14263 b:longint;
14264 begin
14265 t:=Tris[t0].v;
14266 b:=CountTris;
14267 n:=Tris[t0].n;
14268 TrisPushBack(Tri(v,t[1],t[2],b+0,n[0],b+1,b+2));
14269 TriNEIB(Tris[n[0]],t[1],t[2])^:=b+0;
14270 TrisPushBack(Tri(v,t[2],t[0],b+1,n[1],b+2,b+0));
14271 TriNEIB(Tris[n[1]],t[2],t[0])^:=b+1;
14272 TrisPushBack(Tri(v,t[0],t[1],b+2,n[2],b+0,b+1));
14273 TriNEIB(Tris[n[2]],t[0],t[1])^:=b+2;
14274 Tris[t0].n[0]:=-1;
14275 Tris[t0].n[1]:=-1;
14276 Tris[t0].n[2]:=-1;
14277 CheckIt(Tris,CountTris,Tris[b+0]);
14278 CheckIt(Tris,CountTris,Tris[b+1]);
14279 CheckIt(Tris,CountTris,Tris[b+2]);
14280 if HasVertex(Tris[n[0]].v,v) then begin
14281 B2BFix(Tris,CountTris,b+0,n[0]);
14282 end;
14283 if HasVertex(Tris[n[1]].v,v) then begin
14284 B2BFix(Tris,CountTris,b+1,n[1]);
14285 end;
14286 if HasVertex(Tris[n[2]].v,v) then begin
14287 B2BFix(Tris,CountTris,b+2,n[2]);
14288 end;
14289 end;
14290 begin
14291 result:=nil;
14292 isextreme:=nil;
14293 Tris:=nil;
14294 CountTris:=0;
14295 Map:=nil;
14296 Used:=nil;
14297 if CountVertices<4 then begin
14298 exit;
14299 end;
14300 try
14301 if VerticesLimit<1 then begin
14302 VerticesLimit:=1000000000;
14303 end;
14304 try
14305 SetLength(isextreme,CountVertices);
14306 bmin:=Vertices[0];
14307 bmax:=Vertices[0];
14308 for j:=0 to CountVertices-1 do begin
14309 isextreme[j]:=false;
14310 bmin.x:=Min(bmin.x,Vertices[j].x);
14311 bmin.y:=Min(bmin.y,Vertices[j].y);
14312 bmin.z:=Min(bmin.z,Vertices[j].z);
14313 bmax.x:=Max(bmax.x,Vertices[j].x);
14314 bmax.y:=Max(bmax.y,Vertices[j].y);
14315 bmax.z:=Max(bmax.z,Vertices[j].z);
14316 end;
14317 Epsilon:=ConvexHullVectorLength(ConvexHullVectorSub(bmax,bmin))*0.001;
14318 p:=FindSimplex(Vertices,CountVertices);
14319 if p[0]<0 then begin
14320 SetLength(isextreme,0);
14321 result:=nil;
14322 exit;
14323 end;
14324 Center.x:=(Vertices[p[0]].x+Vertices[p[1]].x+Vertices[p[2]].x+Vertices[p[3]].x)*0.25;
14325 Center.y:=(Vertices[p[0]].y+Vertices[p[1]].y+Vertices[p[2]].y+Vertices[p[3]].y)*0.25;
14326 Center.z:=(Vertices[p[0]].z+Vertices[p[1]].z+Vertices[p[2]].z+Vertices[p[3]].z)*0.25;
14327 TrisPushBack(Tri(p[2],p[3],p[1],CountTris,2,3,1));
14328 TrisPushBack(Tri(p[3],p[2],p[0],CountTris,3,2,0));
14329 TrisPushBack(Tri(p[0],p[1],p[3],CountTris,0,1,3));
14330 TrisPushBack(Tri(p[1],p[0],p[2],CountTris,1,0,2));
14331 isextreme[p[0]]:=true;
14332 isextreme[p[1]]:=true;
14333 isextreme[p[2]]:=true;
14334 isextreme[p[3]]:=true;
14335 CheckIt(Tris,CountTris,Tris[0]);
14336 CheckIt(Tris,CountTris,Tris[1]);
14337 CheckIt(Tris,CountTris,Tris[2]);
14338 CheckIt(Tris,CountTris,Tris[3]);
14339 for k:=0 to CountTris-1 do begin
14340 tt:=@Tris[k];
14341 Assert(tt^.ID>=0);
14342 Assert(tt^.vmax<0);
14343 n:=TriNormal(Vertices[tt^.v[0]],Vertices[tt^.v[1]],Vertices[tt^.v[2]]);
14344 tt^.vmax:=Maxdir(Vertices,CountVertices,n);
14345 tt^.Rise:=ConvexHullVectorDot(n,ConvexHullVectorSub(Vertices[tt^.vmax],Vertices[tt^.v[0]]));
14346 end;
14347 dec(VerticesLimit,4);
14348 while VerticesLimit>0 do begin
14349 te:=Extrudable(Tris,CountTris,Epsilon);
14350 if te<0 then begin
14351 break;
14352 end;
14353 //ti:=Tris[te].v;
14354 v:=Tris[te].vmax;
14355 Assert(not isextreme[v]); // wtf we've already done this vertex
14356 isextreme[v]:=true;
14357 {if(v=p0) or (v=p1) or (v=p2) or (v=p3) then begin
14358 continue; // done these already
14359 end;{}
14360 j:=CountTris;
14361 //NewStart:=j;
14362 while j>0 do begin
14363 dec(j);
14364 if TriDead(Tris[j]) then begin
14365 continue;
14366 end;
14367 t:=tris[j].v;
14368 if Above(Vertices,t,Vertices[v],0.01*Epsilon) then begin
14369 Extrude(j,v);
14370 end;
14371 end;
14372 // now check for those degenerate cases where we have a flipped triangle or a really skinny triangle
14373 j:=CountTris;
14374 while j>0 do begin
14375 dec(j);
14376 if TriDead(Tris[j]) then begin
14377 continue;
14378 end;
14379 if not HasVertex(Tris[j].v,v) then begin
14380 break;
14381 end;
14382 nt:=Tris[j].v;
14383 if Above(Vertices,nt,Center,0.01*Epsilon) or
14384 (ConvexHullVectorLength(ConvexHullVectorCross(ConvexHullVectorSub(Vertices[nt[1]],Vertices[nt[0]]),
14385 ConvexHullVectorSub(Vertices[nt[2]],Vertices[nt[1]])))<(Epsilon*Epsilon*0.1)) then begin
14386 nb:=Tris[j].n[0];
14387 Assert(nb>=0);
14388 Assert(not TriDead(Tris[nb]));
14389 Assert(not HasVertex(Tris[nb].v,v));
14390 Assert(Tris[nb].ID<j);
14391 Extrude(nb,v);
14392 j:=CountTris;
14393 end;
14394 end;
14395 j:=CountTris;
14396 while j>0 do begin
14397 dec(j);
14398 if TriDead(Tris[j]) then begin
14399 continue;
14400 end;
14401 tt:=@Tris[j];
14402 if tt^.vmax>=0 then begin
14403 break;
14404 end;
14405 n:=TriNormal(Vertices[tt^.v[0]],Vertices[tt^.v[1]],Vertices[tt^.v[2]]);
14406 tt^.vmax:=MaxDir(Vertices,CountVertices,n);
14407 if isextreme[tt^.vmax] then begin
14408 tt^.vmax:=-1; // already done that vertex - algorithm needs to be able to terminate.
14409 end else begin
14410 tt^.Rise:=ConvexHullVectorDot(n,ConvexHullVectorSub(Vertices[tt^.vmax],Vertices[tt^.v[0]]));
14411 end;
14412 end;
14413 // compress, remove non-tris
14414 j:=CountTris;
14415 while j>0 do begin
14416 dec(j);
14417 if not TriDead(Tris[j]) then begin
14418 continue;
14419 end;
14420 SwapN(Tris,CountTris,j,CountTris-1);
14421 dec(CountTris);
14422 end;
14423 dec(VerticesLimit);
14424 end;
14425 SetLength(result,CountTris);
14426 for i:=0 to CountTris-1 do begin
14427 Assert(not TriDead(Tris[i]));
14428 result[i]:=Tris[i].v;
14429 end;
14430 SetLength(Tris,0);
14431 {} SetLength(Used,CountVertices);
14432 SetLength(Map,CountVertices);
14433 for i:=0 to CountVertices-1 do begin
14434 Used[i]:=0;
14435 Map[i]:=0;
14436 end;
14437 for i:=0 to CountTris-1 do begin
14438 for j:=0 to 2 do begin
14439 inc(Used[result[i,j]]);
14440 end;
14441 end;
14442 j:=0;
14443 for i:=0 to CountVertices-1 do begin
14444 if Used[i]>0 then begin
14445 TempVertex:=Vertices[j];
14446 Vertices[j]:=Vertices[i];
14447 Vertices[i]:=TempVertex;
14448 Map[i]:=j;
14449 inc(j);
14450 end else begin
14451 Map[i]:=-1;
14452 end;
14453 end;
14454 CountVertices:=j;
14455 for i:=0 to CountTris-1 do begin
14456 for j:=0 to 2 do begin
14457 result[i,j]:=Map[result[i,j]];
14458 end;
14459 end;{}
14460 finally
14461 SetLength(isextreme,0);
14462 SetLength(Tris,0);
14463 SetLength(Map,0);
14464 SetLength(Used,0);
14465 end;
14466 except
14467 result:=nil;
14468 raise;
14469 end;
14470 end;
14471 {$warnings on}
14472 procedure SearchMinMax;
14473 var Index:longint;
14474 Point:PConvexHullVector;
14475 begin
14476 MinPoint:=Points[0];
14477 MaxPoint:=Points[0];
14478 for Index:=1 to CountPoints-1 do begin
14479 Point:=@Points[Index];
14480 if MinPoint.x>Point^.x then begin
14481 MinPoint.x:=Point^.x;
14482 end;
14483 if MinPoint.y>Point^.y then begin
14484 MinPoint.y:=Point^.y;
14485 end;
14486 if MinPoint.z>Point^.z then begin
14487 MinPoint.z:=Point^.z;
14488 end;
14489 if MaxPoint.x<Point^.x then begin
14490 MaxPoint.x:=Point^.x;
14491 end;
14492 if MaxPoint.y<Point^.y then begin
14493 MaxPoint.y:=Point^.y;
14494 end;
14495 if MaxPoint.z<Point^.z then begin
14496 MaxPoint.z:=Point^.z;
14497 end;
14498 end;
14499 end;
14500 procedure RemoveDuplicatePoints;
14501 const HashBits=8;
14502 HashSize=1 shl HashBits;
14503 HashMask=HashSize-1;
14504 var PointIndex,OtherPointIndex,CountNewPoints,HashItemIndex:longint;
14505 Hash:longword;
14506 NewPoints:TConvexHullVectors;
14507 PointNextIndices:array of longint;
14508 HashTable:array of longint;
14509 begin
14510 NewPoints:=nil;
14511 PointNextIndices:=nil;
14512 HashTable:=nil;
14513 try
14514
14515 SetLength(PointNextIndices,length(Points));
14516 for PointIndex:=0 to length(PointNextIndices)-1 do begin
14517 PointNextIndices[PointIndex]:=-1;
14518 end;
14519
14520 SetLength(HashTable,HashSize);
14521 for PointIndex:=0 to length(HashTable)-1 do begin
14522 HashTable[PointIndex]:=-1;
14523 end;
14524
14525 SetLength(NewPoints,length(Points));
14526 CountNewPoints:=0;
14527
14528 for PointIndex:=0 to length(Points)-1 do begin
14529
14530 Hash:=((round(Points[PointIndex].x)*73856093) xor (round(Points[PointIndex].y)*19349663) xor (round(Points[PointIndex].z)*83492791)) and HashMask;
14531
14532 HashItemIndex:=HashTable[Hash];
14533 while HashItemIndex>=0 do begin
14534 if ConvexHullVectorCompare(Points[PointIndex],NewPoints[HashItemIndex]) then begin
14535 break;
14536 end;
14537 HashItemIndex:=PointNextIndices[HashItemIndex];
14538 end;
14539
14540 if HashItemIndex<0 then begin
14541 OtherPointIndex:=CountNewPoints;
14542 inc(CountNewPoints);
14543 if CountNewPoints>length(NewPoints) then begin
14544 SetLength(NewPoints,CountNewPoints*2);
14545 end;
14546 NewPoints[OtherPointIndex]:=Points[PointIndex];
14547 PointNextIndices[OtherPointIndex]:=HashTable[Hash];
14548 HashTable[Hash]:=OtherPointIndex;
14549 end;
14550
14551 end;
14552
14553 if length(Points)<>CountNewPoints then begin
14554 SetLength(Points,CountNewPoints);
14555 for PointIndex:=0 to CountNewPoints-1 do begin
14556 Points[PointIndex]:=NewPoints[PointIndex];
14557 end;
14558 end;
14559
14560 finally
14561 SetLength(NewPoints,0);
14562 SetLength(PointNextIndices,0);
14563 SetLength(HashTable,0);
14564 end;
14565 end;
14566 procedure RemoveTooNearPoints;
14567 const HashBits=8;
14568 HashSize=1 shl HashBits;
14569 HashMask=HashSize-1;
14570 var PointIndex,OtherPointIndex,CountNewPoints,HashItemIndex:longint;
14571 Hash:longword;
14572 InverseTolerance:double;
14573 NewPoints:TConvexHullVectors;
14574 PointNextIndices:array of longint;
14575 HashTable:array of longint;
14576 begin
14577 NewPoints:=nil;
14578 PointNextIndices:=nil;
14579 HashTable:=nil;
14580 try
14581
14582 SetLength(PointNextIndices,length(Points));
14583 for PointIndex:=0 to length(PointNextIndices)-1 do begin
14584 PointNextIndices[PointIndex]:=-1;
14585 end;
14586
14587 SetLength(HashTable,HashSize);
14588 for PointIndex:=0 to length(HashTable)-1 do begin
14589 HashTable[PointIndex]:=-1;
14590 end;
14591
14592 SetLength(NewPoints,length(Points));
14593 CountNewPoints:=0;
14594
14595 InverseTolerance:=1.0/Tolerance;
14596
14597 for PointIndex:=0 to length(Points)-1 do begin
14598
14599 Hash:=((trunc(Points[PointIndex].x*InverseTolerance)*73856093) xor
14600 (trunc(Points[PointIndex].y*InverseTolerance)*19349663) xor
14601 (trunc(Points[PointIndex].z*InverseTolerance)*83492791)) and HashMask;
14602
14603 HashItemIndex:=HashTable[Hash];
14604 while HashItemIndex>=0 do begin
14605 if ConvexHullVectorLengthSquared(ConvexHullVectorSub(Points[PointIndex],NewPoints[HashItemIndex]))<=(2.0*Tolerance) then begin
14606 break;
14607 end;
14608 HashItemIndex:=PointNextIndices[HashItemIndex];
14609 end;
14610
14611 if HashItemIndex<0 then begin
14612 OtherPointIndex:=CountNewPoints;
14613 inc(CountNewPoints);
14614 if CountNewPoints>length(NewPoints) then begin
14615 SetLength(NewPoints,CountNewPoints*2);
14616 end;
14617 NewPoints[OtherPointIndex]:=Points[PointIndex];
14618 PointNextIndices[OtherPointIndex]:=HashTable[Hash];
14619 HashTable[Hash]:=OtherPointIndex;
14620 end;
14621
14622 end;
14623
14624 if length(Points)<>CountNewPoints then begin
14625 SetLength(Points,CountNewPoints);
14626 for PointIndex:=0 to CountNewPoints-1 do begin
14627 Points[PointIndex]:=NewPoints[PointIndex];
14628 end;
14629 end;
14630
14631 finally
14632 SetLength(NewPoints,0);
14633 SetLength(PointNextIndices,0);
14634 SetLength(HashTable,0);
14635 end;
14636 end;
14637 procedure SortPoints;
14638 var Count,Index:longint;
14639 NewPoints:TConvexHullVectors;
14640 IndirectPoints:array of PConvexHullVector;
14641 begin
14642 Count:=length(Points);
14643 if Count>1 then begin
14644 NewPoints:=nil;
14645 IndirectPoints:=nil;
14646 try
14647 NewPoints:=Points;
14648 Points:=nil;
14649 SetLength(IndirectPoints,Count);
14650 SetLength(Points,Count);
14651 for Index:=0 to Count-1 do begin
14652 IndirectPoints[Index]:=@NewPoints[Index];
14653 end;
14654 IndirectIntroSort(@IndirectPoints[0],0,Count-1,@CompareConvexHullPoints);
14655 for Index:=0 to Count-1 do begin
14656 Points[Index]:=IndirectPoints[Index]^;
14657 end;
14658 finally
14659 SetLength(NewPoints,0);
14660 SetLength(IndirectPoints,0);
14661 end;
14662 end;
14663 end;
14664 var Tris:TInt3s;
14665 i:longint;
14666 begin
14667 result:=false;
14668 Tris:=nil;
14669 try
14670 CountPoints:=length(Points);
14671 SearchMinMax;
14672 if UserDefinedTolerance>0.0 then begin
14673 Tolerance:=UserDefinedTolerance;
14674 end else begin
14675 Tolerance:=Max(DOUBLE_PREC,(3.0*DOUBLE_PREC)*(Max(abs(MaxPoint.x),abs(MaxPoint.x))+Max(abs(MaxPoint.y),abs(MaxPoint.y))+Max(abs(MaxPoint.z),abs(MaxPoint.z))));
14676 end;
14677 RemoveDuplicatePoints;
14678 RemoveTooNearPoints;
14679 SortPoints;
14680 CountPoints:=length(Points);
14681 Tris:=CalcHull(Points,CountPoints,MaximumOutputPoints);
14682 if (length(Tris)>0) and (CountPoints>0) then begin
14683 SetLength(Points,CountPoints);
14684 SetLength(OutTriangles,length(Tris));
14685 for i:=0 to length(Tris)-1 do begin
14686 OutTriangles[i,0]:=Tris[i,0];
14687 OutTriangles[i,1]:=Tris[i,1];
14688 OutTriangles[i,2]:=Tris[i,2];
14689 end;
14690 result:=true;
14691 end;
14692 finally
14693 SetLength(Tris,0);
14694 end;
14695 end;
14696
14697 function KraftQuickHullIsSameValue(const a,b:double):boolean;
14698 const FuzzFactor=1000;
14699 DoubleResolution=1e-15*FuzzFactor;
14700 var EpsilonTolerance:double;
14701 begin
14702 EpsilonTolerance:=abs(a);
14703 if EpsilonTolerance>abs(b) then begin
14704 EpsilonTolerance:=abs(b);
14705 end;
14706 EpsilonTolerance:=EpsilonTolerance*DoubleResolution;
14707 if EpsilonTolerance<DoubleResolution then begin
14708 EpsilonTolerance:=DoubleResolution;
14709 end;
14710 if a>b then begin
14711 result:=(a-b)<=EpsilonTolerance;
14712 end else begin
14713 result:=(b-a)<=EpsilonTolerance;
14714 end;
14715 end;
14716
14717 function KraftQuickHullIntLog2(x:longword):longword; {$ifdef cpu386}assembler; register;
14718 asm
14719 test eax,eax
14720 jz @Done
14721 bsr eax,eax
14722 @Done:
14723 end;
14724 {$else}
14725 begin
14726 x:=x or (x shr 1);
14727 x:=x or (x shr 2);
14728 x:=x or (x shr 4);
14729 x:=x or (x shr 8);
14730 x:=x or (x shr 16);
14731 x:=x shr 1;
14732 x:=x-((x shr 1) and $55555555);
14733 x:=((x shr 2) and $33333333)+(x and $33333333);
14734 x:=((x shr 4)+x) and $0f0f0f0f;
14735 x:=x+(x shr 8);
14736 x:=x+(x shr 16);
14737 result:=x and $3f;
14738 end;
14739 {$endif}
14740
14741 constructor TKraftQuickHullIntegerList.Create;
14742 begin
14743 inherited Create;
14744 fCountItems:=0;
14745 fAllocated:=0;
14746 fList:=nil;
14747 Clear;
14748 end;
14749
14750 destructor TKraftQuickHullIntegerList.Destroy;
14751 begin
14752 Clear;
14753 inherited Destroy;
14754 end;
14755
14756 procedure TKraftQuickHullIntegerList.Clear;
14757 begin
14758 fCountItems:=0;
14759 fAllocated:=0;
14760 fIsSorted:=false;
14761 ReallocMem(fList,0);
14762 end;
14763
14764 procedure TKraftQuickHullIntegerList.SetCapacity(NewCapacity:longint);
14765 begin
14766 if NewCapacity>=0 then begin
14767 ReallocMem(fList,NewCapacity*sizeof(longint));
14768 fAllocated:=NewCapacity;
14769 end;
14770 end;
14771
14772 procedure TKraftQuickHullIntegerList.SetCount(NewCount:longint);
14773 begin
14774 if NewCount>=0 then begin
14775 if NewCount<fCountItems then begin
14776 fCountItems:=NewCount;
14777 end else if NewCount>fCountItems then begin
14778 if NewCount>fAllocated then begin
14779 SetCapacity((fCountItems+4096) and not 4095);
14780 end;
14781 if fCountItems<NewCount then begin
14782 FillChar(fList^[fCountItems],(NewCount-fCountItems)*SizeOf(longint),#0);
14783 end;
14784 fCountItems:=NewCount;
14785 end;
14786 end;
14787 end;
14788
14789 function TKraftQuickHullIntegerList.Add(Item:longint):longint;
14790 begin
14791 if fCountItems>=fAllocated then begin
14792 fAllocated:=(fCountItems+4096) and not 4095;
14793 ReallocMem(fList,fAllocated*SizeOf(longint));
14794 end;
14795 fList^[fCountItems]:=Item;
14796 result:=fCountItems;
14797 inc(fCountItems);
14798 fIsSorted:=false;
14799 end;
14800
14801 procedure TKraftQuickHullIntegerList.AddSorted(Item:longint);
14802 var i:longint;
14803 begin
14804 if fIsSorted then begin
14805 if fCountItems=0 then begin
14806 Add(Item);
14807 end else begin
14808 i:=0;
14809 while (i<fCountItems) and (Item>=fList^[i]) do begin
14810 inc(i);
14811 end;
14812 Insert(i,Item);
14813 end;
14814 fIsSorted:=true;
14815 end else begin
14816 Add(Item);
14817 Sort;
14818 end;
14819 end;
14820
14821 procedure TKraftQuickHullIntegerList.Insert(Index:longint;Item:longint);
14822 var i:longint;
14823 begin
14824 if (Index>=0) and (Index<fCountItems) then begin
14825 SetCount(fCountItems+1);
14826 for i:=fCountItems-1 downto Index do begin
14827 fList^[i+1]:=fList^[i];
14828 end;
14829 fList^[Index]:=Item;
14830 end else if Index=fCountItems then begin
14831 Add(Item);
14832 end else if Index>fCountItems then begin
14833 SetCount(Index);
14834 Add(Item);
14835 end;
14836 fIsSorted:=false;
14837 end;
14838
14839 procedure TKraftQuickHullIntegerList.Delete(Index:longint);
14840 var i,j,k:longint;
14841 begin
14842 if (Index>=0) and (Index<fCountItems) then begin
14843 k:=fCountItems-1;
14844 j:=Index;
14845 for i:=j to k-1 do begin
14846 fList^[i]:=fList^[i+1];
14847 end;
14848 SetCount(k);
14849 end;
14850 end;
14851
14852 function TKraftQuickHullIntegerList.Remove(Item:longint):longint;
14853 var i,j,k:longint;
14854 begin
14855 result:=-1;
14856 k:=fCountItems;
14857 j:=-1;
14858 for i:=0 to k-1 do begin
14859 if fList^[i]=Item then begin
14860 j:=i;
14861 break;
14862 end;
14863 end;
14864 if j>=0 then begin
14865 dec(k);
14866 for i:=j to k-1 do begin
14867 fList^[i]:=fList^[i+1];
14868 end;
14869 SetCount(k);
14870 result:=j;
14871 end;
14872 end;
14873
14874 function TKraftQuickHullIntegerList.Find(Item:longint):longint;
14875 var i,l,r:longint;
14876 begin
14877 result:=-1;
14878 if fIsSorted then begin
14879 l:=0;
14880 r:=fCountItems-1;
14881 while l<=r do begin
14882 i:=(l+r) shr 1;
14883 if fList^[i]=Item then begin
14884 result:=i;
14885 break;
14886 end else begin
14887 if fList^[i]<Item then begin
14888 l:=i+1;
14889 end else begin
14890 r:=i-1;
14891 end;
14892 end;
14893 end;
14894 end else begin
14895 for i:=0 to fCountItems-1 do begin
14896 if fList^[i]=Item then begin
14897 result:=i;
14898 break;
14899 end;
14900 end;
14901 end;
14902 end;
14903
14904 function TKraftQuickHullIntegerList.IndexOf(Item:longint):longint;
14905 begin
14906 result:=Find(Item);
14907 end;
14908
14909 procedure TKraftQuickHullIntegerList.Exchange(Index1,Index2:longint);
14910 var TempInteger:longint;
14911 begin
14912 if (Index1>=0) and (Index1<fCountItems) and (Index2>=0) and (Index2<fCountItems) then begin
14913 TempInteger:=fList^[Index1];
14914 fList^[Index1]:=fList^[Index2];
14915 fList^[Index2]:=TempInteger;
14916 fIsSorted:=false;
14917 end;
14918 end;
14919
14920 function TKraftQuickHullIntegerList.GetItem(Index:longint):longint;
14921 begin
14922 if (Index>=0) and (Index<fCountItems) then begin
14923 result:=fList^[Index];
14924 end else begin
14925 result:=0;
14926 end;
14927 end;
14928
14929 procedure TKraftQuickHullIntegerList.SetItem(Index:longint;Value:longint);
14930 begin
14931 if (Index>=0) and (Index<fCountItems) then begin
14932 fList^[Index]:=Value;
14933 fIsSorted:=false;
14934 end;
14935 end;
14936
14937 function TKraftQuickHullIntegerList.GetItemPointer(Index:longint):pointer;
14938 begin
14939 if (Index>=0) and (Index<fCountItems) then begin
14940 result:=@fList^[Index];
14941 end else begin
14942 result:=nil;
14943 end;
14944 end;
14945
14946 procedure TKraftQuickHullIntegerList.Sort;
14947 procedure IntroSort(Left,Right,Depth:longint);
14948 procedure SiftDown(Current,MaxIndex:longint);
14949 var SiftLeft,SiftRight,Largest:longint;
14950 v:longint;
14951 begin
14952 SiftLeft:=Left+(2*(Current-Left))+1;
14953 SiftRight:=Left+(2*(Current-Left))+2;
14954 Largest:=Current;
14955 if (SiftLeft<=MaxIndex) and (fList^[SiftLeft]>fList^[Largest]) then begin
14956 Largest:=SiftLeft;
14957 end;
14958 if (SiftRight<=MaxIndex) and (fList^[SiftRight]>fList^[Largest]) then begin
14959 Largest:=SiftRight;
14960 end;
14961 if Largest<>Current then begin
14962 v:=fList^[Current];
14963 fList^[Current]:=fList^[Largest];
14964 fList^[Largest]:=v;
14965 SiftDown(Largest,MaxIndex);
14966 end;
14967 end;
14968 procedure InsertionSort;
14969 var i,j:longint;
14970 t:longint;
14971 begin
14972 i:=Left+1;
14973 while i<=Right do begin
14974 t:=fList^[i];
14975 j:=i-1;
14976 while (j>=Left) and (t<fList^[j]) do begin
14977 fList^[j+1]:=fList^[j];
14978 dec(j);
14979 end;
14980 fList^[j+1]:=t;
14981 inc(i);
14982 end;
14983 end;
14984 procedure HeapSort;
14985 var i:longint;
14986 v:longint;
14987 begin
14988 i:=((Left+Right+1) div 2)-1;
14989 while i>=Left do begin
14990 SiftDown(i,Right);
14991 dec(i);
14992 end;
14993 i:=Right;
14994 while i>=Left+1 do begin
14995 v:=fList^[i];
14996 fList^[i]:=fList^[Left];
14997 fList^[Left]:=v;
14998 SiftDown(Left,i-1);
14999 dec(i);
15000 end;
15001 end;
15002 procedure QuickSortWidthMedianOfThreeOptimization;
15003 var Middle,i,j:longint;
15004 Pivot,v:longint;
15005 begin
15006 Middle:=(Left+Right) div 2;
15007 if (Right-Left)>3 then begin
15008 if fList^[Left]>fList^[Middle] then begin
15009 v:=fList^[Left];
15010 fList^[Left]:=fList^[Middle];
15011 fList^[Middle]:=v;
15012 end;
15013 if fList^[Left]>fList^[Right] then begin
15014 v:=fList^[Left];
15015 fList^[Left]:=fList^[Right];
15016 fList^[Right]:=v;
15017 end;
15018 if fList^[Middle]>fList^[Right] then begin
15019 v:=fList^[Middle];
15020 fList^[Middle]:=fList^[Right];
15021 fList^[Right]:=v;
15022 end;
15023 end;
15024 Pivot:=fList^[Middle];
15025 i:=Left;
15026 j:=Right;
15027 while true do begin
15028 while (i<j) and (fList^[i]<Pivot) do begin
15029 inc(i);
15030 end;
15031 while (j>i) and (fList^[j]>Pivot) do begin
15032 dec(j);
15033 end;
15034 if i>j then begin
15035 break;
15036 end;
15037 v:=fList^[i];
15038 fList^[i]:=fList^[j];
15039 fList^[j]:=v;
15040 inc(i);
15041 dec(j);
15042 end;
15043 IntroSort(Left,j,Depth-1);
15044 IntroSort(i,Right,Depth-1);
15045 end;
15046 begin
15047 if Left<Right then begin
15048 if (Right-Left)<16 then begin
15049 InsertionSort;
15050 end else if Depth=0 then begin
15051 HeapSort;
15052 end else begin
15053 QuickSortWidthMedianOfThreeOptimization;
15054 end;
15055 end;
15056 end;
15057 procedure QuickSort(L,R:longint);
15058 var Pivot,vL,vR:longint;
15059 v:longint;
15060 begin
15061 if (R-L)<=1 then begin
15062 if (L<R) and (fList[R]<fList[L]) then begin
15063 v:=fList^[L];
15064 fList^[L]:=fList^[R];
15065 fList^[R]:=v;
15066 end;
15067 end else begin
15068 vL:=L;
15069 vR:=R;
15070 Pivot:=L+Random(R-L);
15071 while vL<vR do begin
15072 while (vL<Pivot) and (fList^[vL]<=fList^[Pivot]) do begin
15073 inc(vL);
15074 end;
15075 while (vR>Pivot) and (fList^[vR]>fList^[Pivot]) do begin
15076 dec(vR);
15077 end;
15078 v:=fList^[vL];
15079 fList^[vL]:=fList^[vR];
15080 fList^[vR]:=v;
15081 if Pivot=vL then begin
15082 Pivot:=vR;
15083 end else if Pivot=vR then begin
15084 Pivot:=vL;
15085 end;
15086 end;
15087 if (Pivot-1)>=L then begin
15088 QuickSort(L,Pivot-1);
15089 end;
15090 if (Pivot+1)<=R then begin
15091 QuickSort(Pivot+1,R);
15092 end;
15093 end;
15094 end;
15095 procedure QuickSortEx(Left,Right:longint);
15096 var Pivot,i,j:longint;
15097 v:longint;
15098 begin
15099 i:=Left;
15100 j:=Right;
15101 Pivot:=fList^[(i+j) div 2];
15102 while i<=j do begin
15103 while fList^[i]<Pivot do begin
15104 inc(i);
15105 end;
15106 while fList^[j]>Pivot do begin
15107 dec(j);
15108 end;
15109 if i<=j then begin
15110 v:=fList^[i];
15111 fList^[i]:=fList^[i];
15112 fList^[j]:=v;
15113 inc(i);
15114 dec(j);
15115 end;
15116 end;
15117 if Left<j then begin
15118 QuickSortEx(Left,j);
15119 end;
15120 if i<Right then begin
15121 QuickSortEx(i,Right);
15122 end;
15123 end;
15124 procedure BeRoSort;
15125 var i:longint;
15126 v:longint;
15127 begin
15128 i:=0;
15129 while i<(fCountItems-1) do begin
15130 if fList^[i]>fList^[i+1] then begin
15131 v:=fList^[i];
15132 fList^[i]:=fList^[i+1];
15133 fList^[i+1]:=v;
15134 if i>0 then begin
15135 dec(i);
15136 end else begin
15137 inc(i);
15138 end;
15139 end else begin
15140 inc(i);
15141 end;
15142 end;
15143 end;
15144 begin
15145 if fCountItems>0 then begin
15146 IntroSort(0,fCountItems-1,KraftQuickHullIntLog2(fCountItems)*2);
15147 fIsSorted:=true;
15148 end;
15149 end;
15150
15151 function TKraftQuickHullVector3D.Init(const ax:double=0.0;const ay:double=0.0;const az:double=0.0):TKraftQuickHullVector3D;
15152 begin
15153 x:=ax;
15154 y:=ay;
15155 z:=az;
15156 result:=self;
15157 end;
15158
15159 procedure TKraftQuickHullVector3D.SetValue(i:longint;const v:double);
15160 begin
15161 case i of
15162 0:begin
15163 x:=v;
15164 end;
15165 1:begin
15166 y:=v;
15167 end;
15168 2:begin
15169 z:=v;
15170 end;
15171 end;
15172 end;
15173
15174 function TKraftQuickHullVector3D.GetValue(i:longint):double;
15175 begin
15176 case i of
15177 0:begin
15178 result:=x;
15179 end;
15180 1:begin
15181 result:=y;
15182 end;
15183 2:begin
15184 result:=z;
15185 end;
15186 else begin
15187 result:=0;
15188 end;
15189 end;
15190 end;
15191
15192 procedure TKraftQuickHullVector3D.Add(const v0,v1:TKraftQuickHullVector3D);
15193 begin
15194 x:=v0.x+v1.x;
15195 y:=v0.y+v1.y;
15196 z:=v0.z+v1.z;
15197 end;
15198
15199 procedure TKraftQuickHullVector3D.Add(const v:TKraftQuickHullVector3D);
15200 begin
15201 x:=x+v.x;
15202 y:=y+v.y;
15203 z:=z+v.z;
15204 end;
15205
15206 procedure TKraftQuickHullVector3D.Sub(const v0,v1:TKraftQuickHullVector3D);
15207 begin
15208 x:=v0.x-v1.x;
15209 y:=v0.y-v1.y;
15210 z:=v0.z-v1.z;
15211 end;
15212
15213 procedure TKraftQuickHullVector3D.Sub(const v:TKraftQuickHullVector3D);
15214 begin
15215 x:=x-v.x;
15216 y:=y-v.y;
15217 z:=z-v.z;
15218 end;
15219
15220 procedure TKraftQuickHullVector3D.Scale(const v:TKraftQuickHullVector3D;const s:double);
15221 begin
15222 x:=v.x*s;
15223 y:=v.y*s;
15224 z:=v.z*s;
15225 end;
15226
15227 procedure TKraftQuickHullVector3D.Scale(const s:double);
15228 begin
15229 x:=x*s;
15230 y:=y*s;
15231 z:=z*s;
15232 end;
15233
15234 function TKraftQuickHullVector3D.Length:double;
15235 begin
15236 result:=sqrt(sqr(x)+sqr(y)+sqr(z));
15237 end;
15238
15239 function TKraftQuickHullVector3D.LengthSquared:double;
15240 begin
15241 result:=sqr(x)+sqr(y)+sqr(z);
15242 end;
15243
15244 function TKraftQuickHullVector3D.Distance(const v:TKraftQuickHullVector3D):double;
15245 begin
15246 result:=sqrt(sqr(v.x-x)+sqr(v.y-y)+sqr(v.z-z));
15247 end;
15248
15249 function TKraftQuickHullVector3D.DistanceSquared(const v:TKraftQuickHullVector3D):double;
15250 begin
15251 result:=sqr(v.x-x)+sqr(v.y-y)+sqr(v.z-z);
15252 end;
15253
15254 procedure TKraftQuickHullVector3D.Normalize;
15255 var l:double;
15256 begin
15257 l:=sqr(x)+sqr(y)+sqr(z);
15258 if abs(l)>1e-16 then begin
15259 l:=sqrt(l);
15260 x:=x/l;
15261 y:=y/l;
15262 z:=z/l;
15263 end;
15264 end;
15265
15266 function TKraftQuickHullVector3D.Dot(const v:TKraftQuickHullVector3D):double;
15267 begin
15268 result:=(x*v.x)+(y*v.y)+(z*v.z);
15269 end;
15270
15271 procedure TKraftQuickHullVector3D.CrossProduct(const v0,v1:TKraftQuickHullVector3D);
15272 var tx,ty,tz:double;
15273 begin
15274 tx:=(v0.y*v1.z)-(v0.z*v1.y);
15275 ty:=(v0.z*v1.x)-(v0.x*v1.z);
15276 tz:=(v0.x*v1.y)-(v0.y*v1.x);
15277 x:=tx;
15278 y:=ty;
15279 z:=tz;
15280 end;
15281
15282 procedure TKraftQuickHullVector3D.SetRandom(Lower,Upper:double);
15283 var Range:double;
15284 begin
15285 Range:=Upper-Lower;
15286 x:=Lower+(random*Range);
15287 y:=Lower+(random*Range);
15288 z:=Lower+(random*Range);
15289 end;
15290
15291 function TKraftQuickHullVector3D.Equals(const v:TKraftQuickHullVector3D):boolean;
15292 begin
15293 result:=SameValue(v.x,x) and SameValue(v.y,y) and SameValue(v.z,z);
15294 end;
15295
15296 procedure TKraftQuickHullVertexList.Clear;
15297 begin
15298 Head:=nil;
15299 Tail:=nil;
15300 end;
15301
15302 procedure TKraftQuickHullVertexList.Add(vtx:TKraftQuickHullVertex);
15303 begin
15304 if assigned(Head) then begin
15305 Tail.fNext:=vtx;
15306 end else begin
15307 Head:=vtx;
15308 end;
15309 vtx.fPrevious:=Tail;
15310 vtx.fNext:=nil;
15311 Tail:=vtx;
15312 end;
15313
15314 procedure TKraftQuickHullVertexList.AddAll(vtx:TKraftQuickHullVertex);
15315 begin
15316 if assigned(Head) then begin
15317 Tail.Next:=vtx;
15318 end else begin
15319 Head:=vtx;
15320 end;
15321 vtx.Previous:=Tail;
15322 while assigned(vtx.Next) do begin
15323 vtx:=vtx.Next;
15324 end;
15325 Tail:=vtx;
15326 end;
15327
15328 procedure TKraftQuickHullVertexList.Delete(vtx:TKraftQuickHullVertex);
15329 begin
15330 if assigned(vtx.Previous) then begin
15331 vtx.Previous.Next:=vtx.Next;
15332 end else if Head=vtx then begin
15333 Head:=vtx.Next;
15334 end;
15335 if assigned(vtx.Next) then begin
15336 vtx.Next.Previous:=vtx.Previous;
15337 end else if Tail=vtx then begin
15338 Tail:=vtx.Previous;
15339 end;
15340 end;
15341
15342 procedure TKraftQuickHullVertexList.Delete(vtx1,vtx2:TKraftQuickHullVertex);
15343 begin
15344 if assigned(vtx1.Previous) then begin
15345 vtx1.Previous.Next:=vtx2.Next;
15346 end else if Head=vtx1 then begin
15347 Head:=vtx2.Next;
15348 end;
15349 if assigned(vtx2.Next) then begin
15350 vtx2.Next.Previous:=vtx1.Previous;
15351 end else if Tail=vtx2 then begin
15352 Tail:=vtx1.Previous;
15353 end;
15354 end;
15355
15356 procedure TKraftQuickHullVertexList.InsertBefore(vtx,Next:TKraftQuickHullVertex);
15357 begin
15358 vtx.Previous:=Next.Previous;
15359 if assigned(Next.Previous) then begin
15360 Next.Previous.Next:=vtx;
15361 end else begin
15362 Head:=vtx;
15363 enD;
15364 vtx.Next:=Next;
15365 Next.Previous:=vtx;
15366 end;
15367
15368 function TKraftQuickHullVertexList.First:TKraftQuickHullVertex;
15369 begin
15370 result:=Head;
15371 end;
15372
15373 function TKraftQuickHullVertexList.IsEmpty:boolean;
15374 begin
15375 result:=not assigned(Head);
15376 end;
15377
15378 procedure TKraftQuickHullFaceList.Clear;
15379 begin
15380 Head:=nil;
15381 Tail:=nil;
15382 end;
15383
15384 procedure TKraftQuickHullFaceList.Add(vtx:TKraftQuickHullFace);
15385 begin
15386 if assigned(Head) then begin
15387 Tail.fNext:=vtx;
15388 end else begin
15389 Head:=vtx;
15390 end;
15391 vtx.fNext:=nil;
15392 Tail:=vtx;
15393 end;
15394
15395 function TKraftQuickHullFaceList.First:TKraftQuickHullFace;
15396 begin
15397 result:=Head;
15398 end;
15399
15400 function TKraftQuickHullFaceList.IsEmpty:boolean;
15401 begin
15402 result:=not assigned(Head);
15403 end;
15404
15405 constructor TKraftQuickHullVertex.Create(const AInstance:TKraftQuickHull);
15406 begin
15407 inherited Create;
15408 fInstance:=AInstance;
15409 fInstance.fGarbageCollectedClassInstances.Add(self);
15410 end;
15411
15412 destructor TKraftQuickHullVertex.Destroy;
15413 begin
15414 fInstance.fGarbageCollectedClassInstances.Remove(self);
15415 inherited Destroy;
15416 end;
15417
15418 constructor TKraftQuickHullFace.Create(const AInstance:TKraftQuickHull);
15419 begin
15420 inherited Create;
15421 fInstance:=AInstance;
15422 fInstance.fGarbageCollectedClassInstances.Add(self);
15423 fhe0:=nil;
15424 fNormal.Init;
15425 fArea:=0;
15426 fCentroid.Init;
15427 fPlaneOffset:=0;
15428 fIndex:=0;
15429 fCountVertices:=0;
15430 fMark:=KRAFT_QUICKHULL_FACE_MARK_VISIBLE;
15431 fOutside:=nil;
15432 end;
15433
15434 constructor TKraftQuickHullFace.CreatePolygon(const AInstance:TKraftQuickHull;const AVertices:array of TKraftQuickHullVertex;const AIndices:array of longint);
15435 var i:longint;
15436 hePrev,he:TKraftQuickHullHalfEdge;
15437 begin
15438 Create(AInstance);
15439 hePrev:=nil;
15440 for i:=0 to length(AIndices)-1 do begin
15441 he:=TKraftQuickHullHalfEdge.Create(fInstance,AVertices[AIndices[i]],self);
15442 if assigned(hePrev) then begin
15443 he.fPrevious:=hePrev;
15444 hePrev.fNext:=he;
15445 end else begin
15446 fhe0:=he;
15447 end;
15448 hePrev:=he;
15449 end;
15450 fhe0.fPrevious:=hePrev;
15451 hePrev.fNext:=fhe0;
15452 ComputeNormalAndCentroid;
15453 end;
15454
15455 constructor TKraftQuickHullFace.CreateTriangle(const AInstance:TKraftQuickHull;const v0,v1,v2:TKraftQuickHullVertex;const AMinArea:double=0.0);
15456 var he1,he2:TKraftQuickHullHalfEdge;
15457 begin
15458 Create(AInstance);
15459 fhe0:=TKraftQuickHullHalfEdge.Create(fInstance,v0,self);
15460 he1:=TKraftQuickHullHalfEdge.Create(fInstance,v1,self);
15461 he2:=TKraftQuickHullHalfEdge.Create(fInstance,v2,self);
15462 fhe0.fPrevious:=he2;
15463 fhe0.fNext:=he1;
15464 he1.fPrevious:=fhe0;
15465 he1.fNext:=he2;
15466 he2.fPrevious:=he1;
15467 he2.fNext:=fhe0;
15468 ComputeNormalAndCentroid(AMinArea);
15469 end;
15470
15471 destructor TKraftQuickHullFace.Destroy;
15472 begin
15473 fInstance.fGarbageCollectedClassInstances.Remove(self);
15474 inherited Destroy;
15475 end;
15476
15477 procedure TKraftQuickHullFace.ComputeCentroid(var ACentroid:TKraftQuickHullVector3D);
15478 var he:TKraftQuickHullHalfEdge;
15479 begin
15480 ACentroid.x:=0.0;
15481 ACentroid.y:=0.0;
15482 ACentroid.z:=0.0;
15483 he:=fhe0;
15484 repeat
15485 ACentroid.Add(he.Head.Point);
15486 he:=he.fNext;
15487 until he=fhe0;
15488 ACentroid.Scale(1.0/fCountVertices);
15489 end;
15490
15491 procedure TKraftQuickHullFace.ComputeNormal(var ANormal:TKraftQuickHullVector3D);
15492 var he1,he2:TKraftQuickHullHalfEdge;
15493 p0,p2:TKraftQuickHullVector3D;
15494 d2x,d2y,d2z,d1x,d1y,d1z:double;
15495 begin
15496 he1:=fhe0.fNext;
15497 he2:=he1.fNext;
15498 p0:=fhe0.Head.Point;
15499 p2:=he1.Head.Point;
15500 d2x:=p2.x-p0.x;
15501 d2y:=p2.y-p0.y;
15502 d2z:=p2.z-p0.z;
15503 ANormal.x:=0.0;
15504 ANormal.y:=0.0;
15505 ANormal.z:=0.0;
15506 fCountVertices:=2;
15507 while he2<>fhe0 do begin
15508 d1x:=d2x;
15509 d1y:=d2y;
15510 d1z:=d2z;
15511 p2:=he2.Head.Point;
15512 d2x:=p2.x-p0.x;
15513 d2y:=p2.y-p0.y;
15514 d2z:=p2.z-p0.z;
15515 ANormal.x:=ANormal.x+((d1y*d2z)-(d1z*d2y));
15516 ANormal.y:=ANormal.y+((d1z*d2x)-(d1x*d2z));
15517 ANormal.z:=ANormal.z+((d1x*d2y)-(d1y*d2x));
15518 //he1:=he2;
15519 he2:=he2.fNext;
15520 inc(fCountVertices);
15521 end;
15522 fArea:=ANormal.Length;
15523 ANormal.x:=ANormal.x/fArea;
15524 ANormal.y:=ANormal.y/fArea;
15525 ANormal.z:=ANormal.z/fArea;
15526 end;
15527
15528 procedure TKraftQuickHullFace.ComputeNormal(var ANormal:TKraftQuickHullVector3D;const AMinArea:double);
15529 var hedgeMax,hedge:TKraftQuickHullHalfEdge;
15530 LenSquaredMax,LenSquared,ux,uy,uz,Dot,lenMax:double;
15531 p1,p2:TKraftQuickHullVector3D;
15532 begin
15533 ComputeNormal(ANormal);
15534 if fArea<AMinArea then begin
15535 hedgeMax:=nil;
15536 LenSquaredMax:=0;
15537 hedge:=fhe0;
15538 repeat
15539 LenSquared:=hedge.LengthSquared;
15540 if LenSquared>LenSquaredMax then begin
15541 hedgeMax:=hedge;
15542 LenSquaredMax:=LenSquared;
15543 end;
15544 hedge:=hedge.fnext;
15545 until hedge=fhe0;
15546 p2:=HedgeMax.Head.Point;
15547 p1:=HedgeMax.Tail.Point;
15548 lenMax:=sqrt(LenSquaredMax);
15549 ux:=(p2.x-p1.x)/lenMax;
15550 uy:=(p2.y-p1.y)/lenMax;
15551 uz:=(p2.z-p1.z)/lenMax;
15552 Dot:=(ANormal.x*ux)+(ANormal.y*uy)+(ANormal.z*uz);
15553 ANormal.x:=ANormal.x-(Dot*ux);
15554 ANormal.y:=ANormal.y-(Dot*uy);
15555 ANormal.z:=ANormal.z-(Dot*uz);
15556 ANormal.Normalize();
15557 end;
15558 end;
15559
15560 procedure TKraftQuickHullFace.ComputeNormalAndCentroid;
15561 var he:TKraftQuickHullHalfEdge;
15562 CountFoundVertices:longint;
15563 begin
15564 ComputeNormal(fNormal);
15565 ComputeCentroid(fCentroid);
15566 fPlaneOffset:=fNormal.Dot(fCentroid);
15567 CountFoundVertices:=0;
15568 he:=fhe0;
15569 repeat
15570 inc(CountFoundVertices);
15571 he:=he.fNext;
15572 until he=fhe0;
15573 Assert(CountFoundVertices=fCountVertices,'Wrong count of vertices');
15574 end;
15575
15576 procedure TKraftQuickHullFace.ComputeNormalAndCentroid(const AMinArea:double);
15577 begin
15578 ComputeNormal(fNormal,AMinArea);
15579 ComputeCentroid(fCentroid);
15580 fPlaneOffset:=fNormal.Dot(fCentroid);
15581 end;
15582
15583 function TKraftQuickHullFace.GetEdge(i:longint):TKraftQuickHullHalfEdge;
15584 begin
15585 result:=fhe0;
15586 while i>0 do begin
15587 result:=result.fNext;
15588 dec(i);
15589 end;
15590 while i<0 do begin
15591 result:=result.fPrevious;
15592 inc(i);
15593 end;
15594 end;
15595
15596 function TKraftQuickHullFace.GetFirstEdge:TKraftQuickHullHalfEdge;
15597 begin
15598 result:=fhe0;
15599 end;
15600
15601 function TKraftQuickHullFace.FindEdge(const vt,vh:TKraftQuickHullVertex):TKraftQuickHullHalfEdge;
15602 begin
15603 result:=fhe0;
15604 repeat
15605 if (result.Head=vh) and (result.Tail=vt) then begin
15606 exit;
15607 end;
15608 result:=result.fNext;
15609 until result=fhe0;
15610 result:=nil;
15611 end;
15612
15613 function TKraftQuickHullFace.DistanceToPlane(const p:TKraftQuickHullVector3D):double;
15614 begin
15615 result:=((fNormal.x*p.x)+(fNormal.y*p.y)+(fNormal.z*p.z))-fPlaneOffset;
15616 end;
15617
15618 function TKraftQuickHullFace.ConnectHalfEdges(const hedgePrev,hedge:TKraftQuickHullHalfEdge):TKraftQuickHullFace;
15619 var oppFace:TKraftQuickHullFace;
15620 hedgeOpp:TKraftQuickHullHalfEdge;
15621 begin
15622 result:=nil;
15623 if hedgePrev.OppositeFace=hedge.OppositeFace then begin
15624 // then there is a redundant edge that we can get rid off
15625 oppFace:=hedge.OppositeFace;
15626 if hedgePrev=fhe0 then begin
15627 fhe0:=hedge;
15628 end;
15629 if oppFace.fCountVertices=3 then begin
15630 // then we can get rid of the opposite Face altogether
15631 hedgeOpp:=hedge.fOpposite.fPrevious.fOpposite;
15632 oppFace.fMark:=KRAFT_QUICKHULL_FACE_MARK_NON_DELETED;
15633 result:=oppFace;
15634 end else begin
15635 hedgeOpp:=hedge.fOpposite.fNext;
15636 if oppFace.fhe0=hedgeOpp.fPrevious then begin
15637 oppFace.fhe0:=hedgeOpp;
15638 end;
15639 hedgeOpp.fPrevious:=hedgeOpp.fPrevious.fPrevious;
15640 hedgeOpp.fPrevious.fNext:=hedgeOpp;
15641 end;
15642 hedge.fPrevious:=hedgePrev.fPrevious;
15643 hedge.fPrevious.fNext:=hedge;
15644 hedge.fOpposite:=hedgeOpp;
15645 hedgeOpp.fOpposite:=hedge;
15646 oppFace.ComputeNormalAndCentroid; // oppFace was modified, so need to recompute
15647 end else begin
15648 hedgePrev.fNext:=hedge;
15649 hedge.fPrevious:=hedgePrev;
15650 end;
15651 end;
15652
15653 procedure TKraftQuickHullFace.CheckConsistency;
15654 var hedge,hedgeOpp:TKraftQuickHullHalfEdge;
15655 oppFace:TKraftQuickHullFace;
15656 MaxD,d:double;
15657 CountFoundVertices:longint;
15658 begin
15659 Assert(fCountVertices>2,'Degenerated Face');
15660 MaxD:=0.0;
15661 CountFoundVertices:=0;
15662 hedge:=fhe0;
15663 repeat
15664 hedgeOpp:=hedge.fOpposite;
15665 Assert(assigned(hedgeOpp),'Unreflected half edge');
15666 Assert(hedgeOpp.fOpposite<>hedgeOpp,'Opposite half edge has wrong opposite half edge');
15667 Assert((hedgeOpp.Head=hedge.Tail) and (hedge.Head=hedgeOpp.tail),'Wrong reflected half edge');
15668 oppFace:=hedgeOpp.fFace;
15669 Assert(assigned(oppFace),'Opposite half edge has no Face');
15670 Assert(oppFace.fMark<>KRAFT_QUICKHULL_FACE_MARK_NON_DELETED,'Opposite half edge Face isn''t on hull');
15671 d:=abs(DistanceToPlane(Hedge.Head.Point));
15672 if d>MaxD then begin
15673 MaxD:=d;
15674 end;
15675 inc(CountFoundVertices);
15676 hedge:=hedge.fNext;
15677 until hedge=fhe0;
15678 Assert(CountFoundVertices=fCountVertices,'Wrong count of vertices');
15679 end;
15680
15681 function TKraftQuickHullFace.MergeAdjacentFace(const hedgeAdj:TKraftQuickHullHalfEdge;const Discarded:TList):longint;
15682 var oppFace,DiscardedFace:TKraftQuickHullFace;
15683 hedgeOpp,hedgeAdjPrev,hedgeAdjNext,hedgeOppPrev,hedgeOppNext,hedge:TKraftQuickHullHalfEdge;
15684 begin
15685 oppFace:=hedgeAdj.OppositeFace;
15686 result:=0;
15687
15688 Discarded.Clear;
15689
15690 Discarded.Add(oppFace);
15691 inc(result);
15692 oppFace.fMark:=KRAFT_QUICKHULL_FACE_MARK_NON_DELETED;
15693
15694 hedgeOpp:=hedgeAdj.fOpposite;
15695
15696 hedgeAdjPrev:=hedgeAdj.fPrevious;
15697 hedgeAdjNext:=hedgeAdj.fNext;
15698 hedgeOppPrev:=hedgeOpp.fPrevious;
15699 hedgeOppNext:=hedgeOpp.fNext;
15700
15701 while hedgeAdjPrev.OppositeFace=oppFace do begin
15702 hedgeAdjPrev:=hedgeAdjPrev.fPrevious;
15703 hedgeOppNext:=hedgeOppNext.fNext;
15704 end;
15705
15706 while hedgeAdjNext.OppositeFace=oppFace do begin
15707 hedgeOppPrev:=hedgeOppPrev.fPrevious;
15708 hedgeAdjNext:=hedgeAdjNext.fNext;
15709 end;
15710
15711 hedge:=hedgeOppNext;
15712 while hedge<>hedgeOppPrev.fNext do begin
15713 hedge.fFace:=self;
15714 hedge:=hedge.fNext;
15715 end;
15716
15717 if hedgeAdj=fhe0 then begin
15718 fhe0:=hedgeAdjNext;
15719 end;
15720
15721 // handle the half edges at the head
15722 DiscardedFace:=ConnectHalfEdges(hedgeOppPrev,hedgeAdjNext);
15723 if assigned(DiscardedFace) then begin
15724 Discarded.Add(DiscardedFace);
15725 inc(result);
15726 end;
15727
15728 // handle the half edges at the tail
15729 DiscardedFace:=ConnectHalfEdges(hedgeAdjPrev,hedgeOppNext);
15730 if assigned(DiscardedFace) then begin
15731 Discarded.Add(DiscardedFace);
15732 inc(result);
15733 end;
15734
15735 ComputeNormalAndCentroid;
15736 CheckConsistency;
15737
15738 end;
15739
15740 function TKraftQuickHullFace.AreaSquared(const hedge0,hedge1:TKraftQuickHullHalfEdge):double;
15741 var p0,p1,p2:TKraftQuickHullVector3D;
15742 dx1,dy1,dz1,dx2,dy2,dz2,x,y,z:double;
15743 begin
15744 p0:=hedge0.Tail.Point;
15745 p1:=hedge0.Head.Point;
15746 p2:=hedge1.Head.Point;
15747 dx1:=p1.x-p0.x;
15748 dy1:=p1.y-p0.y;
15749 dz1:=p1.z-p0.z;
15750 dx2:=p2.x-p0.x;
15751 dy2:=p2.y-p0.y;
15752 dz2:=p2.z-p0.z;
15753 x:=(dy1*dz2)-(dz1*dy2);
15754 y:=(dz1*dx2)-(dx1*dz2);
15755 z:=(dx1*dy2)-(dy1*dx2);
15756 result:=sqr(x)+sqr(y)+sqr(z);
15757 end;
15758
15759 procedure TKraftQuickHullFace.Triangulate(var NewFaces:TKraftQuickHullFaceList;const MinArea:double);
15760 var hedge,oppPrev:TKraftQuickHullHalfEdge;
15761 face0,Face:TKraftQuickHullFace;
15762 v0:TKraftQuickHullVertex;
15763 begin
15764 if fCountVertices>3 then begin
15765 v0:=fhe0.Head;
15766 hedge:=fhe0.fNext;
15767 oppPrev:=hedge.fOpposite;
15768 face0:=nil;
15769 hedge:=hedge.fNext;
15770 while hedge<>fhe0.fPrevious do begin
15771 Face:=TKraftQuickHullFace.CreateTriangle(fInstance,v0,hedge.fPrevious.Head,hedge.Head,MinArea);
15772 Face.fhe0.fNext.SetOpposite(oppPrev);
15773 Face.fhe0.fPrevious.SetOpposite(hedge.fOpposite);
15774 oppPrev:=Face.fhe0;
15775 NewFaces.Add(Face);
15776 if not assigned(face0) then begin
15777 face0:=Face;
15778 end;
15779 hedge:=hedge.fNext;
15780 end;
15781 hedge:=TKraftQuickHullHalfEdge.Create(fInstance,fhe0.fPrevious.fPrevious.Head,self);
15782 hedge.SetOpposite(oppPrev);
15783 hedge.fPrevious:=fhe0;
15784 hedge.fPrevious.fNext:=hedge;
15785 hedge.fNext:=fhe0.fPrevious;
15786 hedge.fNext.fPrevious:=hedge;
15787 ComputeNormalAndCentroid(MinArea);
15788 CheckConsistency;
15789 Face:=face0;
15790 while assigned(Face) do begin
15791 Face.CheckConsistency;
15792 Face:=Face.fNext;
15793 end;
15794 end;
15795 end;
15796
15797 constructor TKraftQuickHullHalfEdge.Create(const AInstance:TKraftQuickHull;const v:TKraftQuickHullVertex=nil;const f:TKraftQuickHullFace=nil);
15798 begin
15799 inherited Create;
15800 fInstance:=AInstance;
15801 fInstance.fGarbageCollectedClassInstances.Add(self);
15802 fVertex:=v;
15803 fFace:=f;
15804 fNext:=nil;
15805 fPrevious:=nil;
15806 fOpposite:=nil;
15807 end;
15808
15809 destructor TKraftQuickHullHalfEdge.Destroy;
15810 begin
15811 fInstance.fGarbageCollectedClassInstances.Remove(self);
15812 inherited Destroy;
15813 end;
15814
15815 procedure TKraftQuickHullHalfEdge.SetOpposite(const Edge:TKraftQuickHullHalfEdge);
15816 begin
15817 fOpposite:=Edge;
15818 Edge.fOpposite:=self;
15819 end;
15820
15821 function TKraftQuickHullHalfEdge.Head:TKraftQuickHullVertex;
15822 begin
15823 result:=fVertex;
15824 end;
15825
15826 function TKraftQuickHullHalfEdge.Tail:TKraftQuickHullVertex;
15827 begin
15828 if assigned(fPrevious) then begin
15829 result:=fPrevious.fVertex;
15830 end else begin
15831 result:=nil;
15832 end;
15833 end;
15834
15835 function TKraftQuickHullHalfEdge.OppositeFace:TKraftQuickHullFace;
15836 begin
15837 if assigned(fOpposite) then begin
15838 result:=fOpposite.fFace;
15839 end else begin
15840 result:=nil;
15841 end;
15842 end;
15843
15844 function TKraftQuickHullHalfEdge.Length:double;
15845 begin
15846 if assigned(fPrevious) then begin
15847 result:=fVertex.Point.Distance(fPrevious.fVertex.Point);
15848 end else begin
15849 result:=-1.0;
15850 end;
15851 end;
15852
15853 function TKraftQuickHullHalfEdge.LengthSquared:double;
15854 begin
15855 if assigned(fPrevious) then begin
15856 result:=fVertex.Point.DistanceSquared(fPrevious.fVertex.Point);
15857 end else begin
15858 result:=-1.0;
15859 end;
15860 end;
15861
15862 constructor TKraftQuickHull.Create;
15863 begin
15864 inherited Create;
15865 fGarbageCollectedClassInstances:=TList.Create;
15866 fFindIndex:=-1;
15867 fPointBuffer:=TList.Create;
15868 fVertexPointIndices:=TKraftQuickHullIntegerList.Create;
15869 fDiscardedFaces:=TList.Create;
15870 FillChar(fMinVertices,SizeOf(TKraftQuickHullThreeVertices),#0);
15871 FillChar(fMaxVertices,SizeOf(TKraftQuickHullThreeVertices),#0);
15872 FillChar(fVertexHashTable,SizeOf(TKraftQuickHullVertexHashTable),#0);
15873 fFaces:=TList.Create;
15874 fHorizon:=TList.Create;
15875 fNewFaces.Clear;
15876 fUnclaimed.Clear;
15877 fClaimed.Clear;
15878 fCountVertices:=0;
15879 fCountFaces:=0;
15880 fCountPoints:=0;
15881 fExplicitTolerance:=KRAFT_QUICKHULL_AUTOMATIC_TOLERANCE;
15882 fTolerance:=0.0;
15883 end;
15884
15885 destructor TKraftQuickHull.Destroy;
15886 begin
15887 fPointBuffer.Free;
15888 fVertexPointIndices.Free;
15889 fDiscardedFaces.Free;
15890 fFaces.Free;
15891 fHorizon.Free;
15892 while fGarbageCollectedClassInstances.Count>0 do begin
15893 TObject(fGarbageCollectedClassInstances[fGarbageCollectedClassInstances.Count-1]).Free;
15894 end;
15895 fGarbageCollectedClassInstances.Free;
15896 inherited Destroy;
15897 end;
15898
15899 procedure TKraftQuickHull.Reset;
15900 begin
15901 fPointBuffer.Clear;
15902 fVertexPointIndices.Clear;
15903 fFaces.Clear;
15904 fClaimed.Clear;
15905 fCountFaces:=0;
15906 fCountPoints:=0;
15907 end;
15908
15909 procedure TKraftQuickHull.AddPoint(const x,y,z:double);
15910 var Vertex:TKraftQuickHullVertex;
15911 Index,HashBucket:longint;
15912 begin
15913 HashBucket:=((round(x)*73856093) xor (round(y)*19349663) xor (round(z)*83492791)) and KRAFT_QUICKHULL_HASHMASK;
15914 Vertex:=fVertexHashTable[HashBucket];
15915 while assigned(Vertex) do begin
15916 if KraftQuickHullIsSameValue(Vertex.Point.x,x) and
15917 KraftQuickHullIsSameValue(Vertex.Point.y,y) and
15918 KraftQuickHullIsSameValue(Vertex.Point.z,z) then begin
15919 exit;
15920 end;
15921 Vertex:=Vertex.HashNext;
15922 end;
15923 Vertex:=TKraftQuickHullVertex.Create(self);
15924 Vertex.fPoint.x:=x;
15925 Vertex.fPoint.y:=y;
15926 Vertex.fPoint.z:=z;
15927 Vertex.HashNext:=fVertexHashTable[HashBucket];
15928 fVertexHashTable[HashBucket]:=Vertex;
15929 Index:=fPointBuffer.Add(Vertex);
15930 Vertex.Index:=Index;
15931 fVertexPointIndices.Add(Index);
15932 inc(fCountPoints);
15933 end;
15934
15935 procedure TKraftQuickHull.AddPointToFace(const AVertex:TKraftQuickHullVertex;const AFace:TKraftQuickHullFace);
15936 begin
15937 AVertex.Face:=AFace;
15938 if assigned(AFace.fOutside) then begin
15939 fClaimed.InsertBefore(AVertex,AFace.fOutside);
15940 end else begin
15941 fClaimed.Add(AVertex);
15942 end;
15943 AFace.fOutside:=AVertex;
15944 end;
15945
15946 procedure TKraftQuickHull.RemovePointFromFace(const AVertex:TKraftQuickHullVertex;const AFace:TKraftQuickHullFace);
15947 begin
15948 if AVertex=AFace.fOutside then begin
15949 if assigned(AVertex.Next) and (AVertex.Next.Face=AFAce) then begin
15950 AFace.fOutside:=AVertex.Next;
15951 end else begin
15952 AFace.fOutside:=nil;
15953 end;
15954 end;
15955 fClaimed.Delete(AVertex);
15956 end;
15957
15958 function TKraftQuickHull.RemoveAllPointsFromFace(const AFace:TKraftQuickHullFace):TKraftQuickHullVertex;
15959 var EndVertex:TKraftQuickHullVertex;
15960 begin
15961 if assigned(AFace.fOutside) then begin
15962 EndVertex:=AFace.fOutside;
15963 while assigned(EndVertex.Next) and (EndVertex.Next.Face=AFace) do begin
15964 EndVertex:=EndVertex.Next;
15965 end;
15966 fClaimed.Delete(AFace.fOutside,EndVertex);
15967 EndVertex.Next:=nil;
15968 result:=AFace.fOutside;
15969 end else begin
15970 result:=nil;
15971 end;
15972 end;
15973
15974 function TKraftQuickHull.FindHalfEdge(const Tail,Head:TKraftQuickHullVertex):TKraftQuickHullHalfEdge;
15975 var i:longint;
15976 Face:TKraftQuickHullFace;
15977 begin
15978 result:=nil;
15979 for i:=0 to fFaces.Count-1 do begin
15980 Face:=fFaces[i];
15981 result:=Face.FindEdge(Tail,Head);
15982 if assigned(result) then begin
15983 exit;
15984 end;
15985 end;
15986 end;
15987
15988 procedure TKraftQuickHull.Triangulate;
15989 const DOUBLE_PREC=2.2204460492503131e-16;
15990 var i:longint;
15991 Face:TKraftQuickHullFace;
15992 MinArea:double;
15993 begin
15994 MinArea:=1000.0*fCharLength*DOUBLE_PREC;
15995 fNewFaces.Clear;
15996 for i:=0 to fFaces.Count-1 do begin
15997 Face:=fFaces[i];
15998 if Face.fMark=KRAFT_QUICKHULL_FACE_MARK_VISIBLE then begin
15999 Face.Triangulate(fNewFaces,MinArea);
16000 end;
16001 end;
16002 Face:=fNewFaces.First;
16003 while assigned(Face) do begin
16004 fFaces.Add(Face);
16005 Face:=Face.fNext;
16006 end;
16007 ReindexFacesAndVertices;
16008 end;
16009
16010 procedure TKraftQuickHull.ComputeMinAndMax;
16011 const DOUBLE_PREC=2.2204460492503131e-16;
16012 var i:longint;
16013 MinVector,MaxVector,Point:TKraftQuickHullVector3D;
16014 Vertex:TKraftQuickHullVertex;
16015 begin
16016 for i:=0 to 2 do begin
16017 fMinVertices[i]:=fPointBuffer[0];
16018 fMaxVertices[i]:=fPointBuffer[0];
16019 end;
16020 Vertex:=fPointBuffer[0];
16021 MinVector:=Vertex.Point;
16022 MaxVector:=Vertex.Point;
16023 for i:=1 to fCountPoints-1 do begin
16024 Vertex:=fPointBuffer[i];
16025 Point:=Vertex.Point;
16026 if MinVector.x>Point.x then begin
16027 MinVector.x:=Point.x;
16028 fMinVertices[0]:=Vertex;
16029 end;
16030 if MaxVector.x<Point.x then begin
16031 MaxVector.x:=Point.x;
16032 fMaxVertices[0]:=Vertex;
16033 end;
16034 if MinVector.y>Point.y then begin
16035 MinVector.y:=Point.y;
16036 fMinVertices[1]:=Vertex;
16037 end;
16038 if MaxVector.y<Point.y then begin
16039 MaxVector.y:=Point.y;
16040 fMaxVertices[1]:=Vertex;
16041 end;
16042 if MinVector.z>Point.z then begin
16043 MinVector.z:=Point.z;
16044 fMinVertices[2]:=Vertex;
16045 end;
16046 if MaxVector.z<Point.z then begin
16047 MaxVector.z:=Point.z;
16048 fMaxVertices[2]:=Vertex;
16049 end;
16050 end;
16051 fCharLength:=Max(Max(MaxVector.x-MinVector.x,MaxVector.y-MinVector.y),MaxVector.z-MinVector.z);
16052 if fExplicitTolerance<0.0 then begin
16053 fTolerance:=(3.0*DOUBLE_PREC)*(Max(abs(MaxVector.x),abs(MinVector.x))+Max(abs(MaxVector.y),abs(MinVector.y))+Max(abs(MaxVector.z),abs(MinVector.z)));
16054 end else begin
16055 fTolerance:=fExplicitTolerance;
16056 end;
16057 end;
16058
16059 procedure TKraftQuickHull.CreateInitialSimplex;
16060 const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
16061 var MaxIndex,Index,OtherIndex:longint;
16062 MaxValue,Diff,MaxSquared,LenSquared,MaxDistance,d0,Distance:double;
16063 v:TKraftQuickHullVertex;
16064 MaxFace:TKraftQuickHullFace;
16065 Vertices:array[0..3] of TKraftQuickHullVertex;
16066 Triangles:array[0..3] of TKraftQuickHullFace;
16067 u01,Diff02,Normal,CrossProduct:TKraftQuickHullVector3D;
16068 begin
16069
16070 MaxValue:=0.0;
16071 MaxIndex:=0;
16072 for Index:=0 to 2 do begin
16073 Diff:=fMaxVertices[Index].Point.GetValue(Index)-fMinVertices[Index].Point.GetValue(Index);
16074 if MaxValue<Diff then begin
16075 MaxValue:=Diff;
16076 MaxIndex:=Index;
16077 end;
16078 end;
16079
16080 if MaxValue<=fTolerance then begin
16081 raise EKraftQuickHull.Create('Input points appear to be coincident');
16082 end;
16083
16084 // set first two vertices to be those with the greatest one dimensional separation
16085 Vertices[0]:=fMaxVertices[MaxIndex];
16086 Vertices[1]:=fMinVertices[MaxIndex];
16087
16088 // set third vertex to be the vertex farthest from the line between v0 and v1
16089 u01.Sub(Vertices[1].Point,Vertices[0].Point);
16090 u01.Normalize;
16091
16092 MaxSquared:=0.0;
16093 for Index:=0 to fCountPoints-1 do begin
16094 Diff02.Sub(TKraftQuickHullVertex(fPointBuffer[Index]).Point,Vertices[0].Point);
16095 CrossProduct.CrossProduct(u01,Diff02);
16096 LenSquared:=CrossProduct.LengthSquared;
16097 if (MaxSquared<LenSquared) and (fPointBuffer[Index]<>Vertices[0]) and (fPointBuffer[Index]<>Vertices[1]) then begin
16098 MaxSquared:=LenSquared;
16099 Vertices[2]:=fPointBuffer[Index];
16100 Normal:=CrossProduct;
16101 end;
16102 end;
16103 if sqrt(MaxSquared)<=(100.0*fTolerance) then begin
16104 raise EKraftQuickHull.Create('Input points appear to be colinear');
16105 end;
16106 Normal.Normalize();
16107
16108 MaxDistance:=0;
16109 d0:=Vertices[2].Point.Dot(Normal);
16110 for Index:=0 to fCountPoints-1 do begin
16111 Distance:=abs(TKraftQuickHullVertex(fPointBuffer[Index]).Point.Dot(Normal)-d0);
16112 if (MaxDistance<Distance) and (fPointBuffer[Index]<>Vertices[0]) and (fPointBuffer[Index]<>Vertices[1]) and (fPointBuffer[Index]<>Vertices[2]) then begin
16113 MaxDistance:=Distance;
16114 Vertices[3]:=fPointBuffer[Index];
16115 end;
16116 end;
16117 if sqrt(MaxDistance)<=(100.0*fTolerance) then begin
16118 raise EKraftQuickHull.Create('Input points appear to be coplanar');
16119 end;
16120
16121 if (Vertices[3].Point.Dot(Normal)-d0)<0.0 then begin
16122 Triangles[0]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[0],Vertices[1],Vertices[2]);
16123 Triangles[1]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[3],Vertices[1],Vertices[0]);
16124 Triangles[2]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[3],Vertices[2],Vertices[1]);
16125 Triangles[3]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[3],Vertices[0],Vertices[2]);
16126 for Index:=0 to 2 do begin
16127 OtherIndex:=ModuloThree[Index+1];
16128 Triangles[Index+1].fhe0.fNext.SetOpposite(Triangles[OtherIndex+1].fhe0);
16129 Triangles[Index+1].fhe0.fNext.fNext.SetOpposite(Triangles[0].GetEdge(OtherIndex));
16130 end;
16131 end else begin
16132 Triangles[0]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[0],Vertices[2],Vertices[1]);
16133 Triangles[1]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[3],Vertices[0],Vertices[1]);
16134 Triangles[2]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[3],Vertices[1],Vertices[2]);
16135 Triangles[3]:=TKraftQuickHullFace.CreateTriangle(self,Vertices[3],Vertices[2],Vertices[0]);
16136 for Index:=0 to 2 do begin
16137 OtherIndex:=ModuloThree[Index+1];
16138 Triangles[Index+1].fhe0.SetOpposite(Triangles[OtherIndex+1].fhe0.fNext);
16139 Triangles[Index+1].fhe0.fNext.fNext.SetOpposite(Triangles[0].GetEdge(ModuloThree[3-Index]));
16140 end;
16141 end;
16142
16143 for Index:=0 to 3 do begin
16144 fFaces.Add(Triangles[Index]);
16145 end;
16146
16147 for Index:=0 to fCountPoints-1 do begin
16148 v:=fPointBuffer[Index];
16149 if (v<>Vertices[0]) and (v<>Vertices[1]) and (v<>Vertices[2]) and (v<>Vertices[3]) then begin
16150 MaxDistance:=fTolerance;
16151 MaxFace:=nil;
16152 for OtherIndex:=0 to 3 do begin
16153 Distance:=Triangles[OtherIndex].DistanceToPlane(v.Point);
16154 if MaxDistance<Distance then begin
16155 MaxDistance:=Distance;
16156 MaxFace:=Triangles[OtherIndex];
16157 end;
16158 end;
16159 if assigned(MaxFace) then begin
16160 AddPointToFace(v,MaxFace);
16161 end;
16162 end;
16163 end;
16164
16165 end;
16166
16167 function TKraftQuickHull.NextPointToAdd:TKraftQuickHullVertex;
16168 var EyeFace:TKraftQuickHullFace;
16169 Vertex:TKraftQuickHullVertex;
16170 MaxDistance,Distance:double;
16171 begin
16172 result:=nil;
16173 if not fClaimed.IsEmpty then begin
16174 EyeFace:=fClaimed.First.Face;
16175 MaxDistance:=0.0;
16176 Vertex:=EyeFace.fOutside;
16177 while assigned(Vertex) and (Vertex.Face=EyeFace) do begin
16178 Distance:=EyeFace.DistanceToPlane(Vertex.Point);
16179 if MaxDistance<Distance then begin
16180 MaxDistance:=Distance;
16181 result:=Vertex;
16182 end;
16183 Vertex:=Vertex.Next;
16184 end;
16185 end;
16186 end;
16187
16188 procedure TKraftQuickHull.DeleteFacePoints(Face,AbsorbingFace:TKraftQuickHullFace);
16189 var FaceVertices,NextVertex,Vertex:TKraftQuickHullVertex;
16190 begin
16191 FaceVertices:=RemoveAllPointsFromFace(Face);
16192 if assigned(FaceVertices) then begin
16193 if assigned(AbsorbingFace) then begin
16194 NextVertex:=FaceVertices;
16195 Vertex:=NextVertex;
16196 while assigned(Vertex) do begin
16197 NextVertex:=Vertex.Next;
16198 if AbsorbingFace.DistanceToPlane(Vertex.Point)>fTolerance then begin
16199 AddPointToFace(Vertex,AbsorbingFace);
16200 end else begin
16201 fUnclaimed.Add(Vertex);
16202 end;
16203 Vertex:=NextVertex;
16204 end;
16205 end else begin
16206 fUnclaimed.AddAll(FaceVertices);
16207 end;
16208 end;
16209 end;
16210
16211 procedure TKraftQuickHull.CalculateHorizon(const EyePoint:TKraftQuickHullVector3D;Edge0:TKraftQuickHullHalfEdge;const Face:TKraftQuickHullFace;const Horizon:TList);
16212 var Edge:TKraftQuickHullHalfEdge;
16213 oppFace:TKraftQuickHullFace;
16214 begin
16215 //OldFaces.Add(Face);
16216 DeleteFacePoints(Face,nil);
16217 Face.fMark:=KRAFT_QUICKHULL_FACE_MARK_NON_DELETED;
16218 if assigned(Edge0) then begin
16219 Edge:=Edge0.fNext;
16220 end else begin
16221 Edge0:=Face.fhe0;
16222 Edge:=Edge0;
16223 end;
16224 Assert(assigned(Edge.fPrevious),'Edge.Previous is nil');
16225 Assert(Edge.fPrevious.fNext=Edge,'Edge.Previous.Next mismatches Edge');
16226 repeat
16227 oppFace:=Edge.OppositeFace;
16228 if oppFace.fMark=KRAFT_QUICKHULL_FACE_MARK_VISIBLE then begin
16229 if oppFace.DistanceToPlane(EyePoint)>fTolerance then begin
16230 CalculateHorizon(EyePoint,Edge.fOpposite,oppFace,Horizon);
16231 end else begin
16232 Horizon.Add(Edge);
16233 end;
16234 end;
16235 Edge:=Edge.fNext;
16236 until Edge=Edge0;
16237 end;
16238
16239 function TKraftQuickHull.AddAdjoiningFace(const EyeVertex:TKraftQuickHullVertex;const he:TKraftQuickHullHalfEdge):TKraftQuickHullHalfEdge;
16240 var Face:TKraftQuickHullFace;
16241 begin
16242 Face:=TKraftQuickHullFace.CreateTriangle(self,EyeVertex,he.Tail,he.Head);
16243 fFaces.Add(Face);
16244 Face.fhe0.fPrevious.SetOpposite(he.fOpposite);
16245 result:=Face.fhe0;
16246 end;
16247
16248 procedure TKraftQuickHull.AddNewFaces(const NewFaces:TKraftQuickHullFaceList;const EyeVertex:TKraftQuickHullVertex;const Horizon:TList);
16249 var Index:longint;
16250 hedgeSidePrev,hedgeSideBegin,horizonHe,hedgeSide:TKraftQuickHullHalfEdge;
16251 begin
16252 NewFaces.clear;
16253 hedgeSidePrev:=nil;
16254 hedgeSideBegin:=nil;
16255 for Index:=0 to Horizon.Count-1 do begin
16256 horizonHe:=Horizon[Index];
16257 hedgeSide:=AddAdjoiningFace(EyeVertex,horizonHe);
16258 if assigned(hedgeSidePrev) then begin
16259 hedgeSide.fNext.SetOpposite(hedgeSidePrev);
16260 end else begin
16261 hedgeSideBegin:=hedgeSide;
16262 end;
16263 NewFaces.Add(hedgeSide.fFace);
16264 hedgeSidePrev:=hedgeSide;
16265 end;
16266 hedgeSideBegin.fNext.setOpposite(hedgeSidePrev);
16267 end;
16268
16269 function TKraftQuickHull.OppFaceDistance(he:TKraftQuickHullHalfEdge):double;
16270 begin
16271 result:=he.fFace.DistanceToPlane(he.fOpposite.fFace.fCentroid);
16272 end;
16273
16274 function TKraftQuickHull.DoAdjacentMerge(const Face:TKraftQuickHullFace;const MergeType:longint):boolean;
16275 var Index,CountDiscarded:longint;
16276 hedge:TKraftQuickHullHalfEdge;
16277 oppFace:TKraftQuickHullFace;
16278 Convex,Merge:boolean;
16279 begin
16280 hedge:=Face.fhe0;
16281 Convex:=true;
16282 repeat
16283 oppFace:=hedge.OppositeFace;
16284 Merge:=false;
16285 if MergeType=KRAFT_QUICKHULL_MERGE_TYPE_NONCONVEX then begin
16286 // merge faces if they are definitively non-convex
16287 if (OppFaceDistance(hedge)>(-fTolerance)) or (OppFaceDistance(hedge.fOpposite)>(-fTolerance)) then begin
16288 Merge:=true;
16289 end;
16290 end else{if MergeType=KRAFT_QUICKHULL_MERGE_TYPE_NONCONVEX_WRT_LARGER_FACE then}begin
16291 // merge faces if they are parallel or non-convex wrt to the larger face; otherwise, just mark the face non-convex for the second pass.
16292 if Face.fArea>oppFace.fArea then begin
16293 if OppFaceDistance(hedge)>(-fTolerance) then begin
16294 Merge:=true;
16295 end else if OppFaceDistance(hedge.fOpposite)>(-fTolerance) then begin
16296 Convex:=false;
16297 end;
16298 end else begin
16299 if OppFaceDistance(hedge.fOpposite)>(-fTolerance) then begin
16300 Merge:=true;
16301 end else if OppFaceDistance(hedge)>(-fTolerance) then begin
16302 Convex:=false;
16303 end;
16304 end;
16305 end;
16306 if Merge then begin
16307 CountDiscarded:=Face.MergeAdjacentFace(hedge,fDiscardedFaces);
16308 for Index:=0 to CountDiscarded-1 do begin
16309 DeleteFacePoints(fDiscardedFaces[Index],Face);
16310 end;
16311 result:=true;
16312 exit;
16313 end;
16314 hedge:=hedge.fNext;
16315 until hedge=Face.fhe0;
16316 if not Convex then begin
16317 Face.fMark:=KRAFT_QUICKHULL_FACE_MARK_NON_CONVEX;
16318 end;
16319 result:=false;
16320 end;
16321
16322 procedure TKraftQuickHull.ResolveUnclaimedPoints(NewFaces:TKraftQuickHullFaceList);
16323 var NextVertex,Vertex:TKraftQuickHullVertex;
16324 MaxFace,NewFace:TKraftQuickHullFace;
16325 MaxDistance,Distance:double;
16326 begin
16327 NextVertex:=fUnclaimed.First;
16328 Vertex:=NextVertex;
16329 while assigned(Vertex) do begin
16330 NextVertex:=Vertex.Next;
16331 MaxDistance:=fTolerance;
16332 MaxFace:=nil;
16333 NewFace:=NewFaces.First;
16334 while assigned(NewFace) do begin
16335 if NewFace.fMark=KRAFT_QUICKHULL_FACE_MARK_VISIBLE then begin
16336 Distance:=NewFace.DistanceToPlane(Vertex.Point);
16337 if MaxDistance<Distance then begin
16338 MaxDistance:=Distance;
16339 MaxFace:=NewFace;
16340 end;
16341 if MaxDistance>(1000.0*fTolerance) then begin
16342 break;
16343 end;
16344 end;
16345 NewFace:=NewFace.fNext;
16346 end;
16347 if assigned(MaxFace) then begin
16348 AddPointToFace(Vertex,MaxFace);
16349 end;
16350 Vertex:=NextVertex;
16351 end;
16352 end;
16353
16354 procedure TKraftQuickHull.AddPointToHull(const EyeVertex:TKraftQuickHullVertex);
16355 var Face:TKraftQuickHullFace;
16356 begin
16357 fHorizon.Clear;
16358 fUnclaimed.Clear;
16359
16360 RemovePointFromFace(EyeVertex,EyeVertex.Face);
16361 CalculateHorizon(EyeVertex.Point,nil,EyeVertex.Face,fHorizon);
16362 fNewFaces.Clear;
16363 AddNewFaces(fNewFaces,EyeVertex,fHorizon);
16364
16365 // first merge pass ... merge faces which are non-convex as determined by the larger face
16366 Face:=fNewFaces.First;
16367 while assigned(Face) do begin
16368 if Face.fMark=KRAFT_QUICKHULL_FACE_MARK_VISIBLE then begin
16369 while DoAdjacentMerge(Face,KRAFT_QUICKHULL_MERGE_TYPE_NONCONVEX_WRT_LARGER_FACE) do begin
16370 end;
16371 end;
16372 Face:=Face.fNext;
16373 end;
16374
16375 // second merge pass ... merge faces which are non-convex wrt either face
16376 Face:=fNewFaces.First;
16377 while assigned(Face) do begin
16378 if Face.fMark=KRAFT_QUICKHULL_FACE_MARK_NON_CONVEX then begin
16379 Face.fMark:=KRAFT_QUICKHULL_FACE_MARK_VISIBLE;
16380 while DoAdjacentMerge(Face,KRAFT_QUICKHULL_MERGE_TYPE_NONCONVEX) do begin
16381 end;
16382 end;
16383 Face:=Face.fNext;
16384 end;
16385
16386 ResolveUnclaimedPoints(fNewFaces);
16387
16388 end;
16389
16390 procedure TKraftQuickHull.MarkFaceVertices(const Face:TKraftQuickHullFace;const Mark:longint);
16391 var he0,he:TKraftQuickHullHalfEdge;
16392 begin
16393 he0:=Face.GetFirstEdge;
16394 he:=he0;
16395 repeat
16396 he.Head.Index:=Mark;
16397 he:=he.fNext;
16398 until he=he0;
16399 end;
16400
16401 procedure TKraftQuickHull.ReindexFacesAndVertices;
16402 var Index:longint;
16403 Face:TKraftQuickHullFace;
16404 Vertex:TKraftQuickHullVertex;
16405 begin
16406 for Index:=0 to fCountPoints-1 do begin
16407 TKraftQuickHullVertex(fPointBuffer[Index]).Index:=-1;
16408 end;
16409
16410 // remove inactive faces and mark active vertices
16411 fCountFaces:=0;
16412 Index:=0;
16413 while Index<fFaces.Count do begin
16414 Face:=fFaces[Index];
16415 if Face.fMark<>KRAFT_QUICKHULL_FACE_MARK_VISIBLE then begin
16416 fFaces.Delete(Index);
16417 end else begin
16418 MarkFaceVertices(Face,0);
16419 inc(fCountFaces);
16420 inc(Index);
16421 end;
16422 end;
16423
16424 // reindex vertices
16425 fCountVertices:=0;
16426 for Index:=0 to fCountPoints-1 do begin
16427 Vertex:=fPointBuffer[Index];
16428 if Vertex.Index=0 then begin
16429 fVertexPointIndices[fCountVertices]:=Index;
16430 Vertex.Index:=fCountVertices;
16431 inc(fCountVertices);
16432 end;
16433 end;
16434
16435 end;
16436
16437 procedure TKraftQuickHull.Build(const MaximumVertices:longint=-1);
16438 var EyeVertex:TKraftQuickHullVertex;
16439 RemainToDoVertices:longint;
16440 begin
16441 ComputeMinAndMax;
16442 CreateInitialSimplex;
16443 EyeVertex:=NextPointToAdd;
16444 RemainToDoVertices:=MaximumVertices;
16445 while assigned(EyeVertex) and (RemainToDoVertices<>0) do begin
16446 AddPointToHull(EyeVertex);
16447 EyeVertex:=NextPointToAdd;
16448 if RemainToDoVertices>0 then begin
16449 dec(RemainToDoVertices);
16450 end;
16451 end;
16452 ReindexFacesAndVertices;
16453 end;
16454
16455 procedure TKraftQuickHull.GetFaceIndices(out OutputFace:TKraftQuickHullOutputFace;const Face:TKraftQuickHullFace;const Flags:longint);
16456 var CCW,IndexedFromOne,PointRelative:boolean;
16457 hedge:TKraftQuickHullHalfEdge;
16458 Count,Index:longint;
16459 begin
16460 SetLength(OutputFace,Face.fCountVertices);
16461 CCW:=(Flags and KRAFT_QUICKHULL_FACE_FLAG_CLOCKWISE)=0;
16462 IndexedFromOne:=(Flags and KRAFT_QUICKHULL_FACE_FLAG_INDEXED_FROM_ONE)<>0;
16463 PointRelative:=(Flags and KRAFT_QUICKHULL_FACE_FLAG_POINT_RELATIVE)<>0;
16464 hedge:=Face.fhe0;
16465 Count:=0;
16466 repeat
16467 Index:=hedge.Head.Index;
16468 if PointRelative then begin
16469 Index:=fVertexPointIndices[Index];
16470 end;
16471 if IndexedFromOne then begin
16472 inc(Index);
16473 end;
16474 OutputFace[Count]:=Index;
16475 inc(Count);
16476 if CCW then begin
16477 hedge:=hedge.fNext;
16478 end else begin
16479 hedge:=hedge.fPrevious;
16480 end;
16481 until hedge=Face.fhe0;
16482 end;
16483
16484 procedure TKraftQuickHull.GetVertices(out OutputVertices:TKraftQuickHullVector3DArray);
16485 var Index:longint;
16486 begin
16487 SetLength(OutputVertices,fCountVertices);
16488 for Index:=0 to fCountVertices-1 do begin
16489 OutputVertices[Index]:=TKraftQuickHullVertex(fPointBuffer[fVertexPointIndices[Index]]).Point;
16490 end;
16491 end;
16492
16493 procedure TKraftQuickHull.GetFaces(out OutputFaces:TKraftQuickHullOutputFaces);
16494 var Index:longint;
16495 begin
16496 SetLength(OutputFaces,fCountFaces);
16497 for Index:=0 to fCountFaces-1 do begin
16498 GetFaceIndices(OutputFaces[Index],fFaces[Index],0);
16499 end;
16500 end;
16501
16502 type PConvexHullGrahamScanVector=^TConvexHullGrahamScanVector;
16503 TConvexHullGrahamScanVector=record
16504 OriginalIndex:longint;
16505 Angle:double;
16506 LengthToAnchor:double;
16507 Vector:TConvexHullVector;
16508 end;
16509
16510 TConvexHullGrahamScanVectors=array of TConvexHullGrahamScanVector;
16511
16512 function CompareConvexHullGrahamScanVector(const a,b:pointer):longint;
16513 var va,vb:PConvexHullGrahamScanVector;
16514 begin
16515 va:=a;
16516 vb:=b;
16517 if va^.Angle<vb^.Angle then begin
16518 result:=-1;
16519 end else if va^.Angle>vb^.Angle then begin
16520 result:=1;
16521 end else if va^.LengthToAnchor<vb^.LengthToAnchor then begin
16522 result:=-1;
16523 end else if va^.LengthToAnchor<vb^.LengthToAnchor then begin
16524 result:=1;
16525 end else if va^.OriginalIndex<vb^.OriginalIndex then begin
16526 result:=-1;
16527 end else if va^.OriginalIndex>vb^.OriginalIndex then begin
16528 result:=1;
16529 end else begin
16530 result:=0;
16531 end;
16532 end;
16533
16534 procedure ConvexHullGrahamScan2D(var OriginalPoints:TConvexHullGrahamScanVectors;var Hull:TConvexHullGrahamScanVectors;const NormalAxis:TConvexHullVector);
16535 var CountOriginalPoints,Index,Count:longint;
16536 ProjectionLeft,ProjectionRight:double;
16537 Axis0,Axis1,xVector,Relative:TConvexHullVector;
16538 TempPoint:TConvexHullGrahamScanVector;
16539 IsConvex:boolean;
16540 a,b:PConvexHullGrahamScanVector;
16541 PointerToOriginalPoints:array of PConvexHullGrahamScanVector;
16542 begin
16543 PointerToOriginalPoints:=nil;
16544 try
16545 CountOriginalPoints:=length(OriginalPoints);
16546 if CountOriginalPoints<2 then begin
16547 Hull:=copy(OriginalPoints);
16548 end else begin
16549 ConvexHullGetPlaneSpace(NormalAxis,Axis0,Axis1);
16550 for Index:=1 to CountOriginalPoints-1 do begin
16551 ProjectionLeft:=ConvexHullVectorDot(OriginalPoints[Index].Vector,Axis0);
16552 ProjectionRight:=ConvexHullVectorDot(OriginalPoints[0].Vector,Axis0);
16553 if ProjectionLeft<ProjectionRight then begin
16554 TempPoint:=OriginalPoints[0];
16555 OriginalPoints[0]:=OriginalPoints[Index];
16556 OriginalPoints[Index]:=TempPoint;
16557 end;
16558 end;
16559 OriginalPoints[0].Angle:=-1.0e30;
16560 for Index:=1 to CountOriginalPoints-1 do begin
16561 xVector:=Axis0;
16562 Relative:=ConvexHullVectorSub(OriginalPoints[Index].Vector,OriginalPoints[0].Vector);
16563 OriginalPoints[Index].Angle:=ConvexHullVectorDot(ConvexHullVectorCross(xVector,Relative),NormalAxis)/ConvexHullVectorLength(Relative);
16564 end;
16565 for Index:=0 to CountOriginalPoints-1 do begin
16566 OriginalPoints[Index].LengthToAnchor:=ConvexHullVectorLengthSquared(ConvexHullVectorSub(OriginalPoints[Index].Vector,OriginalPoints[0].Vector));
16567 end;
16568 SetLength(PointerToOriginalPoints,CountOriginalPoints);
16569 for Index:=0 to CountOriginalPoints-1 do begin
16570 PointerToOriginalPoints[Index]:=@OriginalPoints[Index];
16571 end;
16572 IndirectIntroSort(@PointerToOriginalPoints[1],0,CountOriginalPoints-2,CompareConvexHullGrahamScanVector);
16573 Hull:=nil;
16574 SetLength(Hull,4);
16575 Count:=0;
16576 Index:=0;
16577 while Index<2 do begin
16578 Hull[Count]:=PointerToOriginalPoints[Index]^;
16579 inc(Count);
16580 inc(Index);
16581 end;
16582 while Index<CountOriginalPoints do begin
16583 IsConvex:=false;
16584 while (Count>1) and not IsConvex do begin
16585 a:=@Hull[Count-2];
16586 b:=@Hull[Count-1];
16587 IsConvex:=ConvexHullVectorDot(ConvexHullVectorCross(ConvexHullVectorSub(a^.Vector,b^.Vector),
16588 ConvexHullVectorSub(a^.Vector,PointerToOriginalPoints[Index]^.Vector)),
16589 NormalAxis)>0.0;
16590 if IsConvex then begin
16591 if (Count+1)>length(Hull) then begin
16592 SetLength(Hull,(Count+1)*2);
16593 end;
16594 Hull[Count]:=PointerToOriginalPoints[Index]^;
16595 inc(Count);
16596 end else begin
16597 dec(Count);
16598 end;
16599 end;
16600 inc(Index);
16601 end;
16602 SetLength(Hull,Count);
16603 end;
16604 finally
16605 SetLength(PointerToOriginalPoints,0);
16606 end;
16607 end;
16608
16609 constructor TKraftConvexHull.Create(const APhysics:TKraft);
16610 begin
16611
16612 inherited Create;
16613
16614 fPhysics:=APhysics;
16615
16616 fVertices:=nil;
16617 fCountVertices:=0;
16618
16619 fFaces:=nil;
16620 fCountFaces:=0;
16621
16622 fEdges:=nil;
16623 fCountEdges:=0;
16624
16625 FillChar(fSphere,SizeOf(TKraftSphere),AnsiChar(#0));
16626
16627 FillChar(fAABB,SizeOf(TKraftAABB),AnsiChar(#0));
16628
16629 fAngularMotionDisc:=0.0;
16630
16631 if assigned(fPhysics.fConvexHullLast) then begin
16632 fPhysics.fConvexHullLast.fNext:=self;
16633 fPrevious:=fPhysics.fConvexHullLast;
16634 end else begin
16635 fPhysics.fConvexHullFirst:=self;
16636 fPrevious:=nil;
16637 end;
16638 fPhysics.fConvexHullLast:=self;
16639 fNext:=nil;
16640
16641 end;
16642
16643 destructor TKraftConvexHull.Destroy;
16644 begin
16645
16646 SetLength(fVertices,0);
16647
16648 SetLength(fFaces,0);
16649
16650 SetLength(fEdges,0);
16651
16652 if assigned(fPrevious) then begin
16653 fPrevious.fNext:=fNext;
16654 end else if fPhysics.fConvexHullFirst=self then begin
16655 fPhysics.fConvexHullFirst:=fNext;
16656 end;
16657 if assigned(fNext) then begin
16658 fNext.fPrevious:=fPrevious;
16659 end else if fPhysics.fConvexHullLast=self then begin
16660 fPhysics.fConvexHullLast:=fPrevious;
16661 end;
16662 fPrevious:=nil;
16663 fNext:=nil;
16664
16665 inherited Destroy;
16666
16667 end;
16668
16669 procedure TKraftConvexHull.LoadFromStream(const AStream:TStream);
16670 var i,j:longint;
16671 begin
16672
16673 AStream.ReadBuffer(i,SizeOf(longint));
16674 fCountVertices:=i;
16675 SetLength(fVertices,fCountVertices);
16676 for i:=0 to fCountVertices-1 do begin
16677 AStream.ReadBuffer(fVertices[i].Position.x,SizeOf(TKraftScalar));
16678 AStream.ReadBuffer(fVertices[i].Position.y,SizeOf(TKraftScalar));
16679 AStream.ReadBuffer(fVertices[i].Position.z,SizeOf(TKraftScalar));
16680 AStream.ReadBuffer(fVertices[i].CountAdjacencies,SizeOf(longint));
16681 SetLength(fVertices[i].Adjacencies,fVertices[i].CountAdjacencies);
16682 for j:=0 to fVertices[i].CountAdjacencies-1 do begin
16683 AStream.ReadBuffer(fVertices[i].Adjacencies[j],SizeOf(longint));
16684 end;
16685 end;
16686
16687 AStream.ReadBuffer(i,SizeOf(longint));
16688 fCountFaces:=i;
16689 SetLength(fFaces,fCountFaces);
16690 for i:=0 to fCountFaces-1 do begin
16691 AStream.ReadBuffer(fFaces[i].Plane.Normal.x,SizeOf(TKraftScalar));
16692 AStream.ReadBuffer(fFaces[i].Plane.Normal.y,SizeOf(TKraftScalar));
16693 AStream.ReadBuffer(fFaces[i].Plane.Normal.z,SizeOf(TKraftScalar));
16694 AStream.ReadBuffer(fFaces[i].Plane.Distance,SizeOf(TKraftScalar));
16695 AStream.ReadBuffer(fFaces[i].CountVertices,SizeOf(longint));
16696 SetLength(fFaces[i].Vertices,fFaces[i].CountVertices);
16697 for j:=0 to fFaces[i].CountVertices-1 do begin
16698 AStream.ReadBuffer(fFaces[i].Vertices[j],SizeOf(longint));
16699 end;
16700 AStream.ReadBuffer(fFaces[i].EdgeVertexOffset,SizeOf(longint));
16701 end;
16702
16703 AStream.ReadBuffer(i,SizeOf(longint));
16704 fCountEdges:=i;
16705 SetLength(fEdges,fCountEdges);
16706 for i:=0 to fCountEdges-1 do begin
16707 AStream.ReadBuffer(fEdges[i].Vertices[0],SizeOf(longint));
16708 AStream.ReadBuffer(fEdges[i].Vertices[1],SizeOf(longint));
16709 AStream.ReadBuffer(fEdges[i].Faces[0],SizeOf(longint));
16710 AStream.ReadBuffer(fEdges[i].Faces[1],SizeOf(longint));
16711 end;
16712
16713 AStream.ReadBuffer(fSphere.Center.x,SizeOf(TKraftScalar));
16714 AStream.ReadBuffer(fSphere.Center.y,SizeOf(TKraftScalar));
16715 AStream.ReadBuffer(fSphere.Center.z,SizeOf(TKraftScalar));
16716 AStream.ReadBuffer(fSphere.Radius,SizeOf(TKraftScalar));
16717
16718 AStream.ReadBuffer(fAABB.Min.x,SizeOf(TKraftScalar));
16719 AStream.ReadBuffer(fAABB.Min.y,SizeOf(TKraftScalar));
16720 AStream.ReadBuffer(fAABB.Min.z,SizeOf(TKraftScalar));
16721 AStream.ReadBuffer(fAABB.Max.x,SizeOf(TKraftScalar));
16722 AStream.ReadBuffer(fAABB.Max.y,SizeOf(TKraftScalar));
16723 AStream.ReadBuffer(fAABB.Max.z,SizeOf(TKraftScalar));
16724
16725 AStream.ReadBuffer(fAngularMotionDisc,SizeOf(TKraftScalar));
16726
16727 AStream.ReadBuffer(fMassData.Inertia,SizeOf(TKraftMatrix3x3));
16728 AStream.ReadBuffer(fMassData.Center,SizeOf(TKraftVector3));
16729 AStream.ReadBuffer(fMassData.Mass,SizeOf(TKraftScalar));
16730 AStream.ReadBuffer(fMassData.Volume,SizeOf(TKraftScalar));
16731
16732 AStream.ReadBuffer(fCentroid.x,SizeOf(TKraftScalar));
16733 AStream.ReadBuffer(fCentroid.y,SizeOf(TKraftScalar));
16734 AStream.ReadBuffer(fCentroid.z,SizeOf(TKraftScalar));
16735
16736 end;
16737
16738 procedure TKraftConvexHull.SaveToStream(const AStream:TStream);
16739 var i,j:longint;
16740 begin
16741
16742 i:=fCountVertices;
16743 AStream.WriteBuffer(i,SizeOf(longint));
16744 for i:=0 to fCountVertices-1 do begin
16745 AStream.WriteBuffer(fVertices[i].Position.x,SizeOf(TKraftScalar));
16746 AStream.WriteBuffer(fVertices[i].Position.y,SizeOf(TKraftScalar));
16747 AStream.WriteBuffer(fVertices[i].Position.z,SizeOf(TKraftScalar));
16748 AStream.WriteBuffer(fVertices[i].CountAdjacencies,SizeOf(longint));
16749 for j:=0 to fVertices[i].CountAdjacencies-1 do begin
16750 AStream.WriteBuffer(fVertices[i].Adjacencies[j],SizeOf(longint));
16751 end;
16752 end;
16753
16754 i:=fCountFaces;
16755 AStream.WriteBuffer(i,SizeOf(longint));
16756 for i:=0 to fCountFaces-1 do begin
16757 AStream.WriteBuffer(fFaces[i].Plane.Normal.x,SizeOf(TKraftScalar));
16758 AStream.WriteBuffer(fFaces[i].Plane.Normal.y,SizeOf(TKraftScalar));
16759 AStream.WriteBuffer(fFaces[i].Plane.Normal.z,SizeOf(TKraftScalar));
16760 AStream.WriteBuffer(fFaces[i].Plane.Distance,SizeOf(TKraftScalar));
16761 AStream.WriteBuffer(fFaces[i].CountVertices,SizeOf(longint));
16762 for j:=0 to fFaces[i].CountVertices-1 do begin
16763 AStream.WriteBuffer(fFaces[i].Vertices[j],SizeOf(longint));
16764 end;
16765 AStream.WriteBuffer(fFaces[i].EdgeVertexOffset,SizeOf(longint));
16766 end;
16767
16768 i:=fCountEdges;
16769 AStream.WriteBuffer(i,SizeOf(longint));
16770 for i:=0 to fCountEdges-1 do begin
16771 AStream.WriteBuffer(fEdges[i].Vertices[0],SizeOf(longint));
16772 AStream.WriteBuffer(fEdges[i].Vertices[1],SizeOf(longint));
16773 AStream.WriteBuffer(fEdges[i].Faces[0],SizeOf(longint));
16774 AStream.WriteBuffer(fEdges[i].Faces[1],SizeOf(longint));
16775 end;
16776
16777 AStream.WriteBuffer(fSphere.Center.x,SizeOf(TKraftScalar));
16778 AStream.WriteBuffer(fSphere.Center.y,SizeOf(TKraftScalar));
16779 AStream.WriteBuffer(fSphere.Center.z,SizeOf(TKraftScalar));
16780 AStream.WriteBuffer(fSphere.Radius,SizeOf(TKraftScalar));
16781
16782 AStream.WriteBuffer(fAABB.Min.x,SizeOf(TKraftScalar));
16783 AStream.WriteBuffer(fAABB.Min.y,SizeOf(TKraftScalar));
16784 AStream.WriteBuffer(fAABB.Min.z,SizeOf(TKraftScalar));
16785 AStream.WriteBuffer(fAABB.Max.x,SizeOf(TKraftScalar));
16786 AStream.WriteBuffer(fAABB.Max.y,SizeOf(TKraftScalar));
16787 AStream.WriteBuffer(fAABB.Max.z,SizeOf(TKraftScalar));
16788
16789 AStream.WriteBuffer(fAngularMotionDisc,SizeOf(TKraftScalar));
16790
16791 AStream.WriteBuffer(fMassData.Inertia,SizeOf(TKraftMatrix3x3));
16792 AStream.WriteBuffer(fMassData.Center,SizeOf(TKraftVector3));
16793 AStream.WriteBuffer(fMassData.Mass,SizeOf(TKraftScalar));
16794 AStream.WriteBuffer(fMassData.Volume,SizeOf(TKraftScalar));
16795
16796 AStream.WriteBuffer(fCentroid.x,SizeOf(TKraftScalar));
16797 AStream.WriteBuffer(fCentroid.y,SizeOf(TKraftScalar));
16798 AStream.WriteBuffer(fCentroid.z,SizeOf(TKraftScalar));
16799
16800 end;
16801
16802 function TKraftConvexHull.AddVertex(const AVertex:TKraftVector3):longint;
16803 var Vertex:PKraftConvexHullVertex;
16804 begin
16805 result:=fCountVertices;
16806 inc(fCountVertices);
16807 if fCountVertices>length(fVertices) then begin
16808 SetLength(fVertices,fCountVertices*2);
16809 end;
16810 Vertex:=@fVertices[result];
16811 Vertex^.Position:=AVertex;
16812 Vertex^.CountAdjacencies:=0;
16813 end;
16814
16815 procedure TKraftConvexHull.Load(const AVertices:PKraftVector3;const ACountVertices:longint);
16816 var Index:longint;
16817 Vertex:PKraftConvexHullVertex;
16818 begin
16819 fCountVertices:=ACountVertices;
16820 SetLength(fVertices,fCountVertices);
16821 for Index:=0 to fCountVertices-1 do begin
16822 Vertex:=@fVertices[Index];
16823 Vertex^.Position:=PKraftVector3s(AVertices)^[Index];
16824 Vertex^.CountAdjacencies:=0;
16825 end;
16826 end;
16827
16828 procedure TKraftConvexHull.Scale(const WithFactor:TKraftScalar);
16829 var Index:longint;
16830 begin
16831 for Index:=0 to fCountVertices-1 do begin
16832 Vector3Scale(fVertices[Index].Position,WithFactor);
16833 end;
16834 end;
16835
16836 procedure TKraftConvexHull.Scale(const WithVector:TKraftVector3);
16837 var Index:longint;
16838 begin
16839 for Index:=0 to fCountVertices-1 do begin
16840 Vector3Scale(fVertices[Index].Position,WithVector.x,WithVector.y,WithVector.z);
16841 end;
16842 end;
16843
16844 procedure TKraftConvexHull.Transform(const WithMatrix:TKraftMatrix3x3);
16845 var Index:longint;
16846 begin
16847 for Index:=0 to fCountVertices-1 do begin
16848 Vector3MatrixMul(fVertices[Index].Position,WithMatrix);
16849 end;
16850 end;
16851
16852 procedure TKraftConvexHull.Transform(const WithMatrix:TKraftMatrix4x4);
16853 var Index:longint;
16854 begin
16855 for Index:=0 to fCountVertices-1 do begin
16856 Vector3MatrixMul(fVertices[Index].Position,WithMatrix);
16857 end;
16858 end;
16859
16860 procedure TKraftConvexHull.Build(const AMaximumCountConvexHullPoints:longint=-1;const AUserDefinedTolerance:double=-1.0);
16861 const HashBits=8;
16862 HashSize=1 shl HashBits;
16863 HashMask=HashSize-1;
16864 ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
16865 DOUBLE_PREC:double=2.2204460492503131e-16;
16866 type PTempFaceEdgeHashItem=^TTempFaceEdgeHashItem;
16867 TTempFaceEdgeHashItem=record
16868 Next:longint;
16869 Hash:longword;
16870 Edge:longint;
16871 Face:longint;
16872 FaceEdge:longint;
16873 FaceEdgeVertexA:longint;
16874 FaceEdgeVertexB:longint;
16875 end;
16876 PTempFaceEdge=^TTempFaceEdge;
16877 TTempFaceEdge=record
16878 Face:longint;
16879 Twin:longint;
16880 Vertices:array[0..1] of longint;
16881 end;
16882 var PointIndex,TriangleIndex,TriangleVertexIndex,VertexIndex,OtherVertexIndex,{OtherTriangleIndex,}Index,
16883 OtherTriangleVertexIndex,SearchIndex,CountTempFaceEdges,FaceIndex,EdgeVertexOffset,TempFaceEdgeIndex,
16884 {OtherTempFaceEdgeIndex,}CountTempFaceEdgeHashItems,TempFaceEdgeHashItemIndex,{v0,v1,v2,}
16885 {FoundSharedVertex,}FaceVertexIndex,{OtherFaceVertexIndex,}CountPoints,HashBucket,CountTriangles:longint;
16886 TempFaceEdgeHash:longword;
16887 TempFaceEdgeHashItem:PTempFaceEdgeHashItem;
16888 TempPoints:TConvexHullVectors;
16889 TempPointHashTable:array of longint;
16890 TempTriangles:TConvexHullTriangles;
16891 Vertex:PKraftConvexHullVertex;
16892 Face:PKraftConvexHullFace;
16893 Edge:PKraftConvexHullEdge;
16894 //pa,pb:TKraftPlane;
16895 //vn,NewPlaneNormal:TKraftVector3;
16896 //Processed:array of boolean;
16897 TempFaceEdges:array of TTempFaceEdge;
16898 TempFaceEdge:PTempFaceEdge;
16899 Found:boolean;
16900 TempFaceEdgeHashItems:array of TTempFaceEdgeHashItem;
16901 TempFaceEdgeHashTable:array of longint;
16902 {TempInputPolygons,}TempOutputPolygons:TConvexHullPolygons;
16903 TempPolygon:PConvexHullPolygon;
16904 QuickHullInstance:TKraftQuickHull;
16905 QuickHullVertex:TKraftQuickHullVertex;
16906 QuickHullFaces:TKraftQuickHullOutputFaces;
16907 MinBounds,MaxBounds,a,b,c,Centroid,Normal:TConvexHullVector;
16908 Tolerance,CharLength,NearTolerance:double;
16909 Last,Current:PConvexHullVector;
16910 Plane:TConvexHullPlane;
16911 InputIsCoplanar:boolean;
16912 TemporaryGrahamScanVectors,HullGrahamScanVectors:TConvexHullGrahamScanVectors;
16913 Triangle:PConvexHullTriangle;
16914 begin
16915 fFaces:=nil;
16916 fCountFaces:=0;
16917 fEdges:=nil;
16918 fCountEdges:=0;
16919
16920 TempPoints:=nil;
16921 TempTriangles:=nil;
16922 TempFaceEdges:=nil;
16923 TempFaceEdgeHashItems:=nil;
16924 TempFaceEdgeHashTable:=nil;
16925 //TempInputPolygons.Items:=nil;
16926 TempOutputPolygons.Items:=nil;
16927 try
16928
16929 if fCountVertices<1 then begin
16930 raise EKraftDegeneratedConvexHull.Create('Degenerated convex hull');
16931 end;
16932
16933 Vertex:=@fVertices[0];
16934 MinBounds.x:=Vertex^.Position.x;
16935 MinBounds.y:=Vertex^.Position.y;
16936 MinBounds.z:=Vertex^.Position.z;
16937 MaxBounds.x:=Vertex^.Position.x;
16938 MaxBounds.y:=Vertex^.Position.y;
16939 MaxBounds.z:=Vertex^.Position.z;
16940 for Index:=0 to fCountVertices-1 do begin
16941 Vertex:=@fVertices[Index];
16942 if MinBounds.x>Vertex^.Position.x then begin
16943 MinBounds.x:=Vertex^.Position.x;
16944 end;
16945 if MinBounds.y>Vertex^.Position.y then begin
16946 MinBounds.y:=Vertex^.Position.y;
16947 end;
16948 if MinBounds.z>Vertex^.Position.z then begin
16949 MinBounds.z:=Vertex^.Position.z;
16950 end;
16951 if MaxBounds.x<Vertex^.Position.x then begin
16952 MaxBounds.x:=Vertex^.Position.x;
16953 end;
16954 if MaxBounds.y<Vertex^.Position.y then begin
16955 MaxBounds.y:=Vertex^.Position.y;
16956 end;
16957 if MaxBounds.z<Vertex^.Position.z then begin
16958 MaxBounds.z:=Vertex^.Position.z;
16959 end;
16960 end;
16961
16962 if AUserDefinedTolerance>0.0 then begin
16963 Tolerance:=AUserDefinedTolerance;
16964 end else begin
16965 Tolerance:=Max(DOUBLE_PREC,(3.0*DOUBLE_PREC)*(Max(abs(MaxBounds.x),abs(MaxBounds.x))+Max(abs(MaxBounds.y),abs(MaxBounds.y))+Max(abs(MaxBounds.z),abs(MaxBounds.z))));
16966 end;
16967
16968 CharLength:=Max(Max(MaxBounds.x-MaxBounds.x,MaxBounds.y-MaxBounds.y),MaxBounds.z-MaxBounds.z);
16969
16970 NearTolerance:=Max(DOUBLE_PREC,(3.0*DOUBLE_PREC)*CharLength);
16971
16972 // Remove duplicate and too near points
16973 TempPointHashTable:=nil;
16974 try
16975 SetLength(TempPoints,fCountVertices);
16976 CountPoints:=0;
16977 try
16978 SetLength(TempPointHashTable,HashSize);
16979 for Index:=0 to HashSize-1 do begin
16980 TempPointHashTable[Index]:=-1;
16981 end;
16982 for PointIndex:=0 to fCountVertices-1 do begin
16983 Vertex:=@fVertices[PointIndex];
16984 HashBucket:=((round(Vertex^.Position.x)*73856093) xor (round(Vertex^.Position.y)*19349663) xor (round(Vertex^.Position.z)*83492791)) and HashMask;
16985 Index:=TempPointHashTable[HashBucket];
16986 while Index>=0 do begin
16987 if (ConvexHullIsSameValue(TempPoints[Index].x,Vertex^.Position.x) and
16988 ConvexHullIsSameValue(TempPoints[Index].y,Vertex^.Position.y) and
16989 ConvexHullIsSameValue(TempPoints[Index].z,Vertex^.Position.z)) or
16990 (sqrt(sqr(TempPoints[Index].x-Vertex^.Position.x)+
16991 sqr(TempPoints[Index].y-Vertex^.Position.y)+
16992 sqr(TempPoints[Index].z-Vertex^.Position.z))<NearTolerance) then begin
16993 break;
16994 end;
16995 Index:=TempPoints[Index].HashNext;
16996 end;
16997 if Index<0 then begin
16998 Index:=CountPoints;
16999 inc(CountPoints);
17000 TempPoints[Index].x:=Vertex^.Position.x;
17001 TempPoints[Index].y:=Vertex^.Position.y;
17002 TempPoints[Index].z:=Vertex^.Position.z;
17003 TempPoints[Index].HashNext:=TempPointHashTable[HashBucket];
17004 TempPointHashTable[HashBucket]:=Index;
17005 end;
17006 end;
17007 finally
17008 SetLength(TempPoints,CountPoints);
17009 end;
17010 finally
17011 SetLength(TempPointHashTable,0);
17012 end;
17013
17014 if CountPoints<3 then begin
17015
17016 raise EKraftDegeneratedConvexHull.Create('Degenerated convex hull');
17017
17018 end else if CountPoints=3 then begin
17019
17020 TempOutputPolygons.Count:=2;
17021 SetLength(TempOutputPolygons.Items,TempOutputPolygons.Count);
17022
17023 TempOutputPolygons.Items[0].Count:=3;
17024 SetLength(TempOutputPolygons.Items[0].Indices,TempOutputPolygons.Items[0].Count);
17025 TempOutputPolygons.Items[0].Indices[0]:=0;
17026 TempOutputPolygons.Items[0].Indices[1]:=1;
17027 TempOutputPolygons.Items[0].Indices[2]:=2;
17028
17029 TempOutputPolygons.Items[1].Count:=3;
17030 SetLength(TempOutputPolygons.Items[1].Indices,TempOutputPolygons.Items[1].Count);
17031 TempOutputPolygons.Items[1].Indices[0]:=0;
17032 TempOutputPolygons.Items[1].Indices[1]:=2;
17033 TempOutputPolygons.Items[1].Indices[2]:=1;
17034
17035 end else begin
17036
17037 a:=ConvexHullVectorSub(TempPoints[0],TempPoints[3]);
17038 b:=ConvexHullVectorSub(TempPoints[1],TempPoints[3]);
17039 c:=ConvexHullVectorSub(TempPoints[2],TempPoints[3]);
17040
17041 if (CountPoints=4) and (((a.x*((b.z*c.y)-(b.y*c.z)))+(a.y*((b.x*c.z)-(b.z*c.x)))+(a.z*((b.y*c.x)-(b.x*c.y))))<Tolerance) then begin
17042
17043 TempOutputPolygons.Count:=2;
17044 SetLength(TempOutputPolygons.Items,TempOutputPolygons.Count);
17045
17046 TempOutputPolygons.Items[0].Count:=4;
17047 SetLength(TempOutputPolygons.Items[0].Indices,TempOutputPolygons.Items[0].Count);
17048 TempOutputPolygons.Items[0].Indices[0]:=0;
17049 TempOutputPolygons.Items[0].Indices[1]:=1;
17050 TempOutputPolygons.Items[0].Indices[2]:=2;
17051 TempOutputPolygons.Items[0].Indices[3]:=3;
17052
17053 TempOutputPolygons.Items[1].Count:=4;
17054 SetLength(TempOutputPolygons.Items[1].Indices,TempOutputPolygons.Items[1].Count);
17055 TempOutputPolygons.Items[1].Indices[0]:=3;
17056 TempOutputPolygons.Items[1].Indices[1]:=2;
17057 TempOutputPolygons.Items[1].Indices[2]:=1;
17058 TempOutputPolygons.Items[1].Indices[3]:=0;
17059
17060 end else begin
17061
17062 // Compute newell plane for coplanarity check
17063 Centroid.x:=0.0;
17064 Centroid.y:=0.0;
17065 Centroid.z:=0.0;
17066 Normal.x:=0.0;
17067 Normal.y:=0.0;
17068 Normal.z:=0.0;
17069 Last:=@TempPoints[CountPoints-1];
17070 for VertexIndex:=0 to CountPoints-1 do begin
17071 Current:=@TempPoints[VertexIndex];
17072 Normal.x:=Normal.x+((Last^.y-Current^.y)*(Last^.z+Current^.z));
17073 Normal.y:=Normal.y+((Last^.z-Current^.z)*(Last^.x+Current^.x));
17074 Normal.z:=Normal.z+((Last^.x-Current^.x)*(Last^.y+Current^.y));
17075 Centroid.x:=Centroid.x+Current^.x;
17076 Centroid.y:=Centroid.y+Current^.y;
17077 Centroid.z:=Centroid.z+Current^.z;
17078 Last:=Current;
17079 end;
17080 if ConvexHullIsSameValue(Normal.x,0.0) and ConvexHullIsSameValue(Normal.y,0.0) and ConvexHullIsSameValue(Normal.z,0.0) then begin
17081 Normal.x:=0.0;
17082 Normal.y:=1.0;
17083 Normal.z:=0.0;
17084 end;
17085 Plane.Normal:=ConvexHullVectorNormalize(Normal);
17086 Plane.Distance:=-ConvexHullVectorDot(Plane.Normal,ConvexHullVectorDivide(Centroid,CountPoints));
17087
17088 // Now check for coplanarity
17089 InputIsCoplanar:=true;
17090 for Index:=0 to CountPoints-1 do begin
17091 Current:=@TempPoints[Index];
17092 if ((Plane.Normal.x*Current^.x)+(Plane.Normal.y*Current^.y)+(Plane.Normal.z*Current^.z)+Plane.Distance)>Tolerance then begin
17093 InputIsCoplanar:=false;
17094 break;
17095 end;
17096 end;
17097
17098 if InputIsCoplanar then begin
17099
17100 TemporaryGrahamScanVectors:=nil;
17101 HullGrahamScanVectors:=nil;
17102 try
17103
17104 SetLength(TemporaryGrahamScanVectors,CountPoints);
17105 for Index:=0 to CountPoints-1 do begin
17106 TemporaryGrahamScanVectors[Index].OriginalIndex:=Index;
17107 TemporaryGrahamScanVectors[Index].Vector:=TempPoints[Index];
17108 end;
17109
17110 ConvexHullGrahamScan2D(TemporaryGrahamScanVectors,HullGrahamScanVectors,Plane.Normal);
17111
17112 if length(HullGrahamScanVectors)<3 then begin
17113 raise EKraftDegeneratedConvexHull.Create('Degenerated convex hull');
17114 end;
17115
17116 CountPoints:=length(HullGrahamScanVectors);
17117 SetLength(TempPoints,CountPoints);
17118 for Index:=0 to CountPoints-1 do begin
17119 TempPoints[Index]:=HullGrahamScanVectors[Index].Vector;
17120 end;
17121
17122 TempOutputPolygons.Count:=2;
17123 SetLength(TempOutputPolygons.Items,TempOutputPolygons.Count);
17124
17125 TempOutputPolygons.Items[0].Count:=CountPoints;
17126 SetLength(TempOutputPolygons.Items[0].Indices,TempOutputPolygons.Items[0].Count);
17127 for Index:=0 to CountPoints-1 do begin
17128 TempOutputPolygons.Items[0].Indices[Index]:=Index;
17129 end;
17130
17131 TempOutputPolygons.Items[1].Count:=CountPoints;
17132 SetLength(TempOutputPolygons.Items[1].Indices,TempOutputPolygons.Items[1].Count);
17133 for Index:=0 to CountPoints-1 do begin
17134 TempOutputPolygons.Items[1].Indices[Index]:=CountPoints-(Index+1);
17135 end;
17136
17137 finally
17138 SetLength(TemporaryGrahamScanVectors,0);
17139 SetLength(HullGrahamScanVectors,0);
17140 end;
17141
17142 end else begin
17143
17144 if AMaximumCountConvexHullPoints>0 then begin
17145
17146 // Here we're using triangular-output-based stan hull as maximum vertex count prefilter for the
17147 // non-triangular-output-based quick hull implementation
17148 StanHullProcess(TempPoints,TempTriangles,AMaximumCountConvexHullPoints,AUserDefinedTolerance);
17149
17150 // Throw the temporary output triangles of the stan hull algorithm away, because we do need only the filtered remain points
17151 SetLength(TempTriangles,0);
17152
17153 end;
17154
17155 QuickHullInstance:=TKraftQuickHull.Create;
17156 try
17157 if AUserDefinedTolerance>0.0 then begin
17158 QuickHullInstance.fExplicitTolerance:=AUserDefinedTolerance;
17159 end;
17160 QuickHullInstance.Reset;
17161 for PointIndex:=0 to length(TempPoints)-1 do begin
17162 QuickHullInstance.AddPoint(TempPoints[PointIndex].x,TempPoints[PointIndex].y,TempPoints[PointIndex].z);
17163 end;
17164 QuickHullInstance.Build(AMaximumCountConvexHullPoints);
17165 SetLength(TempPoints,QuickHullInstance.fCountVertices);
17166 for PointIndex:=0 to QuickHullInstance.fCountVertices-1 do begin
17167 QuickHullVertex:=TKraftQuickHullVertex(QuickHullInstance.fPointBuffer[QuickHullInstance.fVertexPointIndices[PointIndex]]);
17168 TempPoints[PointIndex].x:=QuickHullVertex.Point.x;
17169 TempPoints[PointIndex].y:=QuickHullVertex.Point.y;
17170 TempPoints[PointIndex].z:=QuickHullVertex.Point.z;
17171 end;
17172 QuickHullFaces:=nil;
17173 try
17174 QuickHullInstance.GetFaces(QuickHullFaces);
17175 SetLength(TempOutputPolygons.Items,length(QuickHullFaces));
17176 TempOutputPolygons.Count:=length(QuickHullFaces);
17177 for FaceIndex:=0 to TempOutputPolygons.Count-1 do begin
17178 TempPolygon:[email protected][FaceIndex];
17179 TempPolygon^.Count:=length(QuickHullFaces[FaceIndex]);
17180 SetLength(TempPolygon^.Indices,TempPolygon^.Count);
17181 for VertexIndex:=0 to TempPolygon^.Count-1 do begin
17182 TempPolygon^.Indices[VertexIndex]:=QuickHullFaces[FaceIndex,VertexIndex];
17183 end;
17184 end;
17185 finally
17186 SetLength(QuickHullFaces,0);
17187 end;
17188 finally
17189 QuickHullInstance.Free;
17190 end;
17191
17192 end;
17193
17194 end;
17195
17196 end;
17197
17198 for FaceIndex:=0 to TempOutputPolygons.Count-1 do begin
17199 ConvexHullComputePolygonNewellPlane(TempPoints,TempOutputPolygons.Items[FaceIndex]);
17200 end;
17201
17202 //SetLength(TempInputPolygons.Items,0);
17203
17204 fCountVertices:=length(TempPoints);
17205 SetLength(fVertices,fCountVertices);
17206 for PointIndex:=0 to fCountVertices-1 do begin
17207 fVertices[PointIndex].Position.x:=TempPoints[PointIndex].x;
17208 fVertices[PointIndex].Position.y:=TempPoints[PointIndex].y;
17209 fVertices[PointIndex].Position.z:=TempPoints[PointIndex].z;
17210 end;
17211
17212 // Copy face poylgons
17213 SetLength(fFaces,TempOutputPolygons.Count);
17214 fCountFaces:=TempOutputPolygons.Count;
17215 CountTempFaceEdges:=0;
17216 EdgeVertexOffset:=0;
17217 for FaceIndex:=0 to TempOutputPolygons.Count-1 do begin
17218 Face:=@fFaces[FaceIndex];
17219 TempPolygon:[email protected][FaceIndex];
17220 Face^.Plane.Normal.x:=TempPolygon^.Plane.Normal.x;
17221 Face^.Plane.Normal.y:=TempPolygon^.Plane.Normal.y;
17222 Face^.Plane.Normal.z:=TempPolygon^.Plane.Normal.z;
17223 Face^.Plane.Distance:=TempPolygon^.Plane.Distance;
17224 Face^.CountVertices:=TempPolygon^.Count;
17225 SetLength(Face^.Vertices,Face^.CountVertices);
17226 for VertexIndex:=0 to Face^.CountVertices-1 do begin
17227 Face^.Vertices[VertexIndex]:=TempPolygon^.Indices[VertexIndex];
17228 end;
17229 Face^.EdgeVertexOffset:=EdgeVertexOffset;
17230 inc(EdgeVertexOffset,Face^.CountVertices);
17231 for VertexIndex:=0 to Face^.CountVertices-1 do begin
17232 OtherVertexIndex:=VertexIndex+1;
17233 if OtherVertexIndex>=Face^.CountVertices then begin
17234 dec(OtherVertexIndex,Face^.CountVertices);
17235 end;
17236 TempFaceEdgeIndex:=CountTempFaceEdges;
17237 inc(CountTempFaceEdges);
17238 if CountTempFaceEdges>length(TempFaceEdges) then begin
17239 SetLength(TempFaceEdges,CountTempFaceEdges*2);
17240 end;
17241 TempFaceEdge:=@TempFaceEdges[TempFaceEdgeIndex];
17242 TempFaceEdge^.Face:=FaceIndex;
17243 TempFaceEdge^.Vertices[0]:=Face^.Vertices[VertexIndex];
17244 TempFaceEdge^.Vertices[1]:=Face^.Vertices[OtherVertexIndex];
17245 end;
17246 end;
17247 SetLength(TempFaceEdges,CountTempFaceEdges);
17248
17249 // Find unique edges
17250 try
17251 SetLength(fEdges,CountTempFaceEdges);
17252 SetLength(TempFaceEdgeHashItems,CountTempFaceEdges);
17253 SetLength(TempFaceEdgeHashTable,HashSize);
17254 for TempFaceEdgeHashItemIndex:=0 to HashSize-1 do begin
17255 TempFaceEdgeHashTable[TempFaceEdgeHashItemIndex]:=-1;
17256 end;
17257 CountTempFaceEdgeHashItems:=0;
17258 for TempFaceEdgeIndex:=0 to CountTempFaceEdges-1 do begin
17259 TempFaceEdge:=@TempFaceEdges[TempFaceEdgeIndex];
17260 if TempFaceEdge^.Vertices[0]<TempFaceEdge^.Vertices[1] then begin
17261 TempFaceEdgeHash:=(longword(TempFaceEdge^.Vertices[0])*73856093) xor (longword(TempFaceEdge^.Vertices[1])*83492791);
17262 end else begin
17263 TempFaceEdgeHash:=(longword(TempFaceEdge^.Vertices[1])*73856093) xor (longword(TempFaceEdge^.Vertices[0])*83492791);
17264 end;
17265 TempFaceEdgeHashItemIndex:=TempFaceEdgeHashTable[TempFaceEdgeHash and HashMask];
17266 while TempFaceEdgeHashItemIndex>=0 do begin
17267 TempFaceEdgeHashItem:=@TempFaceEdgeHashItems[TempFaceEdgeHashItemIndex];
17268 if (TempFaceEdgeHashItem^.Hash=TempFaceEdgeHash) and
17269 (((TempFaceEdgeHashItem^.FaceEdgeVertexA=TempFaceEdge^.Vertices[0]) and (TempFaceEdgeHashItem^.FaceEdgeVertexB=TempFaceEdge^.Vertices[1])) or
17270 ((TempFaceEdgeHashItem^.FaceEdgeVertexA=TempFaceEdge^.Vertices[1]) and (TempFaceEdgeHashItem^.FaceEdgeVertexB=TempFaceEdge^.Vertices[0]))) then begin
17271 break;
17272 end else begin
17273 TempFaceEdgeHashItemIndex:=TempFaceEdgeHashItem^.Next;
17274 end;
17275 end;
17276 if TempFaceEdgeHashItemIndex<0 then begin
17277 if length(TempFaceEdgeHashItems)<(CountTempFaceEdgeHashItems+1) then begin
17278 SetLength(TempFaceEdgeHashItems,(CountTempFaceEdgeHashItems+1)*2);
17279 end;
17280 TempFaceEdgeHashItem:=@TempFaceEdgeHashItems[CountTempFaceEdgeHashItems];
17281 TempFaceEdgeHashItem^.Next:=TempFaceEdgeHashTable[TempFaceEdgeHash and HashMask];
17282 TempFaceEdgeHashTable[TempFaceEdgeHash and HashMask]:=CountTempFaceEdgeHashItems;
17283 TempFaceEdgeHashItem^.Hash:=TempFaceEdgeHash;
17284 inc(CountTempFaceEdgeHashItems);
17285 TempFaceEdgeHashItem^.Edge:=-1;
17286 TempFaceEdgeHashItem^.Face:=TempFaceEdge^.Face;
17287 TempFaceEdgeHashItem^.FaceEdge:=TempFaceEdgeIndex;
17288 TempFaceEdgeHashItem^.FaceEdgeVertexA:=TempFaceEdge^.Vertices[0];
17289 TempFaceEdgeHashItem^.FaceEdgeVertexB:=TempFaceEdge^.Vertices[1];
17290 end else begin
17291 TempFaceEdgeHashItem:=@TempFaceEdgeHashItems[TempFaceEdgeHashItemIndex];
17292 if (TempFaceEdgeHashItem^.Edge<0) and (TempFaceEdgeHashItem^.Face<>TempFaceEdge^.Face) then begin
17293 TempFaceEdgeHashItem^.Edge:=fCountEdges;
17294 Edge:=@fEdges[fCountEdges];
17295 inc(fCountEdges);
17296 Edge^.Vertices[0]:=TempFaceEdgeHashItem^.FaceEdgeVertexA;
17297 Edge^.Vertices[1]:=TempFaceEdgeHashItem^.FaceEdgeVertexB;
17298 Edge^.Faces[0]:=TempFaceEdgeHashItem^.Face;
17299 Edge^.Faces[1]:=TempFaceEdge^.Face;
17300 end else begin
17301 raise EKraftDegeneratedConvexHull.Create('Degenerated convex hull');
17302 end;
17303 end;
17304 end;
17305 for TempFaceEdgeHashItemIndex:=0 to CountTempFaceEdgeHashItems-1 do begin
17306 TempFaceEdgeHashItem:=@TempFaceEdgeHashItems[TempFaceEdgeHashItemIndex];
17307 if TempFaceEdgeHashItem^.Edge<0 then begin
17308 raise EKraftDegeneratedConvexHull.Create('Degenerated convex hull');
17309 end;
17310 end;
17311 SetLength(fEdges,fCountEdges);
17312 finally
17313 SetLength(TempFaceEdgeHashItems,0);
17314 SetLength(TempFaceEdgeHashTable,0);
17315 end;
17316
17317 TempTriangles:=nil;
17318 try
17319
17320 // Triangulate convex polygon faces into temporary triangles for the hill-climbing vertex adjacency computation
17321 CountTriangles:=0;
17322 for FaceIndex:=0 to fCountFaces-1 do begin
17323 Face:=@fFaces[FaceIndex];
17324 if Face^.CountVertices>2 then begin
17325 inc(CountTriangles,Face^.CountVertices-2);
17326 end;
17327 end;
17328 SetLength(TempTriangles,CountTriangles);
17329 CountTriangles:=0;
17330 for FaceIndex:=0 to fCountFaces-1 do begin
17331 Face:=@fFaces[FaceIndex];
17332 for FaceVertexIndex:=2 to Face^.CountVertices-1 do begin
17333 if (CountTriangles+1)>length(TempTriangles) then begin
17334 SetLength(TempTriangles,(CountTriangles+1)*2);
17335 end;
17336 Triangle:=@TempTriangles[CountTriangles];
17337 inc(CountTriangles);
17338 Triangle^[0]:=Face^.Vertices[0];
17339 Triangle^[1]:=Face^.Vertices[FaceVertexIndex-1];
17340 Triangle^[2]:=Face^.Vertices[FaceVertexIndex];
17341 end;
17342 end;
17343
17344 // Compute vertex adjacency for hill-climbing
17345 for VertexIndex:=0 to fCountVertices-1 do begin
17346 fVertices[VertexIndex].CountAdjacencies:=0;
17347 end;
17348 for TriangleIndex:=0 to CountTriangles-1 do begin
17349 for TriangleVertexIndex:=0 to 2 do begin
17350 VertexIndex:=TempTriangles[TriangleIndex,TriangleVertexIndex];
17351 Vertex:=@fVertices[VertexIndex];
17352 for OtherTriangleVertexIndex:=1 to 2 do begin
17353 OtherVertexIndex:=TempTriangles[TriangleIndex,ModuloThree[TriangleVertexIndex+OtherTriangleVertexIndex]];
17354 Found:=false;
17355 for SearchIndex:=0 to Vertex^.CountAdjacencies-1 do begin
17356 if Vertex^.Adjacencies[SearchIndex]=OtherVertexIndex then begin
17357 Found:=true;
17358 break;
17359 end;
17360 end;
17361 if not Found then begin
17362 if (Vertex^.CountAdjacencies+1)>length(Vertex^.Adjacencies) then begin
17363 SetLength(Vertex^.Adjacencies,(Vertex^.CountAdjacencies+1)*2);
17364 end;
17365 Vertex^.Adjacencies[Vertex^.CountAdjacencies]:=OtherVertexIndex;
17366 inc(Vertex^.CountAdjacencies);
17367 end;
17368 end;
17369 end;
17370 end;
17371
17372 finally
17373 SetLength(TempTriangles,0);
17374 end;
17375
17376 finally
17377 SetLength(TempPoints,0);
17378 SetLength(TempTriangles,0);
17379 SetLength(TempFaceEdges,0);
17380 //SetLength(TempInputPolygons.Items,0);
17381 SetLength(TempOutputPolygons.Items,0);
17382 end;
17383 end;
17384
17385 procedure TKraftConvexHull.Update;
17386 var FaceIndex,VertexIndex:longint;
17387 Face:PKraftConvexHullFace;
17388 v0,v1,v2:PKraftVector3;
17389 begin
17390
17391 for FaceIndex:=0 to fCountFaces-1 do begin
17392 Face:=@fFaces[FaceIndex];
17393 if Face^.CountVertices>2 then begin
17394 v0:=@fVertices[Face^.Vertices[0]].Position;
17395 v1:=@fVertices[Face^.Vertices[1]].Position;
17396 v2:=@fVertices[Face^.Vertices[2]].Position;
17397 Face^.Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(v1^,v0^),Vector3Sub(v2^,v0^)));
17398 Face^.Plane.Distance:=-Vector3Dot(Face^.Plane.Normal,v0^);
17399 end;
17400 end;
17401
17402 fSphere.Center.x:=0.0;
17403 fSphere.Center.y:=0.0;
17404 fSphere.Center.z:=0.0;
17405 fSphere.Radius:=0.0;
17406 if fCountVertices>0 then begin
17407 v0:=@fVertices[0].Position;
17408 fAABB.Min:=v0^;
17409 fAABB.Max:=v0^;
17410 fSphere.Center:=v0^;
17411 for VertexIndex:=1 to fCountVertices-1 do begin
17412 v0:=@fVertices[VertexIndex].Position;
17413 if fAABB.Min.x>v0^.x then begin
17414 fAABB.Min.x:=v0^.x;
17415 end;
17416 if fAABB.Min.y>v0^.y then begin
17417 fAABB.Min.y:=v0^.y;
17418 end;
17419 if fAABB.Min.z>v0^.z then begin
17420 fAABB.Min.z:=v0^.z;
17421 end;
17422 if fAABB.Max.x<v0^.x then begin
17423 fAABB.Max.x:=v0^.x;
17424 end;
17425 if fAABB.Max.y<v0^.y then begin
17426 fAABB.Max.y:=v0^.y;
17427 end;
17428 if fAABB.Max.z<v0^.z then begin
17429 fAABB.Max.z:=v0^.z;
17430 end;
17431 fSphere.Center.x:=fSphere.Center.x+v0^.x;
17432 fSphere.Center.y:=fSphere.Center.y+v0^.y;
17433 fSphere.Center.z:=fSphere.Center.z+v0^.z;
17434 end;
17435 fSphere.Center.x:=fSphere.Center.x/fCountVertices;
17436 fSphere.Center.y:=fSphere.Center.y/fCountVertices;
17437 fSphere.Center.z:=fSphere.Center.z/fCountVertices;
17438 for VertexIndex:=0 to fCountVertices-1 do begin
17439 fSphere.Radius:=Max(fSphere.Radius,Vector3Length(Vector3Sub(fSphere.Center,fVertices[VertexIndex].Position)));
17440 end;
17441 end else begin
17442 fAABB.Min.x:=MAX_SCALAR;
17443 fAABB.Min.y:=MAX_SCALAR;
17444 fAABB.Min.z:=MAX_SCALAR;
17445 fAABB.Max.x:=-MAX_SCALAR;
17446 fAABB.Max.y:=-MAX_SCALAR;
17447 fAABB.Max.z:=-MAX_SCALAR;
17448 end;
17449
17450 fAngularMotionDisc:=Vector3Length(fSphere.Center)+fSphere.Radius;
17451
17452 end;
17453
17454 procedure TKraftConvexHull.CalculateMassData;
17455 const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
17456 Density=1.0;
17457 var FaceIndex,FaceVertexIndex,CoordinateIndex,SecondCoordinateIndex,ThirdCoordinateIndex:longint;
17458 Face:PKraftConvexHullFace;
17459 vU,vV,vW:PKraftVector3;
17460 CurrentVolume,CentroidX,CentroidY,CentroidZ,Volume,Denominator:double;
17461 Diag,OffDiag,u,v,w:array[0..2] of double;
17462 begin
17463
17464 CentroidX:=0.0;
17465 CentroidY:=0.0;
17466 CentroidZ:=0.0;
17467
17468 Volume:=0.0;
17469
17470 Diag[0]:=0.0;
17471 Diag[1]:=0.0;
17472 Diag[2]:=0.0;
17473
17474 OffDiag[0]:=0.0;
17475 OffDiag[1]:=0.0;
17476 OffDiag[2]:=0.0;
17477
17478 for FaceIndex:=0 to fCountFaces-1 do begin
17479
17480 Face:=@fFaces[FaceIndex];
17481
17482 vU:=@fVertices[Face^.Vertices[0]].Position;
17483 u[0]:=vU^.x;
17484 u[1]:=vU^.y;
17485 u[2]:=vU^.z;
17486
17487 for FaceVertexIndex:=1 to Face^.CountVertices-2 do begin
17488
17489 vV:=@fVertices[Face^.Vertices[FaceVertexIndex]].Position;
17490 v[0]:=vV^.x;
17491 v[1]:=vV^.y;
17492 v[2]:=vV^.z;
17493
17494 vW:=@fVertices[Face^.Vertices[FaceVertexIndex+1]].Position;
17495 w[0]:=vW^.x;
17496 w[1]:=vW^.y;
17497 w[2]:=vW^.z;
17498
17499 CurrentVolume:=Vector3Dot(vU^,Vector3Cross(vV^,vW^));
17500
17501 Volume:=Volume+CurrentVolume;
17502
17503 CentroidX:=CentroidX+((vU^.x+vV^.x+vW^.x)*CurrentVolume);
17504 CentroidY:=CentroidY+((vU^.y+vV^.y+vW^.y)*CurrentVolume);
17505 CentroidZ:=CentroidZ+((vU^.z+vV^.z+vW^.z)*CurrentVolume);
17506
17507 for CoordinateIndex:=0 to 2 do begin
17508
17509 SecondCoordinateIndex:=ModuloThree[CoordinateIndex+1];
17510 ThirdCoordinateIndex:=ModuloThree[CoordinateIndex+2];
17511
17512 Diag[CoordinateIndex]:=Diag[CoordinateIndex]+(((u[CoordinateIndex]*v[CoordinateIndex])+
17513 (v[CoordinateIndex]*w[CoordinateIndex])+
17514 (w[CoordinateIndex]*u[CoordinateIndex])+
17515 (u[CoordinateIndex]*u[CoordinateIndex])+
17516 (v[CoordinateIndex]*v[CoordinateIndex])+
17517 (w[CoordinateIndex]*w[CoordinateIndex]))*CurrentVolume);
17518
17519 OffDiag[CoordinateIndex]:=OffDiag[CoordinateIndex]+(((u[SecondCoordinateIndex]*v[ThirdCoordinateIndex])+
17520 (v[SecondCoordinateIndex]*w[ThirdCoordinateIndex])+
17521 (w[SecondCoordinateIndex]*u[ThirdCoordinateIndex])+
17522 (u[SecondCoordinateIndex]*w[ThirdCoordinateIndex])+
17523 (v[SecondCoordinateIndex]*u[ThirdCoordinateIndex])+
17524 (w[SecondCoordinateIndex]*v[ThirdCoordinateIndex])+
17525 (u[SecondCoordinateIndex]*u[ThirdCoordinateIndex]*2.0)+
17526 (v[SecondCoordinateIndex]*v[ThirdCoordinateIndex]*2.0)+
17527 (w[SecondCoordinateIndex]*w[ThirdCoordinateIndex]*2.0))*CurrentVolume);
17528
17529 end;
17530
17531 end;
17532
17533 end;
17534
17535 Denominator:=Volume*4.0;
17536 fCentroid.x:=CentroidX/Denominator;
17537 fCentroid.y:=CentroidY/Denominator;
17538 fCentroid.z:=CentroidZ/Denominator;
17539
17540 Volume:=Volume/6.0;
17541
17542 Denominator:=Volume*60.0;
17543 Diag[0]:=Diag[0]/Denominator;
17544 Diag[1]:=Diag[1]/Denominator;
17545 Diag[2]:=Diag[2]/Denominator;
17546
17547 Denominator:=Volume*120.0;
17548 OffDiag[0]:=OffDiag[0]/Denominator;
17549 OffDiag[1]:=OffDiag[1]/Denominator;
17550 OffDiag[2]:=OffDiag[2]/Denominator;
17551
17552 fMassData.Volume:=Volume;
17553 fMassData.Mass:=Volume*Density;
17554
17555 if fMassData.Mass>EPSILON then begin
17556 fMassData.Inertia[0,0]:=(Diag[1]+Diag[2])*fMassData.Mass;
17557 fMassData.Inertia[0,1]:=(-OffDiag[2])*fMassData.Mass;
17558 fMassData.Inertia[0,2]:=(-OffDiag[1])*fMassData.Mass;
17559 fMassData.Inertia[1,0]:=(-OffDiag[2])*fMassData.Mass;
17560 fMassData.Inertia[1,1]:=(Diag[0]+Diag[2])*fMassData.Mass;
17561 fMassData.Inertia[1,2]:=(-OffDiag[0])*fMassData.Mass;
17562 fMassData.Inertia[2,0]:=(-OffDiag[1])*fMassData.Mass;
17563 fMassData.Inertia[2,1]:=(-OffDiag[0])*fMassData.Mass;
17564 fMassData.Inertia[2,2]:=(Diag[0]+Diag[1])*fMassData.Mass;
17565 end else begin
17566 fMassData.Inertia[0,0]:=0.0;
17567 fMassData.Inertia[0,1]:=0.0;
17568 fMassData.Inertia[0,2]:=0.0;
17569 fMassData.Inertia[1,0]:=0.0;
17570 fMassData.Inertia[1,1]:=0.0;
17571 fMassData.Inertia[1,2]:=0.0;
17572 fMassData.Inertia[2,0]:=0.0;
17573 fMassData.Inertia[2,1]:=0.0;
17574 fMassData.Inertia[2,2]:=0.0;
17575 end;
17576
17577 end;
17578
17579 procedure TKraftConvexHull.Finish;
17580 const Steps=1024;
17581 //ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
17582 var VertexIndex:longint;
17583 v:PKraftVector3;
17584 begin
17585
17586 SetLength(fVertices,fCountVertices);
17587
17588 CalculateMassData;
17589
17590 // Construct AABB and bounding sphere
17591 fSphere.Center.x:=0.0;
17592 fSphere.Center.y:=0.0;
17593 fSphere.Center.z:=0.0;
17594 fSphere.Radius:=0.0;
17595 if fCountVertices>0 then begin
17596 v:=@fVertices[0].Position;
17597 fAABB.Min:=v^;
17598 fAABB.Max:=v^;
17599 fSphere.Center:=v^;
17600 for VertexIndex:=1 to fCountVertices-1 do begin
17601 v:=@fVertices[VertexIndex].Position;
17602 if fAABB.Min.x>v^.x then begin
17603 fAABB.Min.x:=v^.x;
17604 end;
17605 if fAABB.Min.y>v^.y then begin
17606 fAABB.Min.y:=v^.y;
17607 end;
17608 if fAABB.Min.z>v^.z then begin
17609 fAABB.Min.z:=v^.z;
17610 end;
17611 if fAABB.Max.x<v^.x then begin
17612 fAABB.Max.x:=v^.x;
17613 end;
17614 if fAABB.Max.y<v^.y then begin
17615 fAABB.Max.y:=v^.y;
17616 end;
17617 if fAABB.Max.z<v^.z then begin
17618 fAABB.Max.z:=v^.z;
17619 end;
17620 fSphere.Center.x:=fSphere.Center.x+v^.x;
17621 fSphere.Center.y:=fSphere.Center.y+v^.y;
17622 fSphere.Center.z:=fSphere.Center.z+v^.z;
17623 end;
17624 fSphere.Center.x:=fSphere.Center.x/fCountVertices;
17625 fSphere.Center.y:=fSphere.Center.y/fCountVertices;
17626 fSphere.Center.z:=fSphere.Center.z/fCountVertices;
17627 for VertexIndex:=0 to fCountVertices-1 do begin
17628 fSphere.Radius:=Max(fSphere.Radius,Vector3Length(Vector3Sub(fSphere.Center,fVertices[VertexIndex].Position)));
17629 end;
17630 end else begin
17631 fAABB.Min.x:=MAX_SCALAR;
17632 fAABB.Min.y:=MAX_SCALAR;
17633 fAABB.Min.z:=MAX_SCALAR;
17634 fAABB.Max.x:=-MAX_SCALAR;
17635 fAABB.Max.y:=-MAX_SCALAR;
17636 fAABB.Max.z:=-MAX_SCALAR;
17637 end;
17638
17639 fAngularMotionDisc:=Vector3Length(fSphere.Center)+fSphere.Radius;
17640
17641 end;
17642
17643 function TKraftConvexHull.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
17644 var Index:longint;
17645 Distance:TKraftScalar;
17646 begin
17647 if fCountFaces>0 then begin
17648 result:=PlaneVectorDistance(fFaces[0].Plane,Position);
17649 for Index:=1 to fCountFaces-1 do begin
17650 Distance:=PlaneVectorDistance(fFaces[Index].Plane,Position);
17651 if result<Distance then begin
17652 result:=Distance;
17653 end;
17654 end;
17655 if result>=0.0 then begin
17656 // Point lies on or outside convex hull
17657 for Index:=0 to fCountFaces-1 do begin
17658 Distance:=PlaneVectorDistance(fFaces[Index].Plane,Position);
17659 if result>Distance then begin
17660 result:=Distance;
17661 end;
17662 end;
17663 end else begin
17664 // Point lies inside convex hull
17665 end;
17666 end else begin
17667 result:=MAX_SCALAR;
17668 end;
17669 end;
17670
17671 function TKraftConvexHull.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
17672 begin
17673 if (Index>=0) and (Index<fCountVertices) then begin
17674 result:=fVertices[Index].Position;
17675 end else begin
17676 result:=fMassData.Center; //Vector3Origin;
17677 end;
17678 end;
17679
17680 function TKraftConvexHull.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
17681 var Normal:TKraftVector3;
17682 Index,BestVertexIndex,NewVertexIndex,CurrentVertexIndex:longint;
17683 BestDistance,NewDistance,CurrentDistance:TKraftScalar;
17684 Vertex,CurrentVertex:PKraftConvexHullVertex;
17685 begin
17686 result:=-1;
17687 if fCountVertices>0 then begin
17688 Normal:=Vector3SafeNorm(Direction);
17689 BestVertexIndex:=0;
17690 BestDistance:=Vector3Dot(fVertices[BestVertexIndex].Position,Normal);
17691 if fCountVertices<32 then begin
17692 for Index:=1 to fCountVertices-1 do begin
17693 CurrentDistance:=Vector3Dot(fVertices[Index].Position,Normal);
17694 if BestDistance<CurrentDistance then begin
17695 BestDistance:=CurrentDistance;
17696 BestVertexIndex:=Index;
17697 end;
17698 end;
17699 end else begin
17700 repeat
17701 NewVertexIndex:=BestVertexIndex;
17702 NewDistance:=BestDistance;
17703 Vertex:=@fVertices[BestVertexIndex];
17704 for Index:=0 to Vertex^.CountAdjacencies-1 do begin
17705 CurrentVertexIndex:=Vertex^.Adjacencies[Index];
17706 CurrentVertex:=@fVertices[CurrentVertexIndex];
17707 CurrentDistance:=Vector3Dot(CurrentVertex^.Position,Normal);
17708 if NewDistance<CurrentDistance then begin
17709 NewVertexIndex:=CurrentVertexIndex;
17710 NewDistance:=CurrentDistance;
17711 end;
17712 end;
17713 if NewVertexIndex=BestVertexIndex then begin
17714 break;
17715 end;
17716 BestVertexIndex:=NewVertexIndex;
17717 BestDistance:=NewDistance;
17718 until false;
17719 end;
17720 result:=BestVertexIndex;
17721 end;
17722 end;
17723
17724 function TKraftConvexHull.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
17725 var Normal:TKraftVector3;
17726 Index,BestVertexIndex,NewVertexIndex,CurrentVertexIndex:longint;
17727 BestDistance,NewDistance,CurrentDistance:TKraftScalar;
17728 Vertex,CurrentVertex:PKraftConvexHullVertex;
17729 begin
17730 result:=fMassData.Center;
17731 if fCountVertices>0 then begin
17732 Normal:=Vector3SafeNorm(Direction);
17733 BestVertexIndex:=0;
17734 BestDistance:=Vector3Dot(fVertices[BestVertexIndex].Position,Normal);
17735 if fCountVertices<32 then begin
17736 for Index:=1 to fCountVertices-1 do begin
17737 CurrentDistance:=Vector3Dot(fVertices[Index].Position,Normal);
17738 if BestDistance<CurrentDistance then begin
17739 BestDistance:=CurrentDistance;
17740 BestVertexIndex:=Index;
17741 end;
17742 end;
17743 end else begin
17744 repeat
17745 NewVertexIndex:=BestVertexIndex;
17746 NewDistance:=BestDistance;
17747 Vertex:=@fVertices[BestVertexIndex];
17748 for Index:=0 to Vertex^.CountAdjacencies-1 do begin
17749 CurrentVertexIndex:=Vertex^.Adjacencies[Index];
17750 CurrentVertex:=@fVertices[CurrentVertexIndex];
17751 CurrentDistance:=Vector3Dot(CurrentVertex^.Position,Normal);
17752 if NewDistance<CurrentDistance then begin
17753 NewVertexIndex:=CurrentVertexIndex;
17754 NewDistance:=CurrentDistance;
17755 end;
17756 end;
17757 if NewVertexIndex=BestVertexIndex then begin
17758 break;
17759 end;
17760 BestVertexIndex:=NewVertexIndex;
17761 BestDistance:=NewDistance;
17762 until false;
17763 end;
17764 result:=fVertices[BestVertexIndex].Position;
17765 end;
17766 end;
17767
17768 constructor TKraftMesh.Create(const APhysics:TKraft);
17769 begin
17770
17771 inherited Create;
17772
17773 fPhysics:=APhysics;
17774
17775 fVertices:=nil;
17776 fCountVertices:=0;
17777
17778 fNormals:=nil;
17779 fCountNormals:=0;
17780
17781 fTriangles:=nil;
17782 fCountTriangles:=0;
17783
17784 fNodes:=nil;
17785 fCountNodes:=0;
17786
17787 fSkipListNodes:=nil;
17788 fCountSkipListNodes:=0;
17789
17790 fDoubleSided:=true;
17791
17792 if assigned(fPhysics.fMeshLast) then begin
17793 fPhysics.fMeshLast.fNext:=self;
17794 fPrevious:=fPhysics.fMeshLast;
17795 end else begin
17796 fPhysics.fMeshFirst:=self;
17797 fPrevious:=nil;
17798 end;
17799 fPhysics.fMeshLast:=self;
17800 fNext:=nil;
17801
17802 end;
17803
17804 destructor TKraftMesh.Destroy;
17805 begin
17806
17807 SetLength(fVertices,0);
17808
17809 SetLength(fNormals,0);
17810
17811 SetLength(fTriangles,0);
17812
17813 SetLength(fNodes,0);
17814
17815 SetLength(fSkipListNodes,0);
17816
17817 if assigned(fPrevious) then begin
17818 fPrevious.fNext:=fNext;
17819 end else if fPhysics.fMeshFirst=self then begin
17820 fPhysics.fMeshFirst:=fNext;
17821 end;
17822 if assigned(fNext) then begin
17823 fNext.fPrevious:=fPrevious;
17824 end else if fPhysics.fMeshLast=self then begin
17825 fPhysics.fMeshLast:=fPrevious;
17826 end;
17827 fPrevious:=nil;
17828 fNext:=nil;
17829
17830 inherited Destroy;
17831
17832 end;
17833
17834 function TKraftMesh.AddVertex(const AVertex:TKraftVector3):longint;
17835 begin
17836 result:=fCountVertices;
17837 inc(fCountVertices);
17838 if fCountVertices>length(fVertices) then begin
17839 SetLength(fVertices,fCountVertices*2);
17840 end;
17841 fVertices[result]:=AVertex;
17842 end;
17843
17844 function TKraftMesh.AddNormal(const ANormal:TKraftVector3):longint;
17845 begin
17846 result:=fCountNormals;
17847 inc(fCountNormals);
17848 if fCountNormals>length(fNormals) then begin
17849 SetLength(fNormals,fCountNormals*2);
17850 end;
17851 fNormals[result]:=ANormal;
17852 end;
17853
17854 function TKraftMesh.AddTriangle(const AVertexIndex0,AVertexIndex1,AVertexIndex2:longint;const ANormalIndex0:longint=-1;const ANormalIndex1:longint=-1;ANormalIndex2:longint=-1):longint;
17855 var Triangle:PKraftMeshTriangle;
17856 begin
17857 result:=fCountTriangles;
17858 inc(fCountTriangles);
17859 if fCountTriangles>length(fTriangles) then begin
17860 SetLength(fTriangles,fCountTriangles*2);
17861 end;
17862 Triangle:=@fTriangles[result];
17863 Triangle^.Vertices[0]:=AVertexIndex0;
17864 Triangle^.Vertices[1]:=AVertexIndex1;
17865 Triangle^.Vertices[2]:=AVertexIndex2;
17866 Triangle^.Normals[0]:=ANormalIndex0;
17867 Triangle^.Normals[1]:=ANormalIndex1;
17868 Triangle^.Normals[2]:=ANormalIndex2;
17869 Triangle^.Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(fVertices[Triangle^.Vertices[1]],fVertices[Triangle^.Vertices[0]]),Vector3Sub(fVertices[Triangle^.Vertices[2]],fVertices[Triangle^.Vertices[0]])));
17870 Triangle^.Plane.Distance:=-Vector3Dot(Triangle^.Plane.Normal,fVertices[Triangle^.Vertices[0]]);
17871 Triangle^.Next:=-1;
17872 end;
17873
17874 procedure TKraftMesh.Load(const AVertices:PKraftVector3;const ACountVertices:longint;const ANormals:PKraftVector3;const ACountNormals:longint;const AVertexIndices,ANormalIndices:pointer;const ACountIndices:longint);
17875 var i:longint;
17876 Triangle:PKraftMeshTriangle;
17877 v,n:plongint;
17878 HasNormals:boolean;
17879 begin
17880
17881 HasNormals:=assigned(ANormals) and (ACountNormals>0) and assigned(ANormalIndices);
17882
17883 fVertices:=nil;
17884 fCountVertices:=ACountVertices;
17885 SetLength(fVertices,fCountVertices);
17886 for i:=0 to fCountVertices-1 do begin
17887 fVertices[i]:=PKraftVector3s(AVertices)^[i];
17888 end;
17889
17890 fNormals:=nil;
17891 if HasNormals then begin
17892 fCountNormals:=ACountNormals;
17893 SetLength(fNormals,fCountNormals);
17894 for i:=0 to fCountNormals-1 do begin
17895 fNormals[i]:=PKraftVector3s(ANormals)^[i];
17896 end;
17897 end else begin
17898 fCountNormals:=0;
17899 end;
17900
17901 fTriangles:=nil;
17902 fCountTriangles:=ACountIndices div 3;
17903 SetLength(fTriangles,fCountTriangles);
17904 v:=AVertexIndices;
17905 n:=ANormalIndices;
17906 for i:=0 to fCountTriangles-1 do begin
17907 Triangle:=@fTriangles[i];
17908 Triangle^.Vertices[0]:=v^;
17909 inc(v);
17910 Triangle^.Vertices[1]:=v^;
17911 inc(v);
17912 Triangle^.Vertices[2]:=v^;
17913 inc(v);
17914 if HasNormals then begin
17915 Triangle^.Normals[0]:=n^;
17916 inc(n);
17917 Triangle^.Normals[1]:=n^;
17918 inc(n);
17919 Triangle^.Normals[2]:=n^;
17920 inc(n);
17921 end else begin
17922 Triangle^.Normals[0]:=-1;
17923 Triangle^.Normals[1]:=-1;
17924 Triangle^.Normals[2]:=-1;
17925 end;
17926 Triangle^.Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(fVertices[Triangle^.Vertices[1]],fVertices[Triangle^.Vertices[0]]),Vector3Sub(fVertices[Triangle^.Vertices[2]],fVertices[Triangle^.Vertices[0]])));
17927 Triangle^.Plane.Distance:=-Vector3Dot(Triangle^.Plane.Normal,fVertices[Triangle^.Vertices[0]]);
17928 Triangle^.Next:=-1;
17929 end;
17930
17931 end;
17932
17933 procedure TKraftMesh.Load(const ASourceData:pointer;const ASourceSize:longint);
17934 type TFileSignature=array[0..3] of ansichar;
17935 var SrcPos:longint;
17936 Signature:TFileSignature;
17937 function Read(var Dst;DstLen:longword):longword;
17938 begin
17939 result:=ASourceSize-SrcPos;
17940 if result>DstLen then begin
17941 result:=DstLen;
17942 end;
17943 if result>0 then begin
17944 Move(PAnsiChar(ASourceData)[SrcPos],Dst,result);
17945 inc(SrcPos,result);
17946 end;
17947 end;
17948 function ReadByte:byte;
17949 begin
17950 Read(result,SizeOf(byte));
17951 end;
17952 function ReadWord:word;
17953 begin
17954 Read(result,SizeOf(word));
17955 end;
17956 function ReadLongWord:longword;
17957 begin
17958 Read(result,SizeOf(longword));
17959 end;
17960 function ReadFloat:single;
17961 begin
17962 Read(result,SizeOf(single));
17963 end;
17964 procedure LoadPMF;
17965 type TFace=record
17966 Indices:array[0..2] of longword;
17967 end;
17968 PFaces=^TFaces;
17969 TFaces=array[0..0] of TFace;
17970 var Counter:longint;
17971 Triangle:PKraftMeshTriangle;
17972 begin
17973 fCountTriangles:=ReadLongWord;
17974 SetLength(fTriangles,fCountTriangles);
17975 fCountVertices:=ReadLongWord;
17976 if (fCountTriangles>0) and (fCountVertices>0) then begin
17977 for Counter:=0 to fCountTriangles-1 do begin
17978 Triangle:=@fTriangles[Counter];
17979 Triangle^.Vertices[0]:=ReadLongWord;
17980 Triangle^.Vertices[1]:=ReadLongWord;
17981 Triangle^.Vertices[2]:=ReadLongWord;
17982 Triangle^.Normals[0]:=-1;
17983 Triangle^.Normals[1]:=-1;
17984 Triangle^.Normals[2]:=-1;
17985 end;
17986 SetLength(fVertices,fCountVertices);
17987 for Counter:=0 to fCountVertices-1 do begin
17988 fVertices[Counter].x:=ReadFloat;
17989 fVertices[Counter].y:=ReadFloat;
17990 fVertices[Counter].z:=ReadFloat;
17991 end;
17992 for Counter:=0 to fCountTriangles-1 do begin
17993 Triangle:=@fTriangles[Counter];
17994 Triangle^.Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(fVertices[Triangle^.Vertices[1]],fVertices[Triangle^.Vertices[0]]),Vector3Sub(fVertices[Triangle^.Vertices[2]],fVertices[Triangle^.Vertices[0]])));
17995 Triangle^.Plane.Distance:=-Vector3Dot(Triangle^.Plane.Normal,fVertices[Triangle^.Vertices[0]]);
17996 Triangle^.Next:=-1;
17997 end;
17998 end;
17999 end;
18000 function Load3DS(SrcData:pointer;SrcSize:longword):boolean;
18001 const CHUNK_3DS_MAIN=$4d4d;
18002 CHUNK_3DS_OBJMESH=$3d3d;
18003 CHUNK_3DS_OBJBLOCK=$4000;
18004 CHUNK_3DS_TRIMESH=$4100;
18005 CHUNK_3DS_VERTLIST=$4110;
18006 CHUNK_3DS_FACELIST=$4120;
18007 CHUNK_3DS_MAPLIST=$4140;
18008 CHUNK_3DS_SMOOTHLIST=$4150;
18009 CHUNK_3DS_MESHMATRIX=$4160;
18010 type PVector2=^TVector2;
18011 TVector2=TKraftVector2;
18012 PVector2Array=^TVector2Array;
18013 TVector2Array=array[0..0] of TVector2;
18014 PVector3Array=^TKraftVector3Array;
18015 TKraftVector3Array=array[0..0] of TKraftVector3;
18016 PFace3DS=^TFace3DS;
18017 TFace3DS=record
18018 Indices:array[0..2] of longword;
18019 Flags:longword;
18020 SmoothGroup:longword;
18021 end;
18022 PFaces3DS=^TFaces3DS;
18023 TFaces3DS=array[0..0] of TFace3DS;
18024 PObject3DSMesh=^TObject3DSMesh;
18025 TObject3DSMesh=record
18026 Vertices:PVector3Array;
18027 NumVertices:longint;
18028 TexCoords:PVector2Array;
18029 NumTexCoords:longint;
18030 Faces:PFaces3DS;
18031 NumFaces:longint;
18032 Matrix:TKraftMatrix4x4;
18033 end;
18034 PObject3DSMeshs=^TObject3DSMeshs;
18035 TObject3DSMeshs=array[0..0] of TObject3DSMesh;
18036 PObject3DS=^TObject3DS;
18037 TObject3DS=record
18038 Name:PAnsiChar;
18039 Meshs:PObject3DSMeshs;
18040 NumMeshs:longint;
18041 end;
18042 PObjects3DS=^TObjects3DS;
18043 TObjects3DS=array[0..0] of TObject3DS;
18044 var SrcPos:longword;
18045 Signature3DS:word;
18046 Size3DS:longword;
18047 Objects3DS:PObjects3DS;
18048 NumObjects3DS:longint;
18049 function Read(var Dst;DstLen:longword):longword;
18050 begin
18051 result:=SrcSize-SrcPos;
18052 if result>DstLen then begin
18053 result:=DstLen;
18054 end;
18055 if result>0 then begin
18056 Move(PAnsiChar(SrcData)[SrcPos],Dst,result);
18057 inc(SrcPos,result);
18058 end;
18059 end;
18060 function ReadByte:byte;
18061 begin
18062 Read(result,SizeOf(byte));
18063 end;
18064 function ReadWord:word;
18065 begin
18066 Read(result,SizeOf(word));
18067 end;
18068 function ReadLongWord:longword;
18069 begin
18070 Read(result,SizeOf(longword));
18071 end;
18072 function ReadFloat:single;
18073 begin
18074 Read(result,SizeOf(single));
18075 end;
18076 procedure ReallocateMemory(var p;Size:longint);
18077 begin
18078 if assigned(pointer(p)) then begin
18079 if Size=0 then begin
18080 FreeMem(pointer(p));
18081 pointer(p):=nil;
18082 end else begin
18083 ReallocMem(pointer(p),Size);
18084 end;
18085 end else if Size<>0 then begin
18086 GetMem(pointer(p),Size);
18087 end;
18088 end;
18089 function Read3DSChunks(const ParentChunk,Bytes:longword):longword; forward;
18090 function Skip3DSString:longword;
18091 var c:ansichar;
18092 begin
18093 result:=0;
18094 c:=#255;
18095 while c<>#0 do begin
18096 if Read(c,SizeOf(ansichar))<>SizeOf(ansichar) then begin
18097 break;
18098 end;
18099 inc(result);
18100 end;
18101 end;
18102 function Read3DSString(var p:PAnsiChar):longword;
18103 var c:ansichar;
18104 OldPos:longword;
18105 begin
18106 OldPos:=SrcPos;
18107 result:=0;
18108 c:=#255;
18109 while c<>#0 do begin
18110 if Read(c,SizeOf(ansichar))<>SizeOf(ansichar) then begin
18111 break;
18112 end;
18113 inc(result);
18114 end;
18115 GetMem(p,result);
18116 SrcPos:=OldPos;
18117 result:=0;
18118 c:=#255;
18119 while c<>#0 do begin
18120 if Read(c,SizeOf(ansichar))<>SizeOf(ansichar) then begin
18121 break;
18122 end;
18123 p[result]:=c;
18124 inc(result);
18125 end;
18126 end;
18127 function Read3DSChunk(const ParentChunk:longword):longword;
18128 var Chunk:word;
18129 Size,i,j:longword;
18130 Vertex:PKraftVector3;
18131 TexCoord:PVector2;
18132 Face:PFace3DS;
18133 begin
18134 if Read(Chunk,SizeOf(word))<>SizeOf(word) then begin
18135 result:=$80000000;
18136 exit;
18137 end;
18138 if Read(result,SizeOf(longword))<>SizeOf(longword) then begin
18139 result:=$80000000;
18140 exit;
18141 end;
18142 Size:=result-6;
18143 case ParentChunk of
18144 CHUNK_3DS_MAIN:begin
18145 case Chunk of
18146 CHUNK_3DS_OBJMESH:begin
18147 Read3DSChunks(Chunk,Size);
18148 end;
18149 else begin
18150 inc(SrcPos,Size);
18151 end;
18152 end;
18153 end;
18154 CHUNK_3DS_OBJMESH:begin
18155 case Chunk of
18156 CHUNK_3DS_OBJBLOCK:begin
18157 inc(NumObjects3DS);
18158 ReallocateMemory(Objects3DS,NumObjects3DS*SizeOf(TObject3DS));
18159 FillChar(Objects3DS^[NumObjects3DS-1],SizeOf(TObject3DS),#0);
18160 dec(Size,Read3DSString(Objects3DS^[NumObjects3DS-1].Name));
18161 Read3DSChunks(Chunk,Size);
18162 end;
18163 else begin
18164 inc(SrcPos,Size);
18165 end;
18166 end;
18167 end;
18168 CHUNK_3DS_OBJBLOCK:begin
18169 case Chunk of
18170 CHUNK_3DS_TRIMESH:begin
18171 inc(Objects3DS^[NumObjects3DS-1].NumMeshs);
18172 ReallocateMemory(Objects3DS^[NumObjects3DS-1].Meshs,Objects3DS^[NumObjects3DS-1].NumMeshs*SizeOf(TObject3DSMesh));
18173 FillChar(Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1],SizeOf(TObject3DSMesh),#0);
18174 Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Matrix:=Matrix4x4Identity;
18175 Read3DSChunks(Chunk,Size);
18176 end;
18177 else begin
18178 inc(SrcPos,Size);
18179 end;
18180 end;
18181 end;
18182 CHUNK_3DS_TRIMESH:begin
18183 case Chunk of
18184 CHUNK_3DS_VERTLIST:begin
18185 Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumVertices:=ReadWord;
18186 ReallocateMemory(Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Vertices,Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumVertices*SizeOf(TKraftVector3));
18187 Vertex:=@Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Vertices^[0];
18188 for i:=1 to Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumVertices do begin
18189 Vertex^.x:=ReadFloat;
18190 Vertex^.y:=ReadFloat;
18191 Vertex^.z:=ReadFloat;
18192 inc(Vertex);
18193 end;
18194 end;
18195 CHUNK_3DS_MAPLIST:begin
18196 Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumTexCoords:=ReadWord;
18197 ReallocateMemory(Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].TexCoords,Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumTexCoords*SizeOf(TVector2));
18198 TexCoord:=@Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].TexCoords^[0];
18199 for i:=1 to Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumTexCoords do begin
18200 TexCoord^.x:=ReadFloat;
18201 TexCoord^.y:=ReadFloat;
18202 inc(TexCoord);
18203 end;
18204 end;
18205 CHUNK_3DS_FACELIST:begin
18206 Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumFaces:=ReadWord;
18207 ReallocateMemory(Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Faces,Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumFaces*SizeOf(TFace3DS));
18208 Face:=@Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Faces^[0];
18209 for i:=1 to Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumFaces do begin
18210 Face^.Indices[0]:=ReadWord;
18211 Face^.Indices[1]:=ReadWord;
18212 Face^.Indices[2]:=ReadWord;
18213 Face^.Flags:=ReadWord;
18214 inc(Face);
18215 end;
18216 dec(Size,(Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumFaces*4)+2);
18217 Read3DSChunks(Chunk,Size);
18218 end;
18219 CHUNK_3DS_MESHMATRIX:begin
18220 Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Matrix:=Matrix4x4Identity;
18221 for i:=0 to 3 do begin
18222 for j:=0 to 2 do begin
18223 Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Matrix[i,j]:=ReadFloat;
18224 end;
18225 end;
18226 end;
18227 else begin
18228 inc(SrcPos,Size);
18229 end;
18230 end;
18231 end;
18232 CHUNK_3DS_FACELIST:begin
18233 case Chunk of
18234 CHUNK_3DS_SMOOTHLIST:begin
18235 Face:=@Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].Faces^[0];
18236 for i:=1 to Objects3DS^[NumObjects3DS-1].Meshs^[Objects3DS^[NumObjects3DS-1].NumMeshs-1].NumFaces do begin
18237 Face^.SmoothGroup:=ReadLongWord;
18238 inc(Face);
18239 end;
18240 end;
18241 else begin
18242 inc(SrcPos,Size);
18243 end;
18244 end;
18245 end;
18246 else begin
18247 inc(SrcPos,Size);
18248 end;
18249 end;
18250 end;
18251 function Read3DSChunks(const ParentChunk,Bytes:longword):longword;
18252 begin
18253 result:=0;
18254 while result<Bytes do begin
18255 inc(result,Read3DSChunk(ParentChunk));
18256 end;
18257 end;
18258 procedure Convert3DS;
18259 var i,j,k,h:longint;
18260 v:array[0..2] of TKraftVector3;
18261 tv:TKraftVector3;
18262 begin
18263 for i:=0 to NumObjects3DS-1 do begin
18264 for j:=0 to Objects3DS^[i].NumMeshs-1 do begin
18265 for k:=0 to Objects3DS^[i].Meshs^[j].NumFaces-1 do begin
18266 for h:=0 to 2 do begin
18267 tv:=Objects3DS^[i].Meshs^[j].Vertices^[Objects3DS^[i].Meshs^[j].Faces^[k].Indices[h]];
18268 //Vector3MatrixMul(tv,Objects3DS^[i].Meshs^[j].Matrix);
18269 v[h].x:=tv.x;
18270 v[h].y:=tv.z;
18271 v[h].z:=-tv.y;
18272 end;
18273 AddTriangle(AddVertex(v[0]),AddVertex(v[1]),AddVertex(v[2]));
18274 end;
18275 end;
18276 end;
18277 end;
18278 procedure Free3DS;
18279 var i,j:longint;
18280 begin
18281 for i:=0 to NumObjects3DS-1 do begin
18282 for j:=0 to Objects3DS^[i].NumMeshs-1 do begin
18283 ReallocateMemory(Objects3DS^[i].Meshs^[j].Vertices,0);
18284 ReallocateMemory(Objects3DS^[i].Meshs^[j].TexCoords,0);
18285 ReallocateMemory(Objects3DS^[i].Meshs^[j].Faces,0);
18286 end;
18287 ReallocateMemory(Objects3DS^[i].Meshs,0);
18288 end;
18289 ReallocateMemory(Objects3DS,0);
18290 end;
18291 begin
18292 result:=false;
18293 if SrcSize>0 then begin
18294 SrcPos:=0;
18295 if Read(Signature3DS,SizeOf(word))=SizeOf(word) then begin
18296 if Signature3DS=CHUNK_3DS_MAIN then begin
18297 if Read(Size3DS,SizeOf(longword))=SizeOf(longword) then begin
18298 Objects3DS:=nil;
18299 NumObjects3DS:=0;
18300 result:=Read3DSChunks(Signature3DS,Size3DS)>0;
18301 if assigned(Objects3DS) then begin
18302 if result then begin
18303 Convert3DS;
18304 end;
18305 Free3DS;
18306 end;
18307 end;
18308 end;
18309 end;
18310 end;
18311 end;
18312 var OK:boolean;
18313 begin
18314 OK:=false;
18315 if ASourceSize>SizeOf(TFileSignature) then begin
18316 SrcPos:=0;
18317 if Read(Signature,SizeOf(TFileSignature))=SizeOf(TFileSignature) then begin
18318 if (Signature[0]='P') and (Signature[1]='M') and (Signature[2]='F') and (Signature[3]='0') then begin
18319 LoadPMF;
18320 OK:=true;
18321 end;
18322 end;
18323 if not OK then begin
18324 if Load3DS(ASourceData,ASourceSize) then begin
18325 OK:=true;
18326 end;
18327 end;
18328 end;
18329 if not OK then begin
18330 raise EKraftCorruptMeshData.Create('Corrupt mesh data');
18331 end;
18332 end;
18333
18334 procedure TKraftMesh.Scale(const WithFactor:TKraftScalar);
18335 var Index:longint;
18336 begin
18337 for Index:=0 to fCountVertices-1 do begin
18338 Vector3Scale(fVertices[Index],WithFactor);
18339 end;
18340 end;
18341
18342 procedure TKraftMesh.Scale(const WithVector:TKraftVector3);
18343 var Index:longint;
18344 begin
18345 for Index:=0 to fCountVertices-1 do begin
18346 Vector3Scale(fVertices[Index],WithVector.x,WithVector.y,WithVector.z);
18347 end;
18348 end;
18349
18350 procedure TKraftMesh.Transform(const WithMatrix:TKraftMatrix3x3);
18351 var Index:longint;
18352 begin
18353 for Index:=0 to fCountVertices-1 do begin
18354 Vector3MatrixMul(fVertices[Index],WithMatrix);
18355 end;
18356 end;
18357
18358 procedure TKraftMesh.Transform(const WithMatrix:TKraftMatrix4x4);
18359 var Index:longint;
18360 begin
18361 for Index:=0 to fCountVertices-1 do begin
18362 Vector3MatrixMul(fVertices[Index],WithMatrix);
18363 end;
18364 end;
18365
18366 procedure TKraftMesh.CalculateNormals;
18367 var TriangleIndex,NormalIndex,Counter:longint;
18368 NormalCounts:array of longint;
18369 Triangle:PKraftMeshTriangle;
18370 begin
18371 NormalCounts:=nil;
18372 try
18373 if fCountTriangles>0 then begin
18374 fCountNormals:=fCountVertices;
18375 SetLength(NormalCounts,fCountNormals);
18376 SetLength(fNormals,fCountNormals);
18377 for NormalIndex:=0 to fCountNormals-1 do begin
18378 NormalCounts[NormalIndex]:=0;
18379 fNormals[NormalIndex]:=Vector3Origin;
18380 end;
18381 for TriangleIndex:=0 to fCountTriangles-1 do begin
18382 Triangle:=@fTriangles[TriangleIndex];
18383 Triangle^.Normals[0]:=Triangle^.Vertices[0];
18384 Triangle^.Normals[1]:=Triangle^.Vertices[1];
18385 Triangle^.Normals[2]:=Triangle^.Vertices[2];
18386 Triangle^.Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(fVertices[Triangle^.Vertices[1]],fVertices[Triangle^.Vertices[0]]),Vector3Sub(fVertices[Triangle^.Vertices[2]],fVertices[Triangle^.Vertices[0]])));
18387 Triangle^.Plane.Distance:=-Vector3Dot(Triangle^.Plane.Normal,fVertices[Triangle^.Vertices[0]]);
18388 for Counter:=0 to 2 do begin
18389 NormalIndex:=Triangle^.Normals[Counter];
18390 inc(NormalCounts[NormalIndex]);
18391 Vector3DirectAdd(fNormals[NormalIndex],Triangle^.Plane.Normal);
18392 end;
18393 end;
18394 for NormalIndex:=0 to fCountNormals-1 do begin
18395 Vector3Normalize(fNormals[NormalIndex]);
18396 end;
18397 end;
18398 finally
18399 SetLength(NormalCounts,0);
18400 end;
18401 end;
18402
18403 procedure TKraftMesh.Finish;
18404 type PAABBTreeNode=^TAABBTreeNode;
18405 TAABBTreeNode=record
18406 AABB:TKraftAABB;
18407 Children:array[0..1] of longint;
18408 TriangleIndex:longint;
18409 end;
18410 TAABBTreeNodes=array of TAABBTreeNode;
18411 var Counter,StackPointer,CurrentNodeIndex,LeftCount,RightCount,ParentCount,AxisCounter,Axis,BestAxis,TriangleIndex,
18412 Balance,BestBalance,NextTriangleIndex,LeftNodeIndex,RightNodeIndex,TargetNodeIndex,Count,Root,CountNodes,Index,
18413 NodeID,Pass,NewStackCapacity:longint;
18414 Stack:array of longint;
18415 Points:array[0..2] of array of TKraftScalar;
18416 Center,Median:TKraftVector3;
18417 LeftAABB,RightAABB:TKraftAABB;
18418 Nodes:TAABBTreeNodes;
18419 Node:PAABBTreeNode;
18420 SkipListNode:PKraftMeshSkipListNode;
18421 Triangle:PKraftMeshTriangle;
18422 TriangleAABBs:array of TKraftAABB;
18423 CurrentAABB:PKraftAABB;
18424 v0,v1,v2:PKraftVector3;
18425 begin
18426 if length(fVertices)<>fCountVertices then begin
18427 SetLength(fVertices,fCountVertices);
18428 end;
18429 if length(fTriangles)<>fCountTriangles then begin
18430 SetLength(fTriangles,fCountTriangles);
18431 end;
18432 for Index:=0 to fCountTriangles-1 do begin
18433 Triangle:=@fTriangles[Index];
18434 if (Triangle^.Normals[0]<0) or (Triangle^.Normals[1]<0) or (Triangle^.Normals[2]<0) then begin
18435 CalculateNormals;
18436 break;
18437 end;
18438 end;
18439 if fCountSkipListNodes=0 then begin
18440 if fCountTriangles>0 then begin
18441 Stack:=nil;
18442 Nodes:=nil;
18443 Points[0]:=nil;
18444 Points[1]:=nil;
18445 Points[2]:=nil;
18446 TriangleAABBs:=nil;
18447 try
18448 SetLength(TriangleAABBs,fCountTriangles);
18449 for Index:=0 to fCountTriangles-1 do begin
18450 Triangle:=@fTriangles[Index];
18451 v0:=@fVertices[Triangle^.Vertices[0]];
18452 v1:=@fVertices[Triangle^.Vertices[1]];
18453 v2:=@fVertices[Triangle^.Vertices[2]];
18454 CurrentAABB:=@TriangleAABBs[Index];
18455 CurrentAABB^.Min.x:=Min(Min(v0^.x,v1^.x),v2^.x)-EPSILON;
18456 CurrentAABB^.Min.y:=Min(Min(v0^.y,v1^.y),v2^.y)-EPSILON;
18457 CurrentAABB^.Min.z:=Min(Min(v0^.z,v1^.z),v2^.z)-EPSILON;
18458 CurrentAABB^.Max.x:=Max(Max(v0^.x,v1^.x),v2^.x)+EPSILON;
18459 CurrentAABB^.Max.y:=Max(Max(v0^.y,v1^.y),v2^.y)+EPSILON;
18460 CurrentAABB^.Max.z:=Max(Max(v0^.z,v1^.z),v2^.z)+EPSILON;
18461 Triangle^.AABB:=TriangleAABBs[Index];
18462 end;
18463 Root:=0;
18464 CountNodes:=1;
18465 SetLength(Nodes,Max(CountNodes,fCountTriangles));
18466 SetLength(Points[0],fCountTriangles*6);
18467 SetLength(Points[1],fCountTriangles*6);
18468 SetLength(Points[2],fCountTriangles*6);
18469 Nodes[0].AABB:=TriangleAABBs[0];
18470 for Counter:=1 to fCountTriangles-1 do begin
18471 Nodes[0].AABB:=AABBCombine(Nodes[0].AABB,TriangleAABBs[Counter]);
18472 end;
18473 for Counter:=0 to fCountTriangles-2 do begin
18474 fTriangles[Counter].Next:=Counter+1;
18475 end;
18476 fTriangles[fCountTriangles-1].Next:=-1;
18477 Nodes[0].TriangleIndex:=0;
18478 Nodes[0].Children[0]:=-1;
18479 Nodes[0].Children[1]:=-1;
18480 SetLength(Stack,16);
18481 Stack[0]:=0;
18482 StackPointer:=1;
18483 while StackPointer>0 do begin
18484 dec(StackPointer);
18485 CurrentNodeIndex:=Stack[StackPointer];
18486 if (CurrentNodeIndex>=0) and (Nodes[CurrentNodeIndex].TriangleIndex>=0) then begin
18487 TriangleIndex:=Nodes[CurrentNodeIndex].TriangleIndex;
18488 Nodes[CurrentNodeIndex].AABB:=TriangleAABBs[TriangleIndex];
18489 TriangleIndex:=fTriangles[TriangleIndex].Next;
18490 ParentCount:=1;
18491 while TriangleIndex>=0 do begin
18492 Nodes[CurrentNodeIndex].AABB:=AABBCombine(Nodes[CurrentNodeIndex].AABB,TriangleAABBs[TriangleIndex]);
18493 inc(ParentCount);
18494 TriangleIndex:=fTriangles[TriangleIndex].Next;
18495 end;
18496 if ParentCount>3 then begin
18497 Center:=Vector3Avg(Nodes[CurrentNodeIndex].AABB.Min,Nodes[CurrentNodeIndex].AABB.Max);
18498 TriangleIndex:=Nodes[CurrentNodeIndex].TriangleIndex;
18499 Count:=0;
18500 while TriangleIndex>=0 do begin
18501 v0:=@fVertices[fTriangles[TriangleIndex].Vertices[0]];
18502 v1:=@fVertices[fTriangles[TriangleIndex].Vertices[1]];
18503 v2:=@fVertices[fTriangles[TriangleIndex].Vertices[2]];
18504 Points[0,Count]:=v0^.x;
18505 Points[1,Count]:=v0^.y;
18506 Points[2,Count]:=v0^.z;
18507 Points[0,Count+1]:=v1^.x;
18508 Points[1,Count+1]:=v1^.y;
18509 Points[2,Count+1]:=v1^.z;
18510 Points[0,Count+2]:=v2^.x;
18511 Points[1,Count+2]:=v2^.y;
18512 Points[2,Count+2]:=v2^.z;
18513 inc(Count,3);
18514 TriangleIndex:=fTriangles[TriangleIndex].Next;
18515 end;
18516 if Count>1 then begin
18517 DirectIntroSort(@Points[0,0],0,Count-1,SizeOf(TKraftScalar),@CompareFloat);
18518 DirectIntroSort(@Points[0,1],0,Count-1,SizeOf(TKraftScalar),@CompareFloat);
18519 DirectIntroSort(@Points[0,2],0,Count-1,SizeOf(TKraftScalar),@CompareFloat);
18520 Median.x:=Points[0,Count shr 1];
18521 Median.y:=Points[1,Count shr 1];
18522 Median.z:=Points[2,Count shr 1];
18523 end else begin
18524 Median:=Center;
18525 end;
18526 BestAxis:=-1;
18527 BestBalance:=$7fffffff;
18528 for AxisCounter:=0 to 5 do begin
18529 if AxisCounter>2 then begin
18530 Axis:=AxisCounter-3;
18531 end else begin
18532 Axis:=AxisCounter;
18533 end;
18534 LeftCount:=0;
18535 RightCount:=0;
18536 LeftAABB:=Nodes[CurrentNodeIndex].AABB;
18537 RightAABB:=Nodes[CurrentNodeIndex].AABB;
18538 if AxisCounter>2 then begin
18539 LeftAABB.Max.xyz[Axis]:=Median.xyz[Axis];
18540 RightAABB.Min.xyz[Axis]:=Median.xyz[Axis];
18541 end else begin
18542 LeftAABB.Max.xyz[Axis]:=Center.xyz[Axis];
18543 RightAABB.Min.xyz[Axis]:=Center.xyz[Axis];
18544 end;
18545 TriangleIndex:=Nodes[CurrentNodeIndex].TriangleIndex;
18546 while TriangleIndex>=0 do begin
18547 if Vector3Avg(TriangleAABBs[TriangleIndex].Min,TriangleAABBs[TriangleIndex].Max).xyz[Axis]<RightAABB.Min.xyz[Axis] then begin
18548 inc(LeftCount);
18549 end else begin
18550 inc(RightCount);
18551 end;
18552 TriangleIndex:=fTriangles[TriangleIndex].Next;
18553 end;
18554 if (LeftCount>0) and (RightCount>0) then begin
18555 Balance:=abs(RightCount-LeftCount);
18556 if BestBalance>Balance then begin
18557 BestBalance:=Balance;
18558 BestAxis:=AxisCounter;
18559 end;
18560 end;
18561 end;
18562 if BestAxis>=0 then begin
18563 LeftNodeIndex:=CountNodes;
18564 RightNodeIndex:=CountNodes+1;
18565 inc(CountNodes,2);
18566 if CountNodes>=length(Nodes) then begin
18567 SetLength(Nodes,RoundUpToPowerOfTwo(CountNodes));
18568 end;
18569 LeftAABB:=Nodes[CurrentNodeIndex].AABB;
18570 RightAABB:=Nodes[CurrentNodeIndex].AABB;
18571 TriangleIndex:=Nodes[CurrentNodeIndex].TriangleIndex;
18572 Nodes[LeftNodeIndex].TriangleIndex:=-1;
18573 Nodes[RightNodeIndex].TriangleIndex:=-1;
18574 Nodes[CurrentNodeIndex].TriangleIndex:=-1;
18575 if BestAxis>2 then begin
18576 dec(BestAxis,3);
18577 LeftAABB.Max.xyz[BestAxis]:=Median.xyz[BestAxis];
18578 RightAABB.Min.xyz[BestAxis]:=Median.xyz[BestAxis];
18579 end else begin
18580 LeftAABB.Max.xyz[BestAxis]:=Center.xyz[BestAxis];
18581 RightAABB.Min.xyz[BestAxis]:=Center.xyz[BestAxis];
18582 end;
18583 Nodes[LeftNodeIndex].AABB:=LeftAABB;
18584 Nodes[RightNodeIndex].AABB:=RightAABB;
18585 while TriangleIndex>=0 do begin
18586 NextTriangleIndex:=fTriangles[TriangleIndex].Next;
18587 if Vector3Avg(TriangleAABBs[TriangleIndex].Min,TriangleAABBs[TriangleIndex].Max).xyz[BestAxis]<RightAABB.Min.xyz[BestAxis] then begin
18588 TargetNodeIndex:=LeftNodeIndex;
18589 end else begin
18590 TargetNodeIndex:=RightNodeIndex;
18591 end;
18592 fTriangles[TriangleIndex].Next:=Nodes[TargetNodeIndex].TriangleIndex;
18593 if Nodes[TargetNodeIndex].TriangleIndex<0 then begin
18594 Nodes[TargetNodeIndex].AABB:=TriangleAABBs[TriangleIndex];
18595 end else begin
18596 Nodes[TargetNodeIndex].AABB:=AABBCombine(Nodes[TargetNodeIndex].AABB,TriangleAABBs[TriangleIndex]);
18597 end;
18598 Nodes[TargetNodeIndex].TriangleIndex:=TriangleIndex;
18599 TriangleIndex:=NextTriangleIndex;
18600 end;
18601 Nodes[CurrentNodeIndex].Children[0]:=LeftNodeIndex;
18602 Nodes[CurrentNodeIndex].Children[1]:=RightNodeIndex;
18603 Nodes[LeftNodeIndex].Children[0]:=-1;
18604 Nodes[LeftNodeIndex].Children[1]:=-1;
18605 Nodes[RightNodeIndex].Children[0]:=-1;
18606 Nodes[RightNodeIndex].Children[1]:=-1;
18607 if (StackPointer+2)>=length(Stack) then begin
18608 SetLength(Stack,RoundUpToPowerOfTwo(StackPointer+2));
18609 end;
18610 Stack[StackPointer+0]:=RightNodeIndex;
18611 Stack[StackPointer+1]:=LeftNodeIndex;
18612 inc(StackPointer,2);
18613 end;
18614 end;
18615 end;
18616 end;
18617 SetLength(Nodes,CountNodes);
18618 begin
18619 fCountNodes:=CountNodes;
18620 fCountSkipListNodes:=0;
18621 if Root>=0 then begin
18622 begin
18623 // Pass 1 - Counting
18624 NewStackCapacity:=RoundUpToPowerOfTwo(CountNodes*4);
18625 if NewStackCapacity>length(Stack) then begin
18626 SetLength(Stack,NewStackCapacity);
18627 end;
18628 Stack[0]:=Root;
18629 StackPointer:=1;
18630 while StackPointer>0 do begin
18631 dec(StackPointer);
18632 NodeID:=Stack[StackPointer];
18633 if (NodeID>=0) and (NodeID<CountNodes) then begin
18634 Node:=@Nodes[NodeID];
18635 inc(fCountSkipListNodes);
18636 if Node^.Children[0]>=0 then begin
18637 NewStackCapacity:=RoundUpToPowerOfTwo(StackPointer+2);
18638 if NewStackCapacity>length(Stack) then begin
18639 SetLength(Stack,NewStackCapacity);
18640 end;
18641 Stack[StackPointer+0]:=Node^.Children[1];
18642 Stack[StackPointer+1]:=Node^.Children[0];
18643 inc(StackPointer,2);
18644 end;
18645 end;
18646 end;
18647 end;
18648 begin
18649 // Pass 2 - Resize arrays
18650 SetLength(fNodes,fCountNodes);
18651 SetLength(fSkipListNodes,fCountSkipListNodes);
18652 end;
18653 begin
18654 // Pass 3 - Fill arrays
18655 for Index:=0 to CountNodes-1 do begin
18656 Node:=@Nodes[Index];
18657 fNodes[Index].Children[0]:=Node^.Children[0];
18658 fNodes[Index].Children[1]:=Node^.Children[1];
18659 fNodes[Index].TriangleIndex:=Node^.TriangleIndex;
18660 fNodes[Index].AABB:=Node^.AABB;
18661 end;
18662 fCountSkipListNodes:=0;
18663 Stack[0]:=Root;
18664 Stack[1]:=0;
18665 Stack[2]:=0;
18666 StackPointer:=3;
18667 while StackPointer>0 do begin
18668 dec(StackPointer,3);
18669 NodeID:=Stack[StackPointer];
18670 Pass:=Stack[StackPointer+1];
18671 Index:=Stack[StackPointer+2];
18672 if (NodeID>=0) and (NodeID<CountNodes) then begin
18673 Node:=@Nodes[NodeID];
18674 case Pass of
18675 0:begin
18676 Index:=fCountSkipListNodes;
18677 inc(fCountSkipListNodes);
18678 SkipListNode:=@fSkipListNodes[Index];
18679 SkipListNode^.AABB.Min:=Node^.AABB.Min;
18680 SkipListNode^.AABB.Max:=Node^.AABB.Max;
18681 SkipListNode^.SkipToNodeIndex:=-1;
18682 if Node^.TriangleIndex>=0 then begin
18683 SkipListNode^.TriangleIndex:=Node^.TriangleIndex;
18684 end else begin
18685 SkipListNode^.TriangleIndex:=-1;
18686 end;
18687 if Node^.Children[0]>=0 then begin
18688 NewStackCapacity:=RoundUpToPowerOfTwo(StackPointer+9);
18689 if NewStackCapacity>length(Stack) then begin
18690 SetLength(Stack,NewStackCapacity);
18691 end;
18692 Stack[StackPointer+0]:=NodeID;
18693 Stack[StackPointer+1]:=1;
18694 Stack[StackPointer+2]:=Index;
18695 Stack[StackPointer+3]:=Node^.Children[1];
18696 Stack[StackPointer+4]:=0;
18697 Stack[StackPointer+5]:=0;
18698 Stack[StackPointer+6]:=Node^.Children[0];
18699 Stack[StackPointer+7]:=0;
18700 Stack[StackPointer+8]:=0;
18701 inc(StackPointer,9);
18702 end else begin
18703 NewStackCapacity:=RoundUpToPowerOfTwo(StackPointer+3);
18704 if NewStackCapacity>length(Stack) then begin
18705 SetLength(Stack,NewStackCapacity);
18706 end;
18707 Stack[StackPointer+0]:=NodeID;
18708 Stack[StackPointer+1]:=1;
18709 Stack[StackPointer+2]:=Index;
18710 inc(StackPointer,3);
18711 end;
18712 end;
18713 1:begin
18714 SkipListNode:=@fSkipListNodes[Index];
18715 SkipListNode^.SkipToNodeIndex:=fCountSkipListNodes;
18716 end;
18717 end;
18718 end;
18719 end;
18720 end;
18721 end;
18722 end;
18723 finally
18724 SetLength(Stack,0);
18725 end;
18726 end else begin
18727 SetLength(TriangleAABBs,0);
18728 SetLength(Nodes,0);
18729 SetLength(Points[0],0);
18730 SetLength(Points[1],0);
18731 SetLength(Points[2],0);
18732 end;
18733 for Index:=0 to fCountVertices-1 do begin
18734 if Index=0 then begin
18735 fAABB.Min:=fVertices[Index];
18736 fAABB.Max:=fVertices[Index];
18737 end else begin
18738 fAABB:=AABBCombineVector3(fAABB,fVertices[Index]);
18739 end;
18740 end;
18741 end;
18742 end;
18743
18744 function TKraftMesh.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
18745 {$ifdef KraftSingleThreadedUsage}
18746 type PStackItem=^TStackItem;
18747 TStackItem=record
18748 NodeIndex:longint;
18749 SquaredDistance:TKraftScalar;
18750 end;
18751 TStackItems=array[0..31] of TStackItem;
18752 var LocalStack:TStackItems;
18753 LocalStackPointer,TriangleIndex:longint;
18754 Node:PKraftMeshNode;
18755 Triangle,BestTriangle:PKraftMeshTriangle;
18756 StackItem:PStackItem;
18757 SquaredDistances:array[0..1] of TKraftScalar;
18758 SquaredDistance,SquaredThickness,SquaredThicknessEpsilon:TKraftScalar;
18759 begin
18760 if fCountNodes>0 then begin
18761 result:=MAX_SCALAR;
18762 BestTriangle:=nil;
18763 if fDoubleSided then begin
18764 SquaredThickness:=sqr(2.0*Physics.fLinearSlop);
18765 end else begin
18766 SquaredThickness:=0.0;
18767 end;
18768 SquaredThicknessEpsilon:=SquaredThickness+sqr(EPSILON);
18769 LocalStackPointer:=0;
18770 StackItem:=@LocalStack[LocalStackPointer];
18771 inc(LocalStackPointer);
18772 StackItem^.NodeIndex:=0;
18773 StackItem^.SquaredDistance:=SquaredDistanceFromPointToAABB(fNodes[0].AABB,Position);
18774 while LocalStackPointer>0 do begin
18775 dec(LocalStackPointer);
18776 StackItem:=@LocalStack[LocalStackPointer];
18777 if (StackItem^.SquaredDistance-SquaredThicknessEpsilon)<result then begin
18778 if StackItem^.NodeIndex>=0 then begin
18779 Node:=@fNodes[StackItem^.NodeIndex];
18780 TriangleIndex:=Node^.TriangleIndex;
18781 while TriangleIndex>=0 do begin
18782 Triangle:=@fTriangles[TriangleIndex];
18783 SquaredDistance:=SquaredDistanceFromPointToTriangle(Position,fVertices[Triangle^.Vertices[0]],fVertices[Triangle^.Vertices[1]],fVertices[Triangle^.Vertices[2]]);
18784 if result>SquaredDistance then begin
18785 result:=SquaredDistance;
18786 BestTriangle:=Triangle;
18787 end;
18788 TriangleIndex:=Triangle^.Next;
18789 end;
18790 if (Node^.Children[0]>=0) and (Node^.Children[1]>=0) then begin
18791 SquaredDistances[0]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[0]].AABB,Position);
18792 SquaredDistances[1]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[1]].AABB,Position);
18793 if SquaredDistances[0]<SquaredDistances[1] then begin
18794 if (SquaredDistances[0]-SquaredThicknessEpsilon)<result then begin
18795 StackItem:=@LocalStack[LocalStackPointer];
18796 inc(LocalStackPointer);
18797 StackItem^.NodeIndex:=Node^.Children[0];
18798 StackItem^.SquaredDistance:=SquaredDistances[0];
18799 end;
18800 if (SquaredDistances[1]-SquaredThicknessEpsilon)<result then begin
18801 StackItem:=@LocalStack[LocalStackPointer];
18802 inc(LocalStackPointer);
18803 StackItem^.NodeIndex:=Node^.Children[1];
18804 StackItem^.SquaredDistance:=SquaredDistances[1];
18805 end;
18806 end else begin
18807 if (SquaredDistances[1]-SquaredThicknessEpsilon)<result then begin
18808 StackItem:=@LocalStack[LocalStackPointer];
18809 inc(LocalStackPointer);
18810 StackItem^.NodeIndex:=Node^.Children[1];
18811 StackItem^.SquaredDistance:=SquaredDistances[1];
18812 end;
18813 if (SquaredDistances[0]-SquaredThicknessEpsilon)<result then begin
18814 StackItem:=@LocalStack[LocalStackPointer];
18815 inc(LocalStackPointer);
18816 StackItem^.NodeIndex:=Node^.Children[0];
18817 StackItem^.SquaredDistance:=SquaredDistances[0];
18818 end;
18819 end;
18820 end else begin
18821 if Node^.Children[0]>=0 then begin
18822 SquaredDistances[0]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[0]].AABB,Position);
18823 if (SquaredDistances[0]-SquaredThicknessEpsilon)<result then begin
18824 StackItem:=@LocalStack[LocalStackPointer];
18825 inc(LocalStackPointer);
18826 StackItem^.NodeIndex:=Node^.Children[0];
18827 StackItem^.SquaredDistance:=SquaredDistances[0];
18828 end;
18829 end;
18830 if Node^.Children[1]>=0 then begin
18831 SquaredDistances[1]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[1]].AABB,Position);
18832 if (SquaredDistances[1]-SquaredThicknessEpsilon)<result then begin
18833 StackItem:=@LocalStack[LocalStackPointer];
18834 inc(LocalStackPointer);
18835 StackItem^.NodeIndex:=Node^.Children[1];
18836 StackItem^.SquaredDistance:=SquaredDistances[1];
18837 end;
18838 end;
18839 end;
18840 end;
18841 end;
18842 end;
18843 result:=sqrt(result);
18844 if fDoubleSided then begin
18845 result:=result-(2.0*Physics.fLinearSlop);
18846 end else begin
18847 if assigned(BestTriangle) and (PlaneVectorDistance(BestTriangle^.Plane,Position)<0.0) then begin
18848 result:=-result;
18849 end;
18850 end;
18851 end else begin
18852 result:=0;
18853 end;
18854 end;
18855 {$else}
18856 var TriangleIndex:longint;
18857 Triangle,BestTriangle:PKraftMeshTriangle;
18858 SquaredDistances:array[0..1] of TKraftScalar;
18859 SquaredThickness,SquaredThicknessEpsilon:TKraftScalar;
18860 procedure ProcessNode(const NodeIndex:longint;SquaredDistance:TKraftScalar);
18861 var Node:PKraftMeshNode;
18862 begin
18863 if (NodeIndex>=0) and ((SquaredDistance-SquaredThicknessEpsilon)<result) then begin
18864 Node:=@fNodes[NodeIndex];
18865 TriangleIndex:=Node^.TriangleIndex;
18866 while TriangleIndex>=0 do begin
18867 Triangle:=@fTriangles[TriangleIndex];
18868 SquaredDistance:=SquaredDistanceFromPointToTriangle(Position,fVertices[Triangle^.Vertices[0]],fVertices[Triangle^.Vertices[1]],fVertices[Triangle^.Vertices[2]]);
18869 if result>SquaredDistance then begin
18870 result:=SquaredDistance;
18871 BestTriangle:=Triangle;
18872 end;
18873 TriangleIndex:=Triangle^.Next;
18874 end;
18875 if (Node^.Children[0]>=0) and (Node^.Children[1]>=0) then begin
18876 SquaredDistances[0]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[0]].AABB,Position);
18877 SquaredDistances[1]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[1]].AABB,Position);
18878 if SquaredDistances[0]<SquaredDistances[1] then begin
18879 if (SquaredDistances[0]-SquaredThicknessEpsilon)<result then begin
18880 ProcessNode(Node^.Children[0],SquaredDistances[0]);
18881 end;
18882 if (SquaredDistances[1]-SquaredThicknessEpsilon)<result then begin
18883 ProcessNode(Node^.Children[1],SquaredDistances[1]);
18884 end;
18885 end else begin
18886 if (SquaredDistances[1]-SquaredThicknessEpsilon)<result then begin
18887 ProcessNode(Node^.Children[1],SquaredDistances[1]);
18888 end;
18889 if (SquaredDistances[0]-SquaredThicknessEpsilon)<result then begin
18890 ProcessNode(Node^.Children[0],SquaredDistances[0]);
18891 end;
18892 end;
18893 end else begin
18894 if Node^.Children[0]>=0 then begin
18895 SquaredDistances[0]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[0]].AABB,Position);
18896 if (SquaredDistances[0]-SquaredThicknessEpsilon)<result then begin
18897 ProcessNode(Node^.Children[0],SquaredDistances[0]);
18898 end;
18899 end;
18900 if Node^.Children[1]>=0 then begin
18901 SquaredDistances[1]:=SquaredDistanceFromPointToAABB(fNodes[Node^.Children[1]].AABB,Position);
18902 if (SquaredDistances[1]-SquaredThicknessEpsilon)<result then begin
18903 ProcessNode(Node^.Children[0],SquaredDistances[1]);
18904 end;
18905 end;
18906 end;
18907 end;
18908 end;
18909 begin
18910 if fCountNodes>0 then begin
18911 result:=MAX_SCALAR;
18912 BestTriangle:=nil;
18913 if fDoubleSided then begin
18914 SquaredThickness:=sqr(2.0*Physics.fLinearSlop);
18915 end else begin
18916 SquaredThickness:=0.0;
18917 end;
18918 SquaredThicknessEpsilon:=SquaredThickness+sqr(EPSILON);
18919 ProcessNode(0,SquaredDistanceFromPointToAABB(fNodes[0].AABB,Position));
18920 result:=sqrt(result);
18921 if fDoubleSided then begin
18922 result:=result-(2.0*Physics.fLinearSlop);
18923 end else begin
18924 if assigned(BestTriangle) and (PlaneVectorDistance(BestTriangle^.Plane,Position)<0.0) then begin
18925 result:=-result;
18926 end;
18927 end;
18928 end else begin
18929 result:=0;
18930 end;
18931 end;
18932 {$endif}
18933
18934 constructor TKraftShape.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody);
18935 begin
18936 inherited Create;
18937
18938 fShapeType:=kstUnknown;
18939
18940 fPhysics:=APhysics;
18941
18942 fPhysics.fNewShapes:=true;
18943
18944 fRigidBody:=ARigidBody;
18945
18946 if assigned(fRigidBody) then begin
18947 if assigned(fRigidBody.fShapeLast) then begin
18948 fRigidBody.fShapeLast.fShapeNext:=self;
18949 fShapePrevious:=fRigidBody.fShapeLast;
18950 end else begin
18951 fRigidBody.fShapeFirst:=self;
18952 fShapePrevious:=nil;
18953 end;
18954 fRigidBody.fShapeLast:=self;
18955 fShapeNext:=nil;
18956
18957 inc(fRigidBody.fShapeCount);
18958 end;
18959
18960 fFlags:=[ksfCollision,ksfMass,ksfRayCastable];
18961
18962 fIsMesh:=false;
18963
18964 fFriction:=0.5;
18965
18966 fRestitution:=0.0;
18967
18968 fDensity:=1.0;
18969
18970 fUserData:=nil;
18971
18972 fStaticAABBTreeProxy:=-1;
18973 fSleepingAABBTreeProxy:=-1;
18974 fDynamicAABBTreeProxy:=-1;
18975 fKinematicAABBTreeProxy:=-1;
18976
18977 fShapeAABB.Min:=Vector3Origin;
18978 fShapeAABB.Max:=Vector3Origin;
18979
18980 fWorldAABB.Min:=Vector3Origin;
18981 fWorldAABB.Max:=Vector3Origin;
18982
18983 fLocalTransform:=Matrix4x4Identity;
18984
18985 fWorldTransform:=Matrix4x4Identity;
18986
18987 fLastWorldTransform:=Matrix4x4Identity;
18988
18989 fInterpolatedWorldTransform:=Matrix4x4Identity;
18990
18991 fLocalCentroid:=Vector3Origin;
18992
18993 fLocalCenterOfMass:=Vector3Origin;
18994
18995 FillChar(fMassData,SizeOf(TKraftMassData),AnsiChar(#0));
18996
18997 fFeatureRadius:=0.0;
18998
18999 fContinuousMinimumRadiusScaleFactor:=0.0;
19000
19001 {$ifdef DebugDraw}
19002 fDrawDisplayList:=0;
19003 {$endif}
19004
19005 fOnContactBegin:=nil;
19006 fOnContactEnd:=nil;
19007 fOnContactStay:=nil;
19008
19009 end;
19010
19011 destructor TKraftShape.Destroy;
19012 var ContactPairEdge,NextContactPairEdge:PKraftContactPairEdge;
19013 ContactPair:PKraftContactPair;
19014 begin
19015
19016 {$ifdef DebugDraw}
19017 if fDrawDisplayList<>0 then begin
19018 glDeleteLists(fDrawDisplayList,1);
19019 fDrawDisplayList:=0;
19020 end;
19021 {$endif}
19022
19023 if assigned(fRigidBody) then begin
19024 ContactPairEdge:=fRigidBody.fContactPairEdgeFirst;
19025 while assigned(ContactPairEdge) do begin
19026 ContactPair:=ContactPairEdge^.ContactPair;
19027 NextContactPairEdge:=ContactPairEdge^.Next;
19028 if (ContactPair^.Shapes[0]=self) or (ContactPair^.Shapes[1]=self) then begin
19029 fPhysics.fContactManager.RemoveContact(ContactPair);
19030 end;
19031 ContactPairEdge:=NextContactPairEdge;
19032 end;
19033 end;
19034
19035 if fStaticAABBTreeProxy>=0 then begin
19036 if fPhysics.NewShapes then
19037 fPhysics.fBroadPhase.StaticBufferClearMove(fStaticAABBTreeProxy);
19038 fPhysics.fStaticAABBTree.DestroyProxy(fStaticAABBTreeProxy);
19039 fStaticAABBTreeProxy:=-1;
19040 end;
19041
19042 if fSleepingAABBTreeProxy>=0 then begin
19043 fPhysics.fSleepingAABBTree.DestroyProxy(fSleepingAABBTreeProxy);
19044 fSleepingAABBTreeProxy:=-1;
19045 end;
19046
19047 if fDynamicAABBTreeProxy>=0 then begin
19048 if fPhysics.NewShapes then
19049 fPhysics.fBroadPhase.DynamicBufferClearMove(fDynamicAABBTreeProxy);
19050 fPhysics.fDynamicAABBTree.DestroyProxy(fDynamicAABBTreeProxy);
19051 fDynamicAABBTreeProxy:=-1;
19052 end;
19053
19054 if fKinematicAABBTreeProxy>=0 then begin
19055 if fPhysics.NewShapes then
19056 fPhysics.fBroadPhase.KinematicBufferClearMove(fKinematicAABBTreeProxy);
19057 fPhysics.fKinematicAABBTree.DestroyProxy(fKinematicAABBTreeProxy);
19058 fKinematicAABBTreeProxy:=-1;
19059 end;
19060
19061 if assigned(fRigidBody) then begin
19062 if assigned(fShapePrevious) then begin
19063 fShapePrevious.fShapeNext:=fShapeNext;
19064 end else if fRigidBody.fShapeFirst=self then begin
19065 fRigidBody.fShapeFirst:=fShapeNext;
19066 end;
19067 if assigned(fShapeNext) then begin
19068 fShapeNext.fShapePrevious:=fShapePrevious;
19069 end else if fRigidBody.fShapeLast=self then begin
19070 fRigidBody.fShapeLast:=fShapePrevious;
19071 end;
19072 fShapePrevious:=nil;
19073 fShapeNext:=nil;
19074
19075 dec(fRigidBody.fShapeCount);
19076 end;
19077
19078 inherited Destroy;
19079 end;
19080
19081 function TKraftShape.GetProxyFatWorldAABB:PKraftAABB;
19082 begin
19083 if fStaticAABBTreeProxy>=0 then begin
19084 result:[email protected][fStaticAABBTreeProxy].AABB;
19085 end else if fSleepingAABBTreeProxy>=0 then begin
19086 result:[email protected][fSleepingAABBTreeProxy].AABB;
19087 end else if fDynamicAABBTreeProxy>=0 then begin
19088 result:[email protected][fDynamicAABBTreeProxy].AABB;
19089 end else if fKinematicAABBTreeProxy>=0 then begin
19090 result:[email protected][fKinematicAABBTreeProxy].AABB;
19091 end else begin
19092 result:=@fWorldAABB;
19093 end;
19094 end;
19095
19096 procedure TKraftShape.UpdateShapeAABB;
19097 begin
19098 end;
19099
19100 procedure TKraftShape.CalculateMassData;
19101 begin
19102 end;
19103
19104 procedure TKraftShape.SynchronizeTransform;
19105 begin
19106 if assigned(fRigidBody) then begin
19107 fWorldTransform:=Matrix4x4TermMul(fLocalTransform,fRigidBody.fWorldTransform);
19108 end else begin
19109 fWorldTransform:=fLocalTransform;
19110 end;
19111 end;
19112
19113 procedure TKraftShape.SynchronizeProxies;
19114 var NeedUpdate:boolean;
19115 WorldCenterOfMass,WorldDisplacement,WorldBoundsExpansion,TempPoint:TKraftVector3;
19116 TempAABB:TKraftAABB;
19117 begin
19118
19119 if assigned(fRigidBody) then begin
19120 fWorldTransform:=Matrix4x4TermMul(fLocalTransform,fRigidBody.fWorldTransform);
19121 end else begin
19122 fWorldTransform:=fLocalTransform;
19123 end;
19124 WorldCenterOfMass:=Vector3TermMatrixMul(fLocalCenterOfMass,fWorldTransform);
19125
19126 case fShapeType of
19127 kstSphere:begin
19128 fWorldAABB.Min:=Vector3Sub(WorldCenterOfMass,Vector3(TKraftShapeSphere(self).fRadius,TKraftShapeSphere(self).fRadius,TKraftShapeSphere(self).fRadius));
19129 fWorldAABB.Max:=Vector3Add(WorldCenterOfMass,Vector3(TKraftShapeSphere(self).fRadius,TKraftShapeSphere(self).fRadius,TKraftShapeSphere(self).fRadius));
19130 end;
19131 kstCapsule:begin
19132 TempPoint:=Vector3Sub(WorldCenterOfMass,Vector3ScalarMul(Vector3(fWorldTransform[1,0],fWorldTransform[1,1],fWorldTransform[1,2]),(TKraftShapeCapsule(self).fHeight*0.5)));
19133 fWorldAABB.Min:=Vector3Sub(TempPoint,Vector3(TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius));
19134 fWorldAABB.Max:=Vector3Add(TempPoint,Vector3(TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius));
19135 TempPoint:=Vector3Add(WorldCenterOfMass,Vector3ScalarMul(Vector3(fWorldTransform[1,0],fWorldTransform[1,1],fWorldTransform[1,2]),(TKraftShapeCapsule(self).fHeight*0.5)));
19136 TempAABB.Min:=Vector3Sub(TempPoint,Vector3(TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius));
19137 TempAABB.Max:=Vector3Add(TempPoint,Vector3(TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius,TKraftShapeCapsule(self).fRadius));
19138 fWorldAABB:=AABBCombine(fWorldAABB,TempAABB);
19139 end;
19140 else begin
19141 fWorldAABB:=AABBTransform(fShapeAABB,fWorldTransform);
19142 end;
19143 end;
19144
19145 if assigned(fRigidBody) then begin
19146
19147 WorldDisplacement:=Vector3ScalarMul(fRigidBody.fLinearVelocity,fPhysics.fWorldDeltaTime);
19148 if Vector3LengthSquared(WorldDisplacement)<Vector3LengthSquared(fRigidBody.fWorldDisplacement) then begin
19149 WorldDisplacement:=fRigidBody.fWorldDisplacement;
19150 end;
19151
19152 WorldBoundsExpansion:=Vector3ScalarMul(Vector3(fAngularMotionDisc,fAngularMotionDisc,fAngularMotionDisc),Vector3Length(fRigidBody.fAngularVelocity)*fPhysics.fWorldDeltaTime);
19153
19154 if (fRigidBody.fRigidBodyType<>krbtStatic) and (fStaticAABBTreeProxy>=0) then begin
19155 fPhysics.fStaticAABBTree.DestroyProxy(fStaticAABBTreeProxy);
19156 fStaticAABBTreeProxy:=-1;
19157 end else if fRigidBody.fRigidBodyType=krbtStatic then begin
19158 NeedUpdate:=false;
19159 if fStaticAABBTreeProxy<0 then begin
19160 fStaticAABBTreeProxy:=fPhysics.fStaticAABBTree.CreateProxy(fWorldAABB,self);
19161 NeedUpdate:=true;
19162 end;
19163 if fPhysics.fStaticAABBTree.MoveProxy(fStaticAABBTreeProxy,fWorldAABB,Vector3Origin,Vector3Origin) then begin
19164 NeedUpdate:=true;
19165 end;
19166 if NeedUpdate then begin
19167 fPhysics.fBroadPhase.StaticBufferMove(fStaticAABBTreeProxy);
19168 end;
19169 end;
19170
19171 if (fRigidBody.fRigidBodyType<>krbtDynamic) and (fDynamicAABBTreeProxy>=0) then begin
19172 fPhysics.fDynamicAABBTree.DestroyProxy(fDynamicAABBTreeProxy);
19173 fDynamicAABBTreeProxy:=-1;
19174 end else if fRigidBody.fRigidBodyType=krbtDynamic then begin
19175 NeedUpdate:=false;
19176 if fDynamicAABBTreeProxy<0 then begin
19177 fDynamicAABBTreeProxy:=fPhysics.fDynamicAABBTree.CreateProxy(fWorldAABB,self);
19178 NeedUpdate:=true;
19179 end;
19180 if fPhysics.fDynamicAABBTree.MoveProxy(fDynamicAABBTreeProxy,fWorldAABB,WorldDisplacement,WorldBoundsExpansion) then begin
19181 NeedUpdate:=true;
19182 end;
19183 if NeedUpdate then begin
19184 fPhysics.fBroadPhase.DynamicBufferMove(fDynamicAABBTreeProxy);
19185 end;
19186 end;
19187
19188 if (fRigidBody.fRigidBodyType<>krbtKinematic) and (fKinematicAABBTreeProxy>=0) then begin
19189 fPhysics.fKinematicAABBTree.DestroyProxy(fKinematicAABBTreeProxy);
19190 fKinematicAABBTreeProxy:=-1;
19191 end else if fRigidBody.fRigidBodyType=krbtKinematic then begin
19192 NeedUpdate:=false;
19193 if fKinematicAABBTreeProxy<0 then begin
19194 fKinematicAABBTreeProxy:=fPhysics.fKinematicAABBTree.CreateProxy(fWorldAABB,self);
19195 NeedUpdate:=true;
19196 end;
19197 if fPhysics.fKinematicAABBTree.MoveProxy(fKinematicAABBTreeProxy,fWorldAABB,fRigidBody.fWorldDisplacement,Vector3Origin) then begin
19198 NeedUpdate:=true;
19199 end;
19200 if NeedUpdate then begin
19201 fPhysics.fBroadPhase.KinematicBufferMove(fKinematicAABBTreeProxy);
19202 end;
19203 end;
19204
19205 end;
19206
19207 end;
19208
19209 procedure TKraftShape.Finish;
19210 begin
19211 CalculateMassData;
19212 UpdateShapeAABB;
19213 fShapeSphere:=SphereFromAABB(fShapeAABB);
19214 fAngularMotionDisc:=Vector3Length(fShapeSphere.Center)+fShapeSphere.Radius;
19215 end;
19216
19217 function TKraftShape.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
19218 begin
19219 result:=0.0;
19220 end;
19221
19222 function TKraftShape.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
19223 begin
19224 result:=Vector3Origin;
19225 end;
19226
19227 function TKraftShape.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
19228 begin
19229 result:=Vector3Origin;
19230 end;
19231
19232 function TKraftShape.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
19233 begin
19234 result:=-1;
19235 end;
19236
19237 function TKraftShape.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
19238 begin
19239 result:=Vector3TermMatrixMul(fLocalCentroid,Transform);
19240 end;
19241
19242 function TKraftShape.TestPoint(const p:TKraftVector3):boolean;
19243 begin
19244 result:=false;
19245 end;
19246
19247 function TKraftShape.RayCast(var RayCastData:TKraftRaycastData):boolean;
19248 begin
19249 result:=false;
19250 end;
19251
19252 procedure TKraftShape.StoreWorldTransform;
19253 begin
19254 fLastWorldTransform:=fWorldTransform;
19255 end;
19256
19257 procedure TKraftShape.InterpolateWorldTransform(const Alpha:TKraftScalar);
19258 begin
19259 fInterpolatedWorldTransform:=Matrix4x4Slerp(fLastWorldTransform,fWorldTransform,Alpha);
19260 end;
19261
19262 {$ifdef DebugDraw}
19263 procedure TKraftShape.Draw(const CameraMatrix:TKraftMatrix4x4);
19264 begin
19265 end;
19266 {$endif}
19267
19268 constructor TKraftShapeSphere.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const ARadius:TKraftScalar);
19269 begin
19270 fRadius:=ARadius;
19271 inherited Create(APhysics,ARigidBody);
19272 fShapeType:=kstSphere;
19273 fFeatureRadius:=ARadius;
19274 end;
19275
19276 destructor TKraftShapeSphere.Destroy;
19277 begin
19278 inherited Destroy;
19279 end;
19280
19281 procedure TKraftShapeSphere.UpdateShapeAABB;
19282 begin
19283 fShapeAABB.Min.x:=-fRadius;
19284 fShapeAABB.Min.y:=-fRadius;
19285 fShapeAABB.Min.z:=-fRadius;
19286 fShapeAABB.Max.x:=fRadius;
19287 fShapeAABB.Max.y:=fRadius;
19288 fShapeAABB.Max.z:=fRadius;
19289 end;
19290
19291 procedure TKraftShapeSphere.CalculateMassData;
19292 begin
19293 fMassData.Volume:=((4.0*pi)*(fRadius*fRadius*fRadius))/3.0;
19294 fMassData.Mass:=fMassData.Volume*fDensity;
19295 fMassData.Inertia[0,0]:=(2.0*(sqr(fRadius)*fMassData.Mass))/5.0;
19296 fMassData.Inertia[0,1]:=0.0;
19297 fMassData.Inertia[0,2]:=0.0;
19298 fMassData.Inertia[1,0]:=0.0;
19299 fMassData.Inertia[1,1]:=(2.0*(sqr(fRadius)*fMassData.Mass))/5.0;
19300 fMassData.Inertia[1,2]:=0.0;
19301 fMassData.Inertia[2,0]:=0.0;
19302 fMassData.Inertia[2,1]:=0.0;
19303 fMassData.Inertia[2,2]:=(2.0*(sqr(fRadius)*fMassData.Mass))/5.0;
19304 fMassData.Center.x:=fLocalTransform[3,0];
19305 fMassData.Center.y:=fLocalTransform[3,1];
19306 fMassData.Center.z:=fLocalTransform[3,2];
19307 Matrix3x3Add(fMassData.Inertia,InertiaTensorParallelAxisTheorem(fMassData.Center,fMassData.Mass));
19308 end;
19309
19310 function TKraftShapeSphere.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
19311 begin
19312 result:=Vector3Length(Vector3TermMatrixMulInverted(Position,fWorldTransform))-fRadius;
19313 end;
19314
19315 function TKraftShapeSphere.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
19316 begin
19317 result:=Vector3ScalarMul(Vector3SafeNorm(Direction),fRadius);
19318 end;
19319
19320 function TKraftShapeSphere.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
19321 begin
19322 result:=Vector3Origin;
19323 end;
19324
19325 function TKraftShapeSphere.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
19326 begin
19327 result:=0;
19328 end;
19329
19330 function TKraftShapeSphere.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
19331 begin
19332 result:=PKraftVector3(pointer(@Transform[3,0]))^;
19333 end;
19334
19335 function TKraftShapeSphere.TestPoint(const p:TKraftVector3):boolean;
19336 begin
19337 result:=Vector3Length(Vector3TermMatrixMulInverted(p,fWorldTransform))<=fRadius;
19338 end;
19339
19340 function TKraftShapeSphere.RayCast(var RayCastData:TKraftRaycastData):boolean;
19341 var Origin,Direction,m:TKraftVector3;
19342 p,d,s1,s2,t:TKraftScalar;
19343 begin
19344 result:=false;
19345 if ksfRayCastable in fFlags then begin
19346 Origin:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
19347 Direction:=Vector3SafeNorm(Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform));
19348 m:=Vector3Sub(Origin,Vector3Origin);
19349 p:=-Vector3Dot(m,Direction);
19350 d:=(sqr(p)-Vector3LengthSquared(m))+sqr(fRadius);
19351 if d>0.0 then begin
19352 d:=sqrt(d);
19353 s1:=p-d;
19354 s2:=p+d;
19355 if s2>0.0 then begin
19356 if s1<0.0 then begin
19357 t:=s2;
19358 end else begin
19359 t:=s1;
19360 end;
19361 if (t>=0.0) and (t<=RayCastData.MaxTime) then begin
19362 RayCastData.TimeOfImpact:=t;
19363 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,t)),fWorldTransform);
19364 RayCastData.Normal:=Vector3NormEx(Vector3Sub(RayCastData.Point,Vector3TermMatrixMul(Vector3Origin,fWorldTransform)));
19365 result:=true;
19366 end;
19367 end;
19368 end;
19369 end;
19370 end;
19371
19372 {$ifdef DebugDraw}
19373 procedure TKraftShapeSphere.Draw(const CameraMatrix:TKraftMatrix4x4);
19374 const lats=16;
19375 longs=16;
19376 pi2=pi*2.0;
19377 var i,j:longint;
19378 lat0,z0,zr0,lat1,z1,zr1,lng,x,y:TKraftScalar;
19379 ModelViewMatrix:TKraftMatrix4x4;
19380 begin
19381 glPushMatrix;
19382 glMatrixMode(GL_MODELVIEW);
19383 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
19384 {$ifdef UseDouble}
19385 glLoadMatrixd(pointer(@ModelViewMatrix));
19386 {$else}
19387 glLoadMatrixf(pointer(@ModelViewMatrix));
19388 {$endif}
19389
19390 if fDrawDisplayList=0 then begin
19391 fDrawDisplayList:=glGenLists(1);
19392 glNewList(fDrawDisplayList,GL_COMPILE);
19393
19394 for i:=0 to lats do begin
19395 lat0:=pi*(((i-1)/lats)-0.5);
19396 z0:=sin(lat0)*fRadius;
19397 zr0:=cos(lat0)*fRadius;
19398 lat1:=pi*((i/lats)-0.5);
19399 z1:=sin(lat1)*fRadius;
19400 zr1:=cos(lat1)*fRadius;
19401 glBegin(GL_QUAD_STRIP);
19402 for j:=0 to longs do begin
19403 lng:=pi2*((j-1)/longs);
19404 x:=cos(lng);
19405 y:=sin(lng);
19406 glNormal3f(x*zr1,y*zr1,z1);
19407 glVertex3f(x*zr1,y*zr1,z1);
19408 glNormal3f(x*zr0,y*zr0,z0);
19409 glVertex3f(x*zr0,y*zr0,z0);
19410 end;
19411 glEnd;
19412 end;
19413
19414 glEndList;
19415 end;
19416
19417 if fDrawDisplayList<>0 then begin
19418 glCallList(fDrawDisplayList);
19419 end;
19420
19421 glPopMatrix;
19422 end;
19423 {$endif}
19424
19425 constructor TKraftShapeCapsule.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const ARadius,AHeight:TKraftScalar);
19426 begin
19427 fRadius:=ARadius;
19428 fHeight:=AHeight;
19429 inherited Create(APhysics,ARigidBody);
19430 fShapeType:=kstCapsule;
19431 fFeatureRadius:=ARadius;
19432 end;
19433
19434 destructor TKraftShapeCapsule.Destroy;
19435 begin
19436 inherited Destroy;
19437 end;
19438
19439 procedure TKraftShapeCapsule.UpdateShapeAABB;
19440 begin
19441 fShapeAABB.Min.x:=-fRadius;
19442 fShapeAABB.Min.y:=-(fRadius+(fHeight*0.5));
19443 fShapeAABB.Min.z:=-fRadius;
19444 fShapeAABB.Max.x:=fRadius;
19445 fShapeAABB.Max.y:=fRadius+(fHeight*0.5);
19446 fShapeAABB.Max.z:=fRadius;
19447 end;
19448
19449 //{$define UseTKraftShapeCapsuleCalculateMassDataReferenceTestImplementation}
19450 {$ifdef UseTKraftShapeCapsuleCalculateMassDataReferenceTestImplementation}
19451 procedure TKraftShapeCapsule.CalculateMassData;
19452 var RadiusSquared:TKraftScalar;
19453 CapMassData,CylinderMassData:TKraftMassData;
19454 begin
19455 RadiusSquared:=sqr(fRadius);
19456 begin
19457 CapMassData.Volume:=(2.0/3.0)*pi*RadiusSquared*fRadius;
19458 CapMassData.Mass:=CapMassData.Volume*Density;
19459 CapMassData.Inertia[0,0]:=((2.0/5.0)*CapMassData.Mass*RadiusSquared)+(CapMassData.Mass*fHeight*(((3.0*fRadius)+(2.0*fHeight))/8.0));
19460 CapMassData.Inertia[0,1]:=0.0;
19461 CapMassData.Inertia[0,2]:=0.0;
19462 CapMassData.Inertia[1,0]:=0.0;
19463 CapMassData.Inertia[1,1]:=(2.0/5.0)*CapMassData.Mass*RadiusSquared;
19464 CapMassData.Inertia[1,2]:=0.0;
19465 CapMassData.Inertia[2,0]:=0.0;
19466 CapMassData.Inertia[2,1]:=0.0;
19467 CapMassData.Inertia[2,2]:=((2.0/5.0)*CapMassData.Mass*RadiusSquared)+(CapMassData.Mass*fHeight*(((3.0*fRadius)+(2.0*fHeight))/8.0));
19468 end;
19469 begin
19470 CylinderMassData.Volume:=pi*RadiusSquared*fHeight;
19471 CylinderMassData.Mass:=CylinderMassData.Volume*Density;
19472 CylinderMassData.Inertia[0,0]:=(1.0/12.0)*CylinderMassData.Mass*((3.0*RadiusSquared)+sqr(fHeight));
19473 CylinderMassData.Inertia[0,1]:=0.0;
19474 CylinderMassData.Inertia[0,2]:=0.0;
19475 CylinderMassData.Inertia[1,0]:=0.0;
19476 CylinderMassData.Inertia[1,1]:=(1.0/2.0)*CylinderMassData.Mass*RadiusSquared;
19477 CylinderMassData.Inertia[1,2]:=0.0;
19478 CylinderMassData.Inertia[2,0]:=0.0;
19479 CylinderMassData.Inertia[2,1]:=0.0;
19480 CylinderMassData.Inertia[2,2]:=(1.0/12.0)*CylinderMassData.Mass*((3.0*RadiusSquared)+sqr(fHeight));
19481 end;
19482 fMassData.Volume:=(CapMassData.Volume*2.0)+CylinderMassData.Volume;
19483 fMassData.Mass:=(CapMassData.Mass*2.0)+CylinderMassData.Mass;
19484 fMassData.Inertia[0,0]:=(CapMassData.Inertia[0,0]*2.0)+CylinderMassData.Inertia[0,0];
19485 fMassData.Inertia[0,1]:=(CapMassData.Inertia[0,1]*2.0)+CylinderMassData.Inertia[0,1];
19486 fMassData.Inertia[0,2]:=(CapMassData.Inertia[0,2]*2.0)+CylinderMassData.Inertia[0,2];
19487 fMassData.Inertia[1,0]:=(CapMassData.Inertia[1,0]*2.0)+CylinderMassData.Inertia[1,0];
19488 fMassData.Inertia[1,1]:=(CapMassData.Inertia[1,1]*2.0)+CylinderMassData.Inertia[1,1];
19489 fMassData.Inertia[1,2]:=(CapMassData.Inertia[1,2]*2.0)+CylinderMassData.Inertia[1,2];
19490 fMassData.Inertia[2,0]:=(CapMassData.Inertia[2,0]*2.0)+CylinderMassData.Inertia[2,0];
19491 fMassData.Inertia[2,1]:=(CapMassData.Inertia[2,1]*2.0)+CylinderMassData.Inertia[2,1];
19492 fMassData.Inertia[2,2]:=(CapMassData.Inertia[2,2]*2.0)+CylinderMassData.Inertia[2,2];
19493 fMassData.Center.x:=fLocalTransform[3,0];
19494 fMassData.Center.y:=fLocalTransform[3,1];
19495 fMassData.Center.z:=fLocalTransform[3,2];
19496 fMassData.Inertia:=Matrix3x3TermAdd(InertiaTensorTransform(fMassData.Inertia,Matrix3x3(fLocalTransform)),
19497 InertiaTensorParallelAxisTheorem(fMassData.Center,fMassData.Mass));
19498 end;
19499 {$else}
19500 procedure TKraftShapeCapsule.CalculateMassData;
19501 begin
19502 fMassData.Volume:=(pi*(fRadius*fRadius))*(fHeight+((4.0*fRadius)/3.0));
19503 fMassData.Mass:=fMassData.Volume*fDensity;
19504 fMassData.Inertia[0,0]:=(((5.0*(fHeight*fHeight*fHeight))+(20.0*(fHeight*fHeight)*fRadius)+(45.0*fHeight*(fRadius*fRadius))+(32.0*(fRadius*fRadius*fRadius)))/((60.0*fHeight)+(80.0*fRadius)))*fMassData.Mass;
19505 fMassData.Inertia[0,1]:=0.0;
19506 fMassData.Inertia[0,2]:=0.0;
19507 fMassData.Inertia[1,0]:=0.0;
19508 fMassData.Inertia[1,1]:=(((fRadius*fRadius)*((15.0*fHeight)+(16.0*fRadius)))/((30.0*fHeight)+(40.0*fRadius)))*fMassData.Mass;
19509 fMassData.Inertia[1,2]:=0.0;
19510 fMassData.Inertia[2,0]:=0.0;
19511 fMassData.Inertia[2,1]:=0.0;
19512 fMassData.Inertia[2,2]:=(((5.0*(fHeight*fHeight*fHeight))+(20.0*(fHeight*fHeight)*fRadius)+(45.0*fHeight*(fRadius*fRadius))+(32.0*(fRadius*fRadius*fRadius)))/((60.0*fHeight)+(80.0*fRadius)))*fMassData.Mass;
19513 fMassData.Center.x:=fLocalTransform[3,0];
19514 fMassData.Center.y:=fLocalTransform[3,1];
19515 fMassData.Center.z:=fLocalTransform[3,2];
19516 fMassData.Inertia:=Matrix3x3TermAdd(InertiaTensorTransform(fMassData.Inertia,Matrix3x3(fLocalTransform)),
19517 InertiaTensorParallelAxisTheorem(fMassData.Center,fMassData.Mass));
19518 end;
19519 {$endif}
19520
19521 function TKraftShapeCapsule.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
19522 var p,a,b,pa,ba:TKraftVector3;
19523 HalfHeight:TKraftScalar;
19524 begin
19525 HalfHeight:=fHeight*0.5;
19526 p:=Vector3TermMatrixMulInverted(Position,fWorldTransform);
19527 a.x:=0.0;
19528 a.y:=-HalfHeight;
19529 a.z:=0.0;
19530 b.x:=0.0;
19531 b.y:=HalfHeight;
19532 b.z:=0.0;
19533 pa:=Vector3Sub(p,a);
19534 ba:=Vector3Sub(b,a);
19535 result:=Vector3Length(Vector3Sub(pa,Vector3ScalarMul(b,Min(Max(Vector3Dot(pa,ba)/Vector3Dot(ba,ba),0.0),1.0))))-fRadius;
19536 end;
19537
19538 function TKraftShapeCapsule.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
19539 var Normal,p0,p1:TKraftVector3;
19540 HalfHeight:TKraftScalar;
19541 begin
19542 Normal:=Vector3SafeNorm(Direction);
19543 HalfHeight:=fHeight*0.5;
19544 p0.x:=(Normal.x*fRadius);
19545 p0.y:=(Normal.y*fRadius)-HalfHeight;
19546 p0.z:=(Normal.z*fRadius);
19547 p1.x:=(Normal.x*fRadius);
19548 p1.y:=(Normal.y*fRadius)+HalfHeight;
19549 p1.z:=(Normal.z*fRadius);
19550 if Vector3Dot(p0,Normal)<Vector3Dot(p1,Normal) then begin
19551 result:=p1;
19552 end else begin
19553 result:=p0;
19554 end;
19555 end;
19556
19557 function TKraftShapeCapsule.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
19558 begin
19559 result.x:=0.0;
19560 case Index of
19561 0:begin
19562 result.y:=-fHeight*0.5;
19563 end;
19564 else begin
19565 result.y:=fHeight*0.5;
19566 end;
19567 end;
19568 result.z:=0.0;
19569 end;
19570
19571 function TKraftShapeCapsule.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
19572 begin
19573 if Direction.y<0.0 then begin
19574 result:=0;
19575 end else begin
19576 result:=1;
19577 end;
19578 end;
19579
19580 function TKraftShapeCapsule.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
19581 begin
19582 result:=PKraftVector3(pointer(@Transform[3,0]))^;
19583 end;
19584
19585 function TKraftShapeCapsule.TestPoint(const p:TKraftVector3):boolean;
19586 var v:TKraftVector3;
19587 HalfHeight:TKraftScalar;
19588 begin
19589 v:=Vector3TermMatrixMulInverted(p,fWorldTransform);
19590 HalfHeight:=fHeight*0.5;
19591 result:=(abs(v.y)<=(HalfHeight+fRadius)) and (Vector3Length(Vector3(v.x,Min(Max(v.y,-HalfHeight),HalfHeight),v.z))<=fRadius);
19592 end;
19593
19594 function TKraftShapeCapsule.RayCast(var RayCastData:TKraftRaycastData):boolean;
19595 var Origin,Direction,p,m:TKraftVector3;
19596 Aq,Bq,Cq,t,t0,t1,y0,y1,HalfHeight,pp,d,s1,s2:TKraftScalar;
19597 begin
19598 result:=false;
19599 if ksfRayCastable in fFlags then begin
19600 Origin:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
19601 Direction:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform));
19602 HalfHeight:=fHeight*0.5;
19603 Aq:=sqr(Direction.x)+sqr(Direction.z);
19604 Bq:=((2.0*Origin.x)*Direction.x)+((2.0*Origin.z)*Direction.z);
19605 Cq:=(sqr(Origin.x)+sqr(Origin.z))-sqr(fRadius);
19606 if SolveQuadraticRoots(Aq,Bq,Cq,t0,t1) then begin
19607 if t0>t1 then begin
19608 t:=t0;
19609 t0:=t1;
19610 t1:=t;
19611 end;
19612 y0:=Origin.y+(Direction.y*t0);
19613 y1:=Origin.y+(Direction.y*t1);
19614 if y0<(-HalfHeight) then begin
19615 if y1>=(-HalfHeight) then begin
19616 // if y0 < -HalfHeight and y1 >= -HalfHeight, then the ray hits the bottom Capsule cap
19617 t:=y0-y1;
19618 if t<>0.0 then begin
19619 t:=t0+(((t1-t0)*(y0+HalfHeight))/t);
19620 if (t>=0.0) and (t<=RayCastData.MaxTime) then begin
19621 RayCastData.TimeOfImpact:=t;
19622 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,t)),fWorldTransform);
19623 RayCastData.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(Vector3(0.0,-1.0,0.0),fWorldTransform));
19624 result:=true;
19625 exit;
19626 end;
19627 end;
19628 end;
19629 end else if y0>HalfHeight then begin
19630 if y1<=HalfHeight then begin
19631 // if y0 > HalfHeight and y1 <= HalfHeight, then the ray hits the top Capsule cap
19632 t:=y0-y1;
19633 if t<>0.0 then begin
19634 t:=t0+(((t1-t0)*(y0-HalfHeight))/t);
19635 if (t>=0.0) and (t<=RayCastData.MaxTime) then begin
19636 RayCastData.TimeOfImpact:=t;
19637 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,t)),fWorldTransform);
19638 RayCastData.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(Vector3(0.0,1.0,0.0),fWorldTransform));
19639 result:=true;
19640 exit;
19641 end;
19642 end;
19643 end;
19644 end else begin
19645 if (t0>=0.0) and (t0<=RayCastData.MaxTime) then begin
19646 // if y0 < HalfHeight and y0 > -HalfHeight and t0 >= 0.0, then the ray intersects then Capsule wall
19647 RayCastData.TimeOfImpact:=t0;
19648 p:=Vector3Add(Origin,Vector3ScalarMul(Direction,t0));
19649 RayCastData.Point:=Vector3TermMatrixMul(p,fWorldTransform);
19650 RayCastData.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(p,fWorldTransform));
19651 result:=true;
19652 exit;
19653 end;
19654 end;
19655 end;
19656 begin
19657 m:=Vector3Sub(Origin,Vector3(0.0,-HalfHeight,0.0));
19658 pp:=-Vector3Dot(m,Direction);
19659 d:=sqr(pp)-Vector3LengthSquared(m)+sqr(fRadius);
19660 if d>0.0 then begin
19661 d:=sqrt(d);
19662 s1:=pp-d;
19663 s2:=pp+d;
19664 if s2>0.0 then begin
19665 if s1<0.0 then begin
19666 t:=s2;
19667 end else begin
19668 t:=s1;
19669 end;
19670 if (t>=0.0) and (t<=RayCastData.MaxTime) then begin
19671 RayCastData.TimeOfImpact:=t;
19672 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,t)),fWorldTransform);
19673 RayCastData.Normal:=Vector3NormEx(Vector3Sub(RayCastData.Point,Vector3TermMatrixMul(Vector3(0.0,-HalfHeight,0.0),fWorldTransform)));
19674 result:=true;
19675 exit;
19676 end;
19677 end;
19678 end;
19679 end;
19680 begin
19681 m:=Vector3Sub(Origin,Vector3(0.0,HalfHeight,0.0));
19682 pp:=-Vector3Dot(m,Direction);
19683 d:=sqr(pp)-Vector3LengthSquared(m)+sqr(fRadius);
19684 if d>0.0 then begin
19685 d:=sqrt(d);
19686 s1:=pp-d;
19687 s2:=pp+d;
19688 if s2>0.0 then begin
19689 if s1<0.0 then begin
19690 t:=s2;
19691 end else begin
19692 t:=s1;
19693 end;
19694 if (t>=0.0) and (t<=RayCastData.MaxTime) then begin
19695 RayCastData.TimeOfImpact:=t;
19696 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,t)),fWorldTransform);
19697 RayCastData.Normal:=Vector3NormEx(Vector3Sub(RayCastData.Point,Vector3TermMatrixMul(Vector3(0.0,HalfHeight,0.0),fWorldTransform)));
19698 result:=true;
19699 end;
19700 end;
19701 end;
19702 end;
19703 end;
19704 end;
19705
19706 {$ifdef DebugDraw}
19707 procedure TKraftShapeCapsule.Draw(const CameraMatrix:TKraftMatrix4x4);
19708 const lats=16;
19709 longs=16;
19710 pi2=pi*2.0;
19711 var ModelViewMatrix:TKraftMatrix4x4;
19712 i,j:longint;
19713 HalfHeight,lat0,y0,yr0,lat1,y1,yr1,lng,x,z,yo0,yo1:TKraftScalar;
19714 begin
19715 glPushMatrix;
19716 glMatrixMode(GL_MODELVIEW);
19717 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
19718 {$ifdef UseDouble}
19719 glLoadMatrixd(pointer(@ModelViewMatrix));
19720 {$else}
19721 glLoadMatrixf(pointer(@ModelViewMatrix));
19722 {$endif}
19723
19724 if fDrawDisplayList=0 then begin
19725 fDrawDisplayList:=glGenLists(1);
19726 glNewList(fDrawDisplayList,GL_COMPILE);
19727
19728 HalfHeight:=fHeight*0.5;
19729
19730 for i:=0 to lats do begin
19731 lat0:=pi*(((i-1)/lats)-0.5);
19732 y0:=sin(lat0);
19733 yr0:=cos(lat0);
19734 lat1:=pi*((i/lats)-0.5);
19735 y1:=sin(lat1);
19736 yr1:=cos(lat1);
19737 if y0<0.0 then begin
19738 yo0:=-HalfHeight;
19739 end else begin
19740 yo0:=HalfHeight;
19741 end;
19742 if y1<0.0 then begin
19743 yo1:=-HalfHeight;
19744 end else begin
19745 yo1:=HalfHeight;
19746 end;
19747 glBegin(GL_QUAD_STRIP);
19748 for j:=0 to longs do begin
19749 lng:=pi2*((j-1)/longs);
19750 x:=cos(lng);
19751 z:=sin(lng);
19752 glNormal3f(x*yr0,y0,(z*yr0));
19753 glVertex3f(x*yr0*fRadius,yo0+(y0*fRadius),z*yr0*fRadius);
19754 glNormal3f(x*yr1,y1,(z*yr1));
19755 glVertex3f(x*yr1*fRadius,yo1+(y1*fRadius),z*yr1*fRadius);
19756 end;
19757 glEnd;
19758 end;
19759
19760 glEndList;
19761 end;
19762
19763 if fDrawDisplayList<>0 then begin
19764 glCallList(fDrawDisplayList);
19765 end;
19766
19767 glPopMatrix;
19768 end;
19769 {$endif}
19770
19771 constructor TKraftShapeConvexHull.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AConvexHull:TKraftConvexHull);
19772 begin
19773
19774 fConvexHull:=AConvexHull;
19775
19776 inherited Create(APhysics,ARigidBody);
19777
19778 fShapeType:=kstConvexHull;
19779
19780 fFeatureRadius:=0.0;
19781
19782 //fLocalCentroid:=fConvexHull.fMassData.Center;
19783 fLocalCentroid:=fConvexHull.fCentroid;
19784
19785 fLocalCenterOfMass:=fConvexHull.fMassData.Center;
19786
19787 fAngularMotionDisc:=fConvexHull.fAngularMotionDisc;
19788
19789 end;
19790
19791 destructor TKraftShapeConvexHull.Destroy;
19792 begin
19793 inherited Destroy;
19794 end;
19795
19796 procedure TKraftShapeConvexHull.UpdateShapeAABB;
19797 begin
19798 fShapeAABB:=fConvexHull.fAABB;
19799 end;
19800
19801 procedure TKraftShapeConvexHull.CalculateMassData;
19802 begin
19803 fMassData:=fConvexHull.fMassData;
19804 fMassData.Mass:=fMassData.Mass*fDensity;
19805 fMassData.Inertia[0,0]:=fMassData.Inertia[0,0]*fDensity;
19806 fMassData.Inertia[0,1]:=fMassData.Inertia[0,1]*fDensity;
19807 fMassData.Inertia[0,2]:=fMassData.Inertia[0,2]*fDensity;
19808 fMassData.Inertia[1,0]:=fMassData.Inertia[1,0]*fDensity;
19809 fMassData.Inertia[1,1]:=fMassData.Inertia[1,1]*fDensity;
19810 fMassData.Inertia[1,2]:=fMassData.Inertia[1,2]*fDensity;
19811 fMassData.Inertia[2,0]:=fMassData.Inertia[2,0]*fDensity;
19812 fMassData.Inertia[2,1]:=fMassData.Inertia[2,1]*fDensity;
19813 fMassData.Inertia[2,2]:=fMassData.Inertia[2,2]*fDensity;
19814 end;
19815
19816 function TKraftShapeConvexHull.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
19817 begin
19818 result:=fConvexHull.GetSignedDistance(Vector3TermMatrixMulInverted(Position,fWorldTransform));
19819 end;
19820
19821 function TKraftShapeConvexHull.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
19822 begin
19823 result:=fConvexHull.GetLocalFullSupport(Vector3SafeNorm(Direction));
19824 end;
19825
19826 function TKraftShapeConvexHull.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
19827 begin
19828 result:=fConvexHull.GetLocalFeatureSupportVertex(Index);
19829 end;
19830
19831 function TKraftShapeConvexHull.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
19832 begin
19833 result:=fConvexHull.GetLocalFeatureSupportIndex(Direction);
19834 end;
19835
19836 function TKraftShapeConvexHull.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
19837 begin
19838 result:=Vector3TermMatrixMul(fLocalCentroid,Transform);
19839 end;
19840
19841 function TKraftShapeConvexHull.TestPoint(const p:TKraftVector3):boolean;
19842 var i:longint;
19843 begin
19844 result:=true;
19845 for i:=0 to fConvexHull.fCountFaces-1 do begin
19846 if PlaneVectorDistance(fConvexHull.fFaces[i].Plane,p)>0.0 then begin
19847 result:=false;
19848 exit;
19849 end;
19850 end;
19851 end;
19852
19853 function TKraftShapeConvexHull.RayCast(var RayCastData:TKraftRaycastData):boolean;
19854 var FaceIndex,BestFaceIndex:longint;
19855 Face:PKraftConvexHullFace;
19856 TimeFirst,TimeLast,Numerator,Denominator,Time:TKraftScalar;
19857 Origin,Direction:TKraftVector3;
19858 begin
19859 result:=false;
19860 if ksfRayCastable in fFlags then begin
19861 Origin:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
19862 Direction:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform));
19863 if Vector3LengthSquared(Direction)>EPSILON then begin
19864 BestFaceIndex:=-1;
19865 TimeFirst:=0.0;
19866 TimeLast:=RayCastData.MaxTime+EPSILON;
19867 for FaceIndex:=0 to fConvexHull.fCountFaces-1 do begin
19868 Face:[email protected][FaceIndex];
19869 Numerator:=-PlaneVectorDistance(Face^.Plane,Origin);
19870 Denominator:=Vector3Dot(Face^.Plane.Normal,Direction);
19871 if abs(Denominator)<EPSILON then begin
19872 if Numerator<0.0 then begin
19873 exit;
19874 end;
19875 end else begin
19876 Time:=Numerator/Denominator;
19877 if Denominator<0.0 then begin
19878 if TimeFirst<Time then begin
19879 TimeFirst:=Time;
19880 BestFaceIndex:=FaceIndex;
19881 end;
19882 end else begin
19883 if TimeLast>Time then begin
19884 TimeLast:=Time;
19885 end;
19886 end;
19887 if TimeFirst>TimeLast then begin
19888 exit;
19889 end;
19890 end;
19891 end;
19892 if (BestFaceIndex>=0) and (TimeFirst<=TimeLast) and (TimeFirst<=RayCastData.MaxTime) then begin
19893 RayCastData.TimeOfImpact:=TimeFirst;
19894 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,TimeFirst)),fWorldTransform);
19895 RayCastData.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(fConvexHull.fFaces[BestFaceIndex].Plane.Normal,fWorldTransform));
19896 result:=true;
19897 end;
19898 end;
19899 end;
19900 end;
19901
19902 {$ifdef DebugDraw}
19903 procedure TKraftShapeConvexHull.Draw(const CameraMatrix:TKraftMatrix4x4);
19904 var i,j:longint;
19905 ModelViewMatrix:TKraftMatrix4x4;
19906 Face:PKraftConvexHullFace;
19907 begin
19908 glPushMatrix;
19909 glMatrixMode(GL_MODELVIEW);
19910 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
19911 {$ifdef UseDouble}
19912 glLoadMatrixd(pointer(@ModelViewMatrix));
19913 {$else}
19914 glLoadMatrixf(pointer(@ModelViewMatrix));
19915 {$endif}
19916
19917 if fDrawDisplayList=0 then begin
19918 fDrawDisplayList:=glGenLists(1);
19919 glNewList(fDrawDisplayList,GL_COMPILE);
19920
19921 {$ifdef UseConvexHullTriangleDebugDraw}
19922 glBegin(GL_TRIANGLES);
19923 for i:=0 to fConvexHull.CountFaces-1 do begin
19924 Face:[email protected][i];
19925 {$ifdef UseDouble}
19926 glNormal3dv(@Face^.Plane.Normal);
19927 for j:=1 to Face^.CountVertices-2 do begin
19928 glVertex3dv(@fConvexHull.fVertices[Face^.Vertices[0]].Position);
19929 glVertex3dv(@fConvexHull.fVertices[Face^.Vertices[j]].Position);
19930 glVertex3dv(@fConvexHull.fVertices[Face^.Vertices[j+1]].Position);
19931 end;
19932 {$else}
19933 glNormal3fv(@Face^.Plane.Normal);
19934 for j:=1 to Face^.CountVertices-2 do begin
19935 glVertex3fv(@fConvexHull.fVertices[Face^.Vertices[0]].Position);
19936 glVertex3fv(@fConvexHull.fVertices[Face^.Vertices[j]].Position);
19937 glVertex3fv(@fConvexHull.fVertices[Face^.Vertices[j+1]].Position);
19938 end;
19939 {$endif}
19940 end;
19941 glEnd;
19942 {$else}
19943 for i:=0 to fConvexHull.fCountFaces-1 do begin
19944 Face:[email protected][i];
19945 glBegin(GL_POLYGON);
19946 glNormal3fv(@Face^.Plane.Normal);
19947 for j:=0 to Face^.CountVertices-1 do begin
19948 glVertex3fv(@fConvexHull.fVertices[Face^.Vertices[j]].Position);
19949 end;
19950 glEnd;
19951 end;
19952 {$endif}
19953
19954 glEndList;
19955 end;
19956
19957 if fDrawDisplayList<>0 then begin
19958 glCallList(fDrawDisplayList);
19959 end;
19960
19961 glPopMatrix;
19962 end;
19963 {$endif}
19964
19965 constructor TKraftShapeBox.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AExtents:TKraftVector3);
19966 var i:longint;
19967 BoxPoints:array[0..7] of TKraftVector3;
19968 begin
19969 fExtents:=AExtents;
19970 for i:=0 to length(BoxPoints)-1 do begin
19971 if (i and 1)<>0 then begin
19972 BoxPoints[i].x:=fExtents.x;
19973 end else begin
19974 BoxPoints[i].x:=-fExtents.x;
19975 end;
19976 if (i and 2)<>0 then begin
19977 BoxPoints[i].y:=fExtents.y;
19978 end else begin
19979 BoxPoints[i].y:=-fExtents.y;
19980 end;
19981 if (i and 4)<>0 then begin
19982 BoxPoints[i].z:=fExtents.z;
19983 end else begin
19984 BoxPoints[i].z:=-fExtents.z;
19985 end;
19986 end;
19987 fShapeConvexHull:=TKraftConvexHull.Create(APhysics);
19988 fShapeConvexHull.Load(pointer(@BoxPoints[0]),length(BoxPoints));
19989 fShapeConvexHull.Build;
19990 fShapeConvexHull.Finish;
19991 fAngularMotionDisc:=fShapeConvexHull.fAngularMotionDisc;
19992 inherited Create(APhysics,ARigidBody,fShapeConvexHull);
19993 fShapeType:=kstBox;
19994 fFeatureRadius:=0.0;
19995 end;
19996
19997 destructor TKraftShapeBox.Destroy;
19998 begin
19999 fShapeConvexHull.Free;
20000 inherited Destroy;
20001 end;
20002
20003 procedure TKraftShapeBox.UpdateShapeAABB;
20004 begin
20005 fShapeAABB.Min.x:=-fExtents.x;
20006 fShapeAABB.Min.y:=-fExtents.y;
20007 fShapeAABB.Min.z:=-fExtents.z;
20008 fShapeAABB.Max.x:=fExtents.x;
20009 fShapeAABB.Max.y:=fExtents.y;
20010 fShapeAABB.Max.z:=fExtents.z;
20011 end;
20012
20013 procedure TKraftShapeBox.CalculateMassData;
20014 begin
20015 fMassData.Volume:=fExtents.x*fExtents.y*fExtents.z;
20016 fMassData.Mass:=fMassData.Volume*fDensity;
20017 fMassData.Inertia[0,0]:=((sqr(fExtents.y)+sqr(fExtents.z))*fMassData.Mass)/12.0;
20018 fMassData.Inertia[0,1]:=0.0;
20019 fMassData.Inertia[0,2]:=0.0;
20020 fMassData.Inertia[1,0]:=0.0;
20021 fMassData.Inertia[1,1]:=((sqr(fExtents.x)+sqr(fExtents.z))*fMassData.Mass)/12.0;
20022 fMassData.Inertia[1,2]:=0.0;
20023 fMassData.Inertia[2,0]:=0.0;
20024 fMassData.Inertia[2,1]:=0.0;
20025 fMassData.Inertia[2,2]:=((sqr(fExtents.x)+sqr(fExtents.y))*fMassData.Mass)/12.0;
20026 fMassData.Center.x:=fLocalTransform[3,0];
20027 fMassData.Center.y:=fLocalTransform[3,1];
20028 fMassData.Center.z:=fLocalTransform[3,2];
20029 fMassData.Inertia:=Matrix3x3TermAdd(InertiaTensorTransform(fMassData.Inertia,Matrix3x3(fLocalTransform)),
20030 InertiaTensorParallelAxisTheorem(fMassData.Center,fMassData.Mass));
20031 end;
20032
20033 function TKraftShapeBox.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
20034 var ClosestBoxPoint,Temp,Direction:TKraftVector3;
20035 Overlap:longint;
20036 begin
20037 result:=0;
20038 ClosestBoxPoint:=Vector3TermMatrixMulInverted(Position,fWorldTransform);
20039 if ClosestBoxPoint.x<-Extents.x then begin
20040 result:=result+sqr(ClosestBoxPoint.x-(-Extents.x));
20041 ClosestBoxPoint.x:=-Extents.x;
20042 Overlap:=0;
20043 end else if ClosestBoxPoint.x>Extents.x then begin
20044 result:=result+sqr(ClosestBoxPoint.x-Extents.x);
20045 ClosestBoxPoint.x:=Extents.x;
20046 Overlap:=0;
20047 end else begin
20048 Overlap:=1;
20049 end;
20050 if ClosestBoxPoint.y<-Extents.y then begin
20051 result:=result+sqr(ClosestBoxPoint.y-(-Extents.y));
20052 ClosestBoxPoint.y:=-Extents.y;
20053 end else if ClosestBoxPoint.y>Extents.y then begin
20054 result:=result+sqr(ClosestBoxPoint.y-Extents.y);
20055 ClosestBoxPoint.y:=Extents.y;
20056 end else begin
20057 Overlap:=Overlap or 2;
20058 end;
20059 if ClosestBoxPoint.z<-Extents.z then begin
20060 result:=result+sqr(ClosestBoxPoint.z-(-Extents.z));
20061 ClosestBoxPoint.z:=-Extents.z;
20062 end else if ClosestBoxPoint.z>Extents.z then begin
20063 result:=result+sqr(ClosestBoxPoint.z-Extents.z);
20064 ClosestBoxPoint.z:=Extents.z;
20065 end else begin
20066 Overlap:=Overlap or 3;
20067 end;
20068 if Overlap<>7 then begin
20069 result:=sqrt(result);
20070 end else begin
20071 Temp:=ClosestBoxPoint;
20072 Direction.x:=ClosestBoxPoint.x/Extents.x;
20073 Direction.y:=ClosestBoxPoint.y/Extents.y;
20074 Direction.z:=ClosestBoxPoint.z/Extents.z;
20075 if (abs(Direction.x)>abs(Direction.y)) and (abs(Direction.x)>abs(Direction.z)) then begin
20076 if Direction.x<0.0 then begin
20077 ClosestBoxPoint.x:=-Extents.x;
20078 end else begin
20079 ClosestBoxPoint.x:=Extents.x;
20080 end;
20081 end else if (abs(Direction.y)>abs(Direction.x)) and (abs(Direction.y)>abs(Direction.z)) then begin
20082 if Direction.y<0.0 then begin
20083 ClosestBoxPoint.y:=-Extents.y;
20084 end else begin
20085 ClosestBoxPoint.y:=Extents.y;
20086 end;
20087 end else begin
20088 if Direction.z<0.0 then begin
20089 ClosestBoxPoint.z:=-Extents.z;
20090 end else begin
20091 ClosestBoxPoint.z:=Extents.z;
20092 end;
20093 end;
20094 result:=-Vector3Dist(ClosestBoxPoint,Temp);
20095 end;
20096 end;
20097
20098 function TKraftShapeBox.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
20099 var Normal:TKraftVector3;
20100 begin
20101 Normal:=Direction;
20102 {$ifdef cpuarm}
20103 if Normal.x<0.0 then begin
20104 result.x:=-fExtents.x;
20105 end else begin
20106 result.x:=fExtents.x;
20107 end;
20108 if Normal.y<0.0 then begin
20109 result.y:=-fExtents.y;
20110 end else begin
20111 result.y:=fExtents.y;
20112 end;
20113 if Normal.z<0.0 then begin
20114 result.z:=-fExtents.z;
20115 end else begin
20116 result.z:=fExtents.z;
20117 end;
20118 {$else}
20119 result.x:=fExtents.x*(1-longint(longword(longword(pointer(@Normal.x)^) shr 31) shl 1));
20120 result.y:=fExtents.y*(1-longint(longword(longword(pointer(@Normal.y)^) shr 31) shl 1));
20121 result.z:=fExtents.z*(1-longint(longword(longword(pointer(@Normal.z)^) shr 31) shl 1));
20122 {$endif}
20123 end;
20124
20125 function TKraftShapeBox.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
20126 begin
20127 result:=inherited GetLocalFeatureSupportVertex(Index);
20128 end;
20129
20130 function TKraftShapeBox.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
20131 begin
20132 result:=inherited GetLocalFeatureSupportIndex(Direction);
20133 end;
20134
20135 function TKraftShapeBox.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
20136 begin
20137 result:=PKraftVector3(pointer(@Transform[3,0]))^;
20138 end;
20139
20140 function TKraftShapeBox.TestPoint(const p:TKraftVector3):boolean;
20141 var v:TKraftVector3;
20142 begin
20143 v:=Vector3TermMatrixMulInverted(p,fWorldTransform);
20144 result:=((v.x>=(-fExtents.x)) and (v.x<=fExtents.x)) and
20145 ((v.y>=(-fExtents.y)) and (v.x<=fExtents.y)) and
20146 ((v.z>=(-fExtents.z)) and (v.x<=fExtents.z));
20147 end;
20148
20149 function TKraftShapeBox.RayCast(var RayCastData:TKraftRaycastData):boolean;
20150 var s,v,h:TKraftVector3;
20151 lo,hi,k,Alpha:TKraftScalar;
20152 nlo,nhi,n:longint;
20153 sign:array[0..2] of TKraftScalar;
20154 begin
20155 result:=false;
20156 if ksfRayCastable in fFlags then begin
20157 s:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
20158 v:=Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform);
20159 if v.x<0 then begin
20160 s.x:=-s.x;
20161 v.x:=-v.x;
20162 sign[0]:=1;
20163 end else begin
20164 sign[0]:=-1;
20165 end;
20166 if v.y<0 then begin
20167 s.y:=-s.y;
20168 v.y:=-v.y;
20169 sign[1]:=1;
20170 end else begin
20171 sign[1]:=-1;
20172 end;
20173 if v.z<0 then begin
20174 s.z:=-s.z;
20175 v.z:=-v.z;
20176 sign[2]:=1;
20177 end else begin
20178 sign[2]:=-1;
20179 end;
20180 h:=fExtents;
20181 if (((s.x<-h.x) and (v.x<=0)) or (s.x>h.x)) or
20182 (((s.y<-h.y) and (v.y<=0)) or (s.y>h.y)) or
20183 (((s.z<-h.z) and (v.z<=0)) or (s.z>h.z)) then begin
20184 exit;
20185 end;
20186 lo:=-INFINITY;
20187 hi:=INFINITY;
20188 nlo:=0;
20189 nhi:=0;
20190 if v.x<>0.0 then begin
20191 k:=((-h.x)-s.x)/v.x;
20192 if k>lo then begin
20193 lo:=k;
20194 nlo:=0;
20195 end;
20196 k:=(h.x-s.x)/v.x;
20197 if k<hi then begin
20198 hi:=k;
20199 nhi:=0;
20200 end;
20201 end;
20202 if v.y<>0.0 then begin
20203 k:=((-h.y)-s.y)/v.y;
20204 if k>lo then begin
20205 lo:=k;
20206 nlo:=1;
20207 end;
20208 k:=(h.y-s.y)/v.y;
20209 if k<hi then begin
20210 hi:=k;
20211 nhi:=1;
20212 end;
20213 end;
20214 if v.z<>0.0 then begin
20215 k:=((-h.z)-s.z)/v.z;
20216 if k>lo then begin
20217 lo:=k;
20218 nlo:=2;
20219 end;
20220 k:=(h.z-s.z)/v.z;
20221 if k<hi then begin
20222 hi:=k;
20223 nhi:=2;
20224 end;
20225 end;
20226 if lo>hi then begin
20227 exit;
20228 end;
20229 if lo>=0 then begin
20230 Alpha:=lo;
20231 n:=nlo;
20232 end else begin
20233 Alpha:=hi;
20234 n:=nhi;
20235 end;
20236 if (Alpha<0) or (Alpha>RayCastData.MaxTime) then begin
20237 exit;
20238 end;
20239 RayCastData.TimeOfImpact:=Alpha;
20240 RayCastData.Point:=Vector3Add(RayCastData.Origin,Vector3ScalarMul(RayCastData.Direction,Alpha));
20241 RayCastData.Normal:=Vector3ScalarMul(Vector3(fWorldTransform[n,0],fWorldTransform[n,1],fWorldTransform[n,2]),sign[n]);
20242 result:=true;
20243 end;
20244 end;
20245
20246 {$ifdef DebugDraw}
20247 procedure TKraftShapeBox.Draw(const CameraMatrix:TKraftMatrix4x4);
20248 var ModelViewMatrix:TKraftMatrix4x4;
20249 begin
20250 glPushMatrix;
20251 glMatrixMode(GL_MODELVIEW);
20252 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
20253 {$ifdef UseDouble}
20254 glLoadMatrixd(pointer(@ModelViewMatrix));
20255 {$else}
20256 glLoadMatrixf(pointer(@ModelViewMatrix));
20257 {$endif}
20258
20259 if fDrawDisplayList=0 then begin
20260 fDrawDisplayList:=glGenLists(1);
20261 glNewList(fDrawDisplayList,GL_COMPILE);
20262
20263 glBegin(GL_TRIANGLE_STRIP);
20264 glNormal3f(-1.0,0.0,0.0);
20265 glVertex3f(-fExtents.x,-fExtents.y,-fExtents.z);
20266 glVertex3f(-fExtents.x,-fExtents.y,fExtents.z);
20267 glVertex3f(-fExtents.x,fExtents.y,-fExtents.z);
20268 glVertex3f(-fExtents.x,fExtents.y,fExtents.z);
20269 glNormal3f(0.0,1.0,0.0);
20270 glVertex3f(fExtents.x,fExtents.y,-fExtents.z);
20271 glVertex3f(fExtents.x,fExtents.y,fExtents.z);
20272 glNormal3f(1.0,0.0,0.0);
20273 glVertex3f(fExtents.x,-fExtents.y,-fExtents.z);
20274 glVertex3f(fExtents.x,-fExtents.y,fExtents.z);
20275 glNormal3f(0.0,-1.0,0.0);
20276 glVertex3f(-fExtents.x,-fExtents.y,-fExtents.z);
20277 glVertex3f(-fExtents.x,-fExtents.y,fExtents.z);
20278 glEnd;
20279 glBegin(GL_TRIANGLE_FAN);
20280 glNormal3f(0.0,0.0,1.0);
20281 glVertex3f(-fExtents.x,-fExtents.y,fExtents.z);
20282 glVertex3f(fExtents.x,-fExtents.y,fExtents.z);
20283 glVertex3f(fExtents.x,fExtents.y,fExtents.z);
20284 glVertex3f(-fExtents.x,fExtents.y,fExtents.z);
20285 glEnd;
20286 glBegin(GL_TRIANGLE_FAN);
20287 glNormal3f(0.0,0.0,-1.0);
20288 glVertex3f(-fExtents.x,-fExtents.y,-fExtents.z);
20289 glVertex3f(-fExtents.x,fExtents.y,-fExtents.z);
20290 glVertex3f(fExtents.x,fExtents.y,-fExtents.z);
20291 glVertex3f(fExtents.x,-fExtents.y,-fExtents.z);
20292 glEnd;
20293
20294 glEndList;
20295 end;
20296
20297 if fDrawDisplayList<>0 then begin
20298 glCallList(fDrawDisplayList);
20299 end;
20300
20301 glPopMatrix;
20302 end;
20303 {$endif}
20304
20305 const PlaneSize=32768.0;
20306
20307 constructor TKraftShapePlane.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const APlane:TKraftPlane);
20308 var HullPlaneVertices:array[0..7] of TKraftVector3;
20309 b,p,q:TKraftVector3;
20310 begin
20311 fStaticAABBTreeProxy:=-1;
20312 fSleepingAABBTreeProxy:=-1;
20313 fDynamicAABBTreeProxy:=-1;
20314 fKinematicAABBTreeProxy:=-1;
20315 fPlane:=APlane;
20316 GetPlaneSpace(fPlane.Normal,p,q);
20317 fPlaneCenter:=Vector3ScalarMul(fPlane.Normal,fPlane.Distance-(PlaneSize*0.5));
20318 b:=Vector3ScalarMul(fPlane.Normal,fPlane.Distance);
20319 fPlaneVertices[0]:=Vector3Add(b,Vector3Add(Vector3ScalarMul(p,PlaneSize),Vector3ScalarMul(q,PlaneSize)));
20320 fPlaneVertices[1]:=Vector3Add(b,Vector3Add(Vector3ScalarMul(p,PlaneSize),Vector3ScalarMul(q,-PlaneSize)));
20321 fPlaneVertices[2]:=Vector3Add(b,Vector3Add(Vector3ScalarMul(p,-PlaneSize),Vector3ScalarMul(q,-PlaneSize)));
20322 fPlaneVertices[3]:=Vector3Add(b,Vector3Add(Vector3ScalarMul(p,-PlaneSize),Vector3ScalarMul(q,PlaneSize)));
20323 b:=Vector3ScalarMul(fPlane.Normal,PlaneSize);
20324 HullPlaneVertices[0]:=fPlaneVertices[0];
20325 HullPlaneVertices[1]:=fPlaneVertices[1];
20326 HullPlaneVertices[2]:=fPlaneVertices[2];
20327 HullPlaneVertices[3]:=fPlaneVertices[3];
20328 HullPlaneVertices[4]:=Vector3Sub(fPlaneVertices[0],b);
20329 HullPlaneVertices[5]:=Vector3Sub(fPlaneVertices[1],b);
20330 HullPlaneVertices[6]:=Vector3Sub(fPlaneVertices[2],b);
20331 HullPlaneVertices[7]:=Vector3Sub(fPlaneVertices[3],b);
20332 //PlaneCenter:=Vector3Avg(@HullPlaneVertices[0],length(HullPlaneVertices));
20333 fShapeConvexHull:=TKraftConvexHull.Create(APhysics);
20334 fShapeConvexHull.Load(pointer(@HullPlaneVertices[0]),length(HullPlaneVertices));
20335 fShapeConvexHull.Build;
20336 fShapeConvexHull.Finish;
20337 fAngularMotionDisc:=fShapeConvexHull.fAngularMotionDisc;
20338 inherited Create(APhysics,ARigidBody,fShapeConvexHull);
20339 fShapeType:=kstPlane;
20340 fFeatureRadius:=0.0;
20341 end;
20342
20343 destructor TKraftShapePlane.Destroy;
20344 begin
20345 fShapeConvexHull.Free;
20346 inherited Destroy;
20347 end;
20348
20349 procedure TKraftShapePlane.UpdateShapeAABB;
20350 var b:TKraftVector3;
20351 begin
20352 b:=Vector3ScalarMul(fPlane.Normal,fPlane.Distance-PlaneSize);
20353 fShapeAABB.Min.x:=Min(Min(Min(Min(fPlaneVertices[0].x,fPlaneVertices[1].x),fPlaneVertices[2].x),fPlaneVertices[3].x),b.x)-0.1;
20354 fShapeAABB.Min.y:=Min(Min(Min(Min(fPlaneVertices[0].y,fPlaneVertices[1].y),fPlaneVertices[2].y),fPlaneVertices[3].y),b.y)-0.1;
20355 fShapeAABB.Min.z:=Min(Min(Min(Min(fPlaneVertices[0].z,fPlaneVertices[1].z),fPlaneVertices[2].z),fPlaneVertices[3].z),b.z)-0.1;
20356 fShapeAABB.Max.x:=Max(Max(Max(Max(fPlaneVertices[0].x,fPlaneVertices[1].x),fPlaneVertices[2].x),fPlaneVertices[3].x),b.x)+0.1;
20357 fShapeAABB.Max.y:=Max(Max(Max(Max(fPlaneVertices[0].y,fPlaneVertices[1].y),fPlaneVertices[2].y),fPlaneVertices[3].y),b.y)+0.1;
20358 fShapeAABB.Max.z:=Max(Max(Max(Max(fPlaneVertices[0].z,fPlaneVertices[1].z),fPlaneVertices[2].z),fPlaneVertices[3].z),b.z)+0.1;
20359 end;
20360
20361 procedure TKraftShapePlane.CalculateMassData;
20362 begin
20363 end;
20364
20365 function TKraftShapePlane.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
20366 begin
20367 result:=Vector3Dot(Plane.Normal,Vector3TermMatrixMulInverted(Position,fWorldTransform))+Plane.Distance;
20368 end;
20369
20370 function TKraftShapePlane.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
20371 var Index,BestIndex:longint;
20372 BestDistance,NewDistance:TKraftScalar;
20373 Normal:TKraftVector3;
20374 begin
20375 Normal:=Vector3SafeNorm(Direction);
20376 BestDistance:=Vector3Dot(Normal,fPlaneVertices[0]);
20377 BestIndex:=0;
20378 for Index:=1 to 3 do begin
20379 NewDistance:=Vector3Dot(Normal,fPlaneVertices[Index]);
20380 if BestDistance<NewDistance then begin
20381 BestDistance:=NewDistance;
20382 BestIndex:=Index;
20383 end;
20384 end;
20385 result:=fPlaneVertices[BestIndex];
20386 if Vector3Dot(fPlane.Normal,Normal)<0.0 then begin
20387 result:=Vector3Sub(result,Vector3ScalarMul(fPlane.Normal,PlaneSize));
20388 end;
20389 end;
20390
20391 function TKraftShapePlane.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
20392 begin
20393 if (Index>=0) and (Index<4) then begin
20394 result:=fPlaneVertices[Index];
20395 end else begin
20396 result:=Vector3Origin;
20397 end;
20398 end;
20399
20400 function TKraftShapePlane.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
20401 var Index:longint;
20402 BestDistance,NewDistance:TKraftScalar;
20403 Normal:TKraftVector3;
20404 begin
20405 result:=0;
20406 Normal:=Vector3SafeNorm(Direction);
20407 BestDistance:=Vector3Dot(Normal,fPlaneVertices[0]);
20408 for Index:=1 to 3 do begin
20409 NewDistance:=Vector3Dot(Normal,fPlaneVertices[Index]);
20410 if BestDistance<NewDistance then begin
20411 BestDistance:=NewDistance;
20412 result:=Index;
20413 end;
20414 end;
20415 end;
20416
20417 function TKraftShapePlane.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
20418 begin
20419 result:=Vector3TermMatrixMul(fPlaneCenter,Transform);
20420 end;
20421
20422 function TKraftShapePlane.TestPoint(const p:TKraftVector3):boolean;
20423 begin
20424 result:=false;
20425 end;
20426
20427 function TKraftShapePlane.RayCast(var RayCastData:TKraftRaycastData):boolean;
20428 var Origin,Direction:TKraftVector3;
20429 Time:TKraftScalar;
20430 begin
20431 result:=false;
20432 if ksfRayCastable in fFlags then begin
20433 Origin:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
20434 Direction:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform));
20435 if Vector3LengthSquared(Direction)>EPSILON then begin
20436 Time:=-Vector3Dot(fPlane.Normal,Direction);
20437 if abs(Time)>EPSILON then begin
20438 Time:=PlaneVectorDistance(fPlane,Origin)/Time;
20439 if Time>=0.0 then begin
20440 if Time<RayCastData.MaxTime then begin
20441 RayCastData.TimeOfImpact:=Time;
20442 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,Time)),fWorldTransform);
20443 RayCastData.Normal:=Vector3TermMatrixMulBasis(fPlane.Normal,fWorldTransform);
20444 result:=true;
20445 end;
20446 end;
20447 end;
20448 end;
20449 end;
20450 end;
20451
20452 {$ifdef DebugDraw}
20453 procedure TKraftShapePlane.Draw(const CameraMatrix:TKraftMatrix4x4);
20454 var ModelViewMatrix:TKraftMatrix4x4;
20455 n:TKraftVector3;
20456 begin
20457
20458 glPushMatrix;
20459 glMatrixMode(GL_MODELVIEW);
20460 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
20461 {$ifdef UseDouble}
20462 glLoadMatrixd(pointer(@ModelViewMatrix));
20463 {$else}
20464 glLoadMatrixf(pointer(@ModelViewMatrix));
20465 {$endif}
20466
20467 if fDrawDisplayList=0 then begin
20468 fDrawDisplayList:=glGenLists(1);
20469 glNewList(fDrawDisplayList,GL_COMPILE);
20470
20471 n:=Vector3NormEx(Vector3Cross(Vector3Sub(fPlaneVertices[1],fPlaneVertices[0]),Vector3Sub(fPlaneVertices[2],fPlaneVertices[0])));
20472
20473 {$ifdef UseDouble}
20474 glBegin(GL_TRIANGLES);
20475 glNormal3dv(@n);
20476 glVertex3dv(@fPlaneVertices[0]);
20477 glVertex3dv(@fPlaneVertices[1]);
20478 glVertex3dv(@fPlaneVertices[2]);
20479 glVertex3dv(@fPlaneVertices[2]);
20480 glVertex3dv(@fPlaneVertices[3]);
20481 glVertex3dv(@fPlaneVertices[0]);
20482 n:=Vector3Neg(n);
20483 glNormal3dv(@n);
20484 glVertex3dv(@fPlaneVertices[2]);
20485 glVertex3dv(@fPlaneVertices[1]);
20486 glVertex3dv(@fPlaneVertices[0]);
20487 glVertex3dv(@fPlaneVertices[0]);
20488 glVertex3dv(@fPlaneVertices[3]);
20489 glVertex3dv(@fPlaneVertices[2]);
20490 glEnd;
20491 {$else}
20492 glBegin(GL_TRIANGLES);
20493 glNormal3fv(@n);
20494 glVertex3fv(@fPlaneVertices[0]);
20495 glVertex3fv(@fPlaneVertices[1]);
20496 glVertex3fv(@fPlaneVertices[2]);
20497 glVertex3fv(@fPlaneVertices[2]);
20498 glVertex3fv(@fPlaneVertices[3]);
20499 glVertex3fv(@fPlaneVertices[0]);
20500 n:=Vector3Neg(n);
20501 glNormal3fv(@n);
20502 glVertex3fv(@fPlaneVertices[2]);
20503 glVertex3fv(@fPlaneVertices[1]);
20504 glVertex3fv(@fPlaneVertices[0]);
20505 glVertex3fv(@fPlaneVertices[0]);
20506 glVertex3fv(@fPlaneVertices[3]);
20507 glVertex3fv(@fPlaneVertices[2]);
20508 glEnd;
20509 {$endif}
20510
20511 glEndList;
20512 end;
20513
20514 if fDrawDisplayList<>0 then begin
20515 glCallList(fDrawDisplayList);
20516 end;
20517
20518 glPopMatrix;
20519 end;
20520 {$endif}
20521
20522 constructor TKraftShapeTriangle.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AVertex0,AVertex1,AVertex2:TKraftVector3);
20523 //var TriangleVertices:array[0..2] of TKraftVector3;
20524 var Vertices:PPKraftConvexHullVertices;
20525 begin
20526
20527 {TriangleVertices[0]:=AVertex0;
20528 TriangleVertices[1]:=AVertex1;
20529 TriangleVertices[2]:=AVertex2;
20530
20531 ShapeConvexHull:=TKraftConvexHull.Create(APhysics);
20532 ShapeConvexHull.Load(pointer(@TriangleVertices[0]),length(TriangleVertices));
20533 ShapeConvexHull.Build;
20534 ShapeConvexHull.Finish;{}
20535
20536 fShapeConvexHull:=TKraftConvexHull.Create(APhysics);
20537
20538 fShapeConvexHull.fCountVertices:=3;
20539 SetLength(fShapeConvexHull.fVertices,fShapeConvexHull.fCountVertices);
20540 fShapeConvexHull.fVertices[0].Position:=AVertex0;
20541 fShapeConvexHull.fVertices[0].CountAdjacencies:=2;
20542 SetLength(fShapeConvexHull.fVertices[0].Adjacencies,2);
20543 fShapeConvexHull.fVertices[0].Adjacencies[0]:=1;
20544 fShapeConvexHull.fVertices[0].Adjacencies[1]:=2;
20545 fShapeConvexHull.fVertices[1].Position:=AVertex1;
20546 fShapeConvexHull.fVertices[1].CountAdjacencies:=2;
20547 SetLength(fShapeConvexHull.fVertices[1].Adjacencies,2);
20548 fShapeConvexHull.fVertices[1].Adjacencies[0]:=2;
20549 fShapeConvexHull.fVertices[1].Adjacencies[1]:=0;
20550 fShapeConvexHull.fVertices[2].Position:=AVertex2;
20551 fShapeConvexHull.fVertices[2].CountAdjacencies:=2;
20552 SetLength(fShapeConvexHull.fVertices[2].Adjacencies,2);
20553 fShapeConvexHull.fVertices[2].Adjacencies[0]:=0;
20554 fShapeConvexHull.fVertices[2].Adjacencies[1]:=1;
20555
20556 Vertices:[email protected][0];
20557
20558 fShapeConvexHull.fCountFaces:=2;
20559 SetLength(fShapeConvexHull.fFaces,fShapeConvexHull.fCountFaces);
20560 fShapeConvexHull.fFaces[0].Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(Vertices^[1].Position,Vertices^[0].Position),Vector3Sub(Vertices^[2].Position,Vertices^[0].Position)));
20561 fShapeConvexHull.fFaces[0].Plane.Distance:=-Vector3Dot(fShapeConvexHull.fFaces[0].Plane.Normal,Vertices^[0].Position);
20562 fShapeConvexHull.fFaces[0].CountVertices:=3;
20563 SetLength(fShapeConvexHull.fFaces[0].Vertices,fShapeConvexHull.fFaces[0].CountVertices);
20564 fShapeConvexHull.fFaces[0].Vertices[0]:=0;
20565 fShapeConvexHull.fFaces[0].Vertices[1]:=1;
20566 fShapeConvexHull.fFaces[0].Vertices[2]:=2;
20567 fShapeConvexHull.fFaces[0].EdgeVertexOffset:=0;
20568 fShapeConvexHull.fFaces[1].Plane.Normal:=Vector3Neg(fShapeConvexHull.fFaces[0].Plane.Normal);
20569 fShapeConvexHull.fFaces[1].Plane.Distance:=-fShapeConvexHull.fFaces[0].Plane.Distance;
20570 fShapeConvexHull.fFaces[1].CountVertices:=3;
20571 SetLength(fShapeConvexHull.fFaces[1].Vertices,fShapeConvexHull.fFaces[1].CountVertices);
20572 fShapeConvexHull.fFaces[1].Vertices[0]:=0;
20573 fShapeConvexHull.fFaces[1].Vertices[1]:=2;
20574 fShapeConvexHull.fFaces[1].Vertices[2]:=1;
20575 fShapeConvexHull.fFaces[1].EdgeVertexOffset:=3;
20576
20577 fShapeConvexHull.fCountEdges:=3;
20578 SetLength(fShapeConvexHull.fEdges,fShapeConvexHull.fCountEdges);
20579 fShapeConvexHull.fEdges[0].Vertices[0]:=2;
20580 fShapeConvexHull.fEdges[0].Vertices[1]:=0;
20581 fShapeConvexHull.fEdges[0].Faces[0]:=0;
20582 fShapeConvexHull.fEdges[0].Faces[1]:=1;
20583 fShapeConvexHull.fEdges[1].Vertices[0]:=1;
20584 fShapeConvexHull.fEdges[1].Vertices[1]:=2;
20585 fShapeConvexHull.fEdges[1].Faces[0]:=0;
20586 fShapeConvexHull.fEdges[1].Faces[1]:=1;
20587 fShapeConvexHull.fEdges[2].Vertices[0]:=0;
20588 fShapeConvexHull.fEdges[2].Vertices[1]:=1;
20589 fShapeConvexHull.fEdges[2].Faces[0]:=0;
20590 fShapeConvexHull.fEdges[2].Faces[1]:=1;
20591
20592 fShapeAABB.Min.x:=Min(Min(Vertices^[0].Position.x,Vertices^[1].Position.x),Vertices^[2].Position.x)-0.1;
20593 fShapeAABB.Min.y:=Min(Min(Vertices^[0].Position.y,Vertices^[1].Position.y),Vertices^[2].Position.y)-0.1;
20594 fShapeAABB.Min.z:=Min(Min(Vertices^[0].Position.z,Vertices^[1].Position.z),Vertices^[2].Position.z)-0.1;
20595 fShapeAABB.Max.x:=Max(Max(Vertices^[0].Position.x,Vertices^[1].Position.x),Vertices^[2].Position.x)+0.1;
20596 fShapeAABB.Max.y:=Max(Max(Vertices^[0].Position.y,Vertices^[1].Position.y),Vertices^[2].Position.y)+0.1;
20597 fShapeAABB.Max.z:=Max(Max(Vertices^[0].Position.z,Vertices^[1].Position.z),Vertices^[2].Position.z)+0.1;
20598
20599 fShapeConvexHull.fAABB:=fShapeAABB;
20600
20601 //fShapeSphere.Center:=Vector3Add(Vertices^[0].Position,Vector3Add(Vector3ScalarMul(Vector3Sub(Vertices^[1].Position,Vertices^[0].Position),0.5),Vector3ScalarMul(Vector3Sub(Vertices^[2].Position,Vertices^[0].Position),0.5)));
20602 fShapeSphere.Center.x:=(Vertices^[0].Position.x+Vertices^[1].Position.x+Vertices^[2].Position.x)/3.0;
20603 fShapeSphere.Center.y:=(Vertices^[0].Position.y+Vertices^[1].Position.y+Vertices^[2].Position.y)/3.0;
20604 fShapeSphere.Center.z:=(Vertices^[0].Position.z+Vertices^[1].Position.z+Vertices^[2].Position.z)/3.0;{}
20605 fShapeSphere.Radius:=sqrt(Max(Max(Vector3DistSquared(fShapeSphere.Center,Vertices^[0].Position),
20606 Vector3DistSquared(fShapeSphere.Center,Vertices^[1].Position)),
20607 Vector3DistSquared(fShapeSphere.Center,Vertices^[2].Position)));
20608
20609 fShapeConvexHull.fAngularMotionDisc:=Vector3Length(fShapeSphere.Center)+fShapeSphere.Radius;
20610 fAngularMotionDisc:=fShapeConvexHull.fAngularMotionDisc;
20611
20612 inherited Create(APhysics,ARigidBody,fShapeConvexHull);
20613
20614 fShapeType:=kstTriangle;
20615
20616 fFeatureRadius:=0.0;
20617
20618 end;
20619
20620 destructor TKraftShapeTriangle.Destroy;
20621 begin
20622 fShapeConvexHull.Free;
20623 inherited Destroy;
20624 end;
20625
20626 procedure TKraftShapeTriangle.UpdateShapeAABB;
20627 var Vertices:PPKraftConvexHullVertices;
20628 begin
20629 Vertices:[email protected][0];
20630 fShapeAABB.Min.x:=Min(Min(Vertices^[0].Position.x,Vertices^[1].Position.x),Vertices^[2].Position.x)-0.1;
20631 fShapeAABB.Min.y:=Min(Min(Vertices^[0].Position.y,Vertices^[1].Position.y),Vertices^[2].Position.y)-0.1;
20632 fShapeAABB.Min.z:=Min(Min(Vertices^[0].Position.z,Vertices^[1].Position.z),Vertices^[2].Position.z)-0.1;
20633 fShapeAABB.Max.x:=Max(Max(Vertices^[0].Position.x,Vertices^[1].Position.x),Vertices^[2].Position.x)+0.1;
20634 fShapeAABB.Max.y:=Max(Max(Vertices^[0].Position.y,Vertices^[1].Position.y),Vertices^[2].Position.y)+0.1;
20635 fShapeAABB.Max.z:=Max(Max(Vertices^[0].Position.z,Vertices^[1].Position.z),Vertices^[2].Position.z)+0.1;
20636 end;
20637
20638 procedure TKraftShapeTriangle.CalculateMassData;
20639 begin
20640 end;
20641
20642 procedure TKraftShapeTriangle.UpdateData;
20643 const f1d3=1.0/3.0;
20644 var Vertices:PPKraftConvexHullVertices;
20645 begin
20646 Vertices:[email protected][0];
20647 //fShapeSphere.Center:=Vector3Add(Vertices^[0].Position,Vector3Add(Vector3ScalarMul(Vector3Sub(Vertices^[1].Position,Vertices^[0].Position),0.5),Vector3ScalarMul(Vector3Sub(Vertices^[2].Position,Vertices^[0].Position),0.5)));
20648 fShapeSphere.Center.x:=(Vertices^[0].Position.x+Vertices^[1].Position.x+Vertices^[2].Position.x)*f1d3;
20649 fShapeSphere.Center.y:=(Vertices^[0].Position.y+Vertices^[1].Position.y+Vertices^[2].Position.y)*f1d3;
20650 fShapeSphere.Center.z:=(Vertices^[0].Position.z+Vertices^[1].Position.z+Vertices^[2].Position.z)*f1d3;
20651 fShapeSphere.Radius:=sqrt(Max(Max(Vector3DistSquared(fShapeSphere.Center,Vertices^[0].Position),
20652 Vector3DistSquared(fShapeSphere.Center,Vertices^[1].Position)),
20653 Vector3DistSquared(fShapeSphere.Center,Vertices^[2].Position)));
20654 fShapeConvexHull.fFaces[0].Plane.Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(Vertices^[1].Position,Vertices^[0].Position),Vector3Sub(Vertices^[2].Position,Vertices^[0].Position)));
20655 fShapeConvexHull.fFaces[0].Plane.Distance:=-Vector3Dot(fShapeConvexHull.fFaces[0].Plane.Normal,Vertices^[0].Position);
20656 fShapeConvexHull.fFaces[1].Plane.Normal:=Vector3Neg(fShapeConvexHull.fFaces[0].Plane.Normal);
20657 fShapeConvexHull.fFaces[1].Plane.Distance:=-fShapeConvexHull.fFaces[0].Plane.Distance;
20658 fLocalCentroid:=fShapeSphere.Center;
20659 fLocalCenterOfMass:=fShapeSphere.Center;
20660 fAngularMotionDisc:=Vector3Length(fShapeSphere.Center)+fShapeSphere.Radius;
20661 fFeatureRadius:=0.0;
20662 end;
20663
20664 function TKraftShapeTriangle.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
20665 begin
20666 result:=sqrt(SquaredDistanceFromPointToTriangle(Vector3TermMatrixMulInverted(Position,fWorldTransform),
20667 fConvexHull.fVertices[0].Position,
20668 fConvexHull.fVertices[1].Position,
20669 fConvexHull.fVertices[2].Position))-(2.0*Physics.fLinearSlop);
20670 end;
20671
20672 function TKraftShapeTriangle.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
20673 var i:longint;
20674 Vertices:PPKraftConvexHullVertices;
20675 d0,d1,d2:TKraftScalar;
20676 Normal:TKraftVector3;
20677 begin
20678 Vertices:[email protected][0];
20679 Normal:=Vector3SafeNorm(Direction);
20680 d0:=Vector3Dot(Normal,Vertices^[0].Position);
20681 d1:=Vector3Dot(Normal,Vertices^[1].Position);
20682 d2:=Vector3Dot(Normal,Vertices^[2].Position);
20683 if d0>d1 then begin
20684 if d2>d0 then begin
20685 i:=2;
20686 end else begin
20687 i:=0;
20688 end;
20689 end else begin
20690 if d2>d1 then begin
20691 i:=2;
20692 end else begin
20693 i:=1;
20694 end;
20695 end;
20696 result:=Vertices^[i].Position;
20697 end;
20698
20699 function TKraftShapeTriangle.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
20700 begin
20701 if (Index>=0) and (Index<3) then begin
20702 result:=fConvexHull.fVertices[Index].Position;
20703 end else begin
20704 result:=Vector3Origin;
20705 end;
20706 end;
20707
20708 function TKraftShapeTriangle.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
20709 var Vertices:PPKraftConvexHullVertices;
20710 d0,d1,d2:TKraftScalar;
20711 Normal:TKraftVector3;
20712 begin
20713 Vertices:[email protected][0];
20714 Normal:=Vector3SafeNorm(Direction);
20715 d0:=Vector3Dot(Normal,Vertices^[0].Position);
20716 d1:=Vector3Dot(Normal,Vertices^[1].Position);
20717 d2:=Vector3Dot(Normal,Vertices^[2].Position);
20718 if d0>d1 then begin
20719 if d2>d0 then begin
20720 result:=2;
20721 end else begin
20722 result:=0;
20723 end;
20724 end else begin
20725 if d2>d1 then begin
20726 result:=2;
20727 end else begin
20728 result:=1;
20729 end;
20730 end;
20731 end;
20732
20733 function TKraftShapeTriangle.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
20734 begin
20735 result:=Vector3TermMatrixMul(fShapeSphere.Center,Transform);
20736 end;
20737
20738 function TKraftShapeTriangle.TestPoint(const p:TKraftVector3):boolean;
20739 begin
20740 result:=false;
20741 end;
20742
20743 function TKraftShapeTriangle.RayCast(var RayCastData:TKraftRaycastData):boolean;
20744 var Origin,Direction:TKraftVector3;
20745 Vertices:PPKraftConvexHullVertices;
20746 Time,u,v:TKraftScalar;
20747 begin
20748 result:=false;
20749 if ksfRayCastable in fFlags then begin
20750 Origin:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
20751 Direction:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform));
20752 if Vector3LengthSquared(Direction)>EPSILON then begin
20753 Vertices:[email protected][0];
20754 if RayIntersectTriangle(Origin,Direction,Vertices^[0].Position,Vertices^[1].Position,Vertices^[2].Position,Time,u,v) then begin
20755 if (Time>=0.0) and (Time<=RayCastData.MaxTime) then begin
20756 RayCastData.TimeOfImpact:=Time;
20757 RayCastData.Point:=Vector3TermMatrixMul(Vector3Add(Origin,Vector3ScalarMul(Direction,Time)),fWorldTransform);
20758 RayCastData.Normal:=Vector3TermMatrixMulBasis(Vector3NormEx(Vector3Cross(Vector3Sub(Vertices^[1].Position,Vertices^[0].Position),Vector3Sub(Vertices^[2].Position,Vertices^[0].Position))),fWorldTransform);
20759 result:=true;
20760 end;
20761 end;
20762 end;
20763 end;
20764 end;
20765
20766 {$ifdef DebugDraw}
20767 procedure TKraftShapeTriangle.Draw(const CameraMatrix:TKraftMatrix4x4);
20768 var ModelViewMatrix:TKraftMatrix4x4;
20769 Vertices:PPKraftConvexHullVertices;
20770 n:TKraftVector3;
20771 begin
20772
20773 glPushMatrix;
20774 glMatrixMode(GL_MODELVIEW);
20775 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
20776 {$ifdef UseDouble}
20777 glLoadMatrixd(pointer(@ModelViewMatrix));
20778 {$else}
20779 glLoadMatrixf(pointer(@ModelViewMatrix));
20780 {$endif}
20781
20782 if fDrawDisplayList=0 then begin
20783 Vertices:[email protected][0];
20784
20785 fDrawDisplayList:=glGenLists(1);
20786 glNewList(fDrawDisplayList,GL_COMPILE);
20787
20788 n:=Vector3NormEx(Vector3Cross(Vector3Sub(Vertices^[1].Position,Vertices^[0].Position),Vector3Sub(Vertices^[2].Position,Vertices^[0].Position)));
20789
20790 {$ifdef UseDouble}
20791 glBegin(GL_TRIANGLES);
20792 glNormal3dv(@n);
20793 glVertex3dv(@Vertices^[0].Position);
20794 glVertex3dv(@Vertices^[1].Position);
20795 glVertex3dv(@Vertices^[2].Position);
20796 n:=Vector3Neg(n);
20797 glNormal3dv(@n);
20798 glVertex3dv(@Vertices^[0].Position);
20799 glVertex3dv(@Vertices^[2].Position);
20800 glVertex3dv(@Vertices^[1].Position);
20801 glEnd;
20802 {$else}
20803 glBegin(GL_TRIANGLES);
20804 glNormal3fv(@n);
20805 glVertex3fv(@Vertices^[0].Position);
20806 glVertex3fv(@Vertices^[1].Position);
20807 glVertex3fv(@Vertices^[2].Position);
20808 n:=Vector3Neg(n);
20809 glNormal3fv(@n);
20810 glVertex3fv(@Vertices^[0].Position);
20811 glVertex3fv(@Vertices^[2].Position);
20812 glVertex3fv(@Vertices^[1].Position);
20813 glEnd;
20814 {$endif}
20815
20816 glEndList;
20817 end;
20818
20819 if fDrawDisplayList<>0 then begin
20820 glCallList(fDrawDisplayList);
20821 end;
20822
20823 glPopMatrix;
20824 end;
20825 {$endif}
20826
20827 constructor TKraftShapeMesh.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AMesh:TKraftMesh);
20828 begin
20829
20830 fMesh:=AMesh;
20831
20832 inherited Create(APhysics,ARigidBody);
20833
20834 fIsMesh:=true;
20835
20836 fShapeType:=kstMesh;
20837
20838 fFeatureRadius:=0.0;
20839
20840 end;
20841
20842 destructor TKraftShapeMesh.Destroy;
20843 begin
20844 inherited Destroy;
20845 end;
20846
20847 procedure TKraftShapeMesh.UpdateShapeAABB;
20848 begin
20849 fShapeAABB:=fMesh.fAABB;
20850 end;
20851
20852 procedure TKraftShapeMesh.CalculateMassData;
20853 begin
20854 end;
20855
20856 function TKraftShapeMesh.GetSignedDistance(const Position:TKraftVector3):TKraftScalar;
20857 begin
20858 result:=Mesh.GetSignedDistance(Vector3TermMatrixMulInverted(Position,fWorldTransform));
20859 end;
20860
20861 function TKraftShapeMesh.GetLocalFullSupport(const Direction:TKraftVector3):TKraftVector3;
20862 begin
20863 result:=Vector3Origin;
20864 end;
20865
20866 function TKraftShapeMesh.GetLocalFeatureSupportVertex(const Index:longint):TKraftVector3;
20867 begin
20868 result:=Vector3Origin;
20869 end;
20870
20871 function TKraftShapeMesh.GetLocalFeatureSupportIndex(const Direction:TKraftVector3):longint;
20872 begin
20873 result:=-1;
20874 end;
20875
20876 function TKraftShapeMesh.GetCenter(const Transform:TKraftMatrix4x4):TKraftVector3;
20877 begin
20878 result:=Vector3Origin;
20879 end;
20880
20881 function TKraftShapeMesh.TestPoint(const p:TKraftVector3):boolean;
20882 begin
20883 result:=false;
20884 end;
20885
20886 function TKraftShapeMesh.RayCast(var RayCastData:TKraftRaycastData):boolean;
20887 var SkipListNodeIndex,TriangleIndex:longint;
20888 SkipListNode:PKraftMeshSkipListNode;
20889 Triangle:PKraftMeshTriangle;
20890 First:boolean;
20891 Nearest,Time,u,v:TKraftScalar;
20892 Origin,Direction,p,Normal:TKraftVector3;
20893 begin
20894 result:=false;
20895 if ksfRayCastable in fFlags then begin
20896 Origin:=Vector3TermMatrixMulInverted(RayCastData.Origin,fWorldTransform);
20897 Direction:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(RayCastData.Direction,fWorldTransform));
20898 if Vector3LengthSquared(Direction)>EPSILON then begin
20899 Nearest:=MAX_SCALAR;
20900 First:=true;
20901 SkipListNodeIndex:=0;
20902 while SkipListNodeIndex<fMesh.fCountSkipListNodes do begin
20903 SkipListNode:[email protected][SkipListNodeIndex];
20904 if AABBRayIntersect(SkipListNode^.AABB,Origin,Direction) then begin
20905 TriangleIndex:=SkipListNode^.TriangleIndex;
20906 while TriangleIndex>=0 do begin
20907 Triangle:[email protected][TriangleIndex];
20908 if RayIntersectTriangle(Origin,
20909 Direction,
20910 fMesh.fVertices[Triangle^.Vertices[0]],
20911 fMesh.fVertices[Triangle^.Vertices[1]],
20912 fMesh.fVertices[Triangle^.Vertices[2]],
20913 Time,
20914 u,
20915 v) then begin
20916 p:=Vector3Add(Origin,Vector3ScalarMul(Direction,Time));
20917 if ((Time>=0.0) and (Time<=RayCastData.MaxTime)) and (First or (Time<Nearest)) then begin
20918 First:=false;
20919 Nearest:=Time;
20920 Normal:=Vector3Norm(Vector3Add(Vector3ScalarMul(fMesh.fNormals[Triangle^.Normals[0]],1.0-(u+v)),
20921 Vector3Add(Vector3ScalarMul(fMesh.fNormals[Triangle^.Normals[1]],u),
20922 Vector3ScalarMul(fMesh.fNormals[Triangle^.Normals[2]],v))));
20923 RayCastData.TimeOfImpact:=Time;
20924 RayCastData.Point:=p;
20925 RayCastData.Normal:=Normal;
20926 result:=true;
20927 end;
20928 end;
20929 TriangleIndex:=Triangle^.Next;
20930 end;
20931 inc(SkipListNodeIndex);
20932 end else begin
20933 SkipListNodeIndex:=SkipListNode^.SkipToNodeIndex;
20934 end;
20935 end;
20936 if result then begin
20937 RayCastData.Point:=Vector3TermMatrixMul(RayCastData.Point,fWorldTransform);
20938 RayCastData.Normal:=Vector3NormEx(Vector3TermMatrixMulBasis(RayCastData.Normal,fWorldTransform));
20939 end;
20940 end;
20941 end;
20942 end;
20943
20944 {$ifdef DebugDraw}
20945 procedure TKraftShapeMesh.Draw(const CameraMatrix:TKraftMatrix4x4);
20946 var i:longint;
20947 ModelViewMatrix:TKraftMatrix4x4;
20948 Triangle:PKraftMeshTriangle;
20949 begin
20950 glPushMatrix;
20951 glMatrixMode(GL_MODELVIEW);
20952 ModelViewMatrix:=Matrix4x4TermMul(fInterpolatedWorldTransform,CameraMatrix);
20953 {$ifdef UseDouble}
20954 glLoadMatrixd(pointer(@ModelViewMatrix));
20955 {$else}
20956 glLoadMatrixf(pointer(@ModelViewMatrix));
20957 {$endif}
20958
20959 if fDrawDisplayList=0 then begin
20960 fDrawDisplayList:=glGenLists(1);
20961 glNewList(fDrawDisplayList,GL_COMPILE);
20962
20963 glBegin(GL_TRIANGLES);
20964 for i:=0 to fMesh.fCountTriangles-1 do begin
20965 Triangle:[email protected][i];
20966 {$ifdef UseDouble}
20967 glNormal3dv(@fMesh.fNormals[Triangle^.Normals[0]]);
20968 glVertex3dv(@fMesh.fVertices[Triangle^.Vertices[0]]);
20969 glNormal3dv(@fMesh.fNormals[Triangle^.Normals[1]]);
20970 glVertex3dv(@fMesh.fVertices[Triangle^.Vertices[1]]);
20971 glNormal3dv(@fMesh.fNormals[Triangle^.Normals[2]]);
20972 glVertex3dv(@fMesh.fVertices[Triangle^.Vertices[2]]);
20973 {$else}
20974 glNormal3fv(@fMesh.fNormals[Triangle^.Normals[0]]);
20975 glVertex3fv(@fMesh.fVertices[Triangle^.Vertices[0]]);
20976 glNormal3fv(@fMesh.fNormals[Triangle^.Normals[1]]);
20977 glVertex3fv(@fMesh.fVertices[Triangle^.Vertices[1]]);
20978 glNormal3fv(@fMesh.fNormals[Triangle^.Normals[2]]);
20979 glVertex3fv(@fMesh.fVertices[Triangle^.Vertices[2]]);
20980 {$endif}
20981
20982 end;
20983 glEnd;
20984
20985 glEndList;
20986 end;
20987
20988 if fDrawDisplayList<>0 then begin
20989 glCallList(fDrawDisplayList);
20990 end;
20991
20992 glPopMatrix;
20993 end;
20994 {$endif}
20995
20996 procedure TKraftContactPair.GetSolverContactManifold(out SolverContactManifold:TKraftSolverContactManifold;const WorldTransformA,WorldTransformB:TKraftMatrix4x4;const ContactManifoldMode:TKraftContactPairContactManifoldMode);
20997 var ContactIndex:longint;
20998 Contact:PKraftContact;
20999 SolverContact:PKraftSolverContact;
21000 PointA,PointB,PlanePoint,ClipPoint,cA,cB:TKraftVector3;
21001 tA,tB:TKraftMatrix4x4;
21002 begin
21003 tA:=Matrix4x4TermMul(Shapes[0].fLocalTransform,WorldTransformA);
21004 tB:=Matrix4x4TermMul(Shapes[1].fLocalTransform,WorldTransformB);
21005 SolverContactManifold.CountContacts:=Manifold.CountContacts;
21006 case Manifold.ContactManifoldType of
21007 kcmtImplicit,kcmtImplicitNormal:begin
21008 case Manifold.ContactManifoldType of
21009 kcmtImplicit:begin
21010 SolverContactManifold.Normal:=Vector3Origin;
21011 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21012 Contact:[email protected][ContactIndex];
21013 PointA:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21014 PointB:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21015 SolverContactManifold.Normal:=Vector3Add(SolverContactManifold.Normal,Vector3Sub(PointB,PointA));
21016 end;
21017 if Vector3LengthSquared(SolverContactManifold.Normal)<EPSILON then begin
21018 SolverContactManifold.Normal:=Vector3YAxis;
21019 end else begin
21020 SolverContactManifold.Normal:=Vector3NormEx(SolverContactManifold.Normal);
21021 end;
21022 end;
21023 else {kcmtImplicitNormal:}begin
21024 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tB);
21025 end;
21026 end;
21027 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21028 Contact:[email protected][ContactIndex];
21029 SolverContact:[email protected][ContactIndex];
21030 PointA:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21031 PointB:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21032 case ContactManifoldMode of
21033 kcpcmmVelocitySolver,kcpcmmBaumgarte,kcpcmmTemporalCoherence:begin
21034 cA:=Vector3Add(PointA,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[0]));
21035 cB:=Vector3Sub(PointB,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[1]));
21036 SolverContact^.Point:=Vector3Avg(cA,cB);
21037 SolverContact^.Separation:=Vector3Dot(Vector3Sub(cB,cA),SolverContactManifold.Normal);
21038 end;
21039 kcpcmmPositionSolver:begin
21040 SolverContact^.Point:=Vector3Avg(PointA,PointB);
21041 SolverContact^.Separation:=Vector3Dot(Vector3Sub(PointB,PointA),SolverContactManifold.Normal)-(Manifold.LocalRadius[0]+Manifold.LocalRadius[1]);{}
21042 end;
21043 end;
21044 end;
21045 end;
21046 kcmtFaceA:begin
21047 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tA);
21048 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21049 Contact:[email protected][ContactIndex];
21050 SolverContact:[email protected][ContactIndex];
21051 PlanePoint:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21052 ClipPoint:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21053 case ContactManifoldMode of
21054 kcpcmmVelocitySolver,kcpcmmBaumgarte,kcpcmmTemporalCoherence:begin
21055 cA:=Vector3Add(ClipPoint,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[0]-Vector3Dot(Vector3Sub(ClipPoint,PlanePoint),SolverContactManifold.Normal)));
21056 cB:=Vector3Sub(ClipPoint,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[1]));
21057 SolverContact^.Point:=Vector3Avg(cA,cB);
21058 SolverContact^.Separation:=Vector3Dot(Vector3Sub(cB,cA),SolverContactManifold.Normal);
21059 end;
21060 kcpcmmPositionSolver:begin
21061 SolverContact^.Point:=ClipPoint;
21062 SolverContact^.Separation:=Vector3Dot(Vector3Sub(ClipPoint,PlanePoint),SolverContactManifold.Normal)-(Manifold.LocalRadius[0]+Manifold.LocalRadius[1]);
21063 end;
21064 end;
21065 end;
21066 end;
21067 kcmtFaceB:begin
21068 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tB);
21069 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21070 Contact:[email protected][ContactIndex];
21071 SolverContact:[email protected][ContactIndex];
21072 ClipPoint:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21073 PlanePoint:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21074 case ContactManifoldMode of
21075 kcpcmmVelocitySolver,kcpcmmBaumgarte,kcpcmmTemporalCoherence:begin
21076 cA:=Vector3Sub(ClipPoint,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[0]));
21077 cB:=Vector3Add(ClipPoint,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[1]-Vector3Dot(Vector3Sub(ClipPoint,PlanePoint),SolverContactManifold.Normal)));
21078 SolverContact^.Point:=Vector3Avg(cA,cB);
21079 SolverContact^.Separation:=Vector3Dot(Vector3Sub(cA,cB),SolverContactManifold.Normal);
21080 end;
21081 kcpcmmPositionSolver:begin
21082 SolverContact^.Point:=ClipPoint;
21083 SolverContact^.Separation:=Vector3Dot(Vector3Sub(ClipPoint,PlanePoint),SolverContactManifold.Normal)-(Manifold.LocalRadius[0]+Manifold.LocalRadius[1]);
21084 end;
21085 end;
21086 end;
21087 SolverContactManifold.Normal:=Vector3Neg(SolverContactManifold.Normal);
21088 end;
21089 kcmtEdges,kcmtImplicitEdge:begin
21090 case Manifold.ContactManifoldType of
21091 kcmtEdges:begin
21092 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tA);
21093 end;
21094 else {kcmtImplicitEdge:}begin
21095 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tB);
21096 end;
21097 end;
21098 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21099 Contact:[email protected][ContactIndex];
21100 SolverContact:[email protected][ContactIndex];
21101 PointA:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21102 PointB:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21103 case ContactManifoldMode of
21104 kcpcmmVelocitySolver,kcpcmmBaumgarte,kcpcmmTemporalCoherence:begin
21105 cA:=Vector3Add(PointA,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[0]));
21106 cB:=Vector3Sub(PointB,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[1]));
21107 SolverContact^.Point:=Vector3Avg(cA,cB);
21108 SolverContact^.Separation:=Vector3Dot(Vector3Sub(cB,cA),SolverContactManifold.Normal);
21109 end;
21110 kcpcmmPositionSolver:begin
21111 SolverContact^.Point:=Vector3Avg(PointA,PointB);
21112 SolverContact^.Separation:=Vector3Dot(Vector3Sub(PointB,PointA),SolverContactManifold.Normal)-(Manifold.LocalRadius[0]+Manifold.LocalRadius[1]);
21113 end;
21114 end;
21115 end;
21116 end;
21117 kcmtPersistentImplicit:begin
21118 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tB);
21119 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21120 Contact:[email protected][ContactIndex];
21121 SolverContact:[email protected][ContactIndex];
21122 PointA:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21123 PointB:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21124 case ContactManifoldMode of
21125 kcpcmmVelocitySolver,kcpcmmBaumgarte,kcpcmmTemporalCoherence:begin
21126 cA:=Vector3Add(PointA,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[0]));
21127 cB:=Vector3Sub(PointB,Vector3ScalarMul(SolverContactManifold.Normal,Manifold.LocalRadius[1]));
21128 SolverContact^.Point:=Vector3Avg(cA,cB);
21129 SolverContact^.Separation:=Vector3Dot(Vector3Sub(cB,cA),SolverContactManifold.Normal);
21130 end;
21131 kcpcmmPositionSolver:begin
21132 SolverContact^.Point:=Vector3Avg(PointA,PointB);
21133 SolverContact^.Separation:=Vector3Dot(Vector3Sub(PointB,PointA),SolverContactManifold.Normal)-(Manifold.LocalRadius[0]+Manifold.LocalRadius[1]);{}
21134 end;
21135 end;
21136 SolverContact^.Separation:=SolverContact^.Separation+Contact.Penetration;
21137 end;
21138 end;
21139 kcmtSpeculative:begin
21140 SolverContactManifold.Normal:=Vector3TermMatrixMulBasis(Manifold.LocalNormal,tB);
21141 for ContactIndex:=0 to Manifold.CountContacts-1 do begin
21142 Contact:[email protected][ContactIndex];
21143 SolverContact:[email protected][ContactIndex];
21144 SolverContactManifold.Points[0]:=Vector3TermMatrixMul(Contact^.LocalPoints[0],tA);
21145 SolverContactManifold.Points[1]:=Vector3TermMatrixMul(Contact^.LocalPoints[1],tB);
21146 SolverContact^.Point:=Vector3Avg(SolverContactManifold.Points[0],SolverContactManifold.Points[1]);
21147 SolverContact^.Separation:=Contact^.Penetration;
21148 end;
21149 end;
21150 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
21151 end;
21152 end;
21153
21154 procedure TKraftContactPair.DetectCollisions(const ContactManager:TKraftContactManager;const TriangleShape:TKraftShape=nil;const ThreadIndex:longint=0;const SpeculativeContacts:boolean=true;const DeltaTime:double=0.0);
21155 var OldManifoldCountContacts:longint;
21156 OldContactManifoldType:TKraftContactManifoldType;
21157 ShapeTriangle:TKraftShapeTriangle;
21158 function CreateFeatureID(const ElementA,ElementB:longword):TKraftContactFeatureID; overload; {$ifdef caninline}inline;{$endif}
21159 begin
21160 result.ElementA:=ElementA;
21161 result.ElementB:=ElementB;
21162 end;
21163 function CreateFeatureID(const Key:int64):TKraftContactFeatureID; overload; {$ifdef caninline}inline;{$endif}
21164 begin
21165 result.Key:=Key;
21166 end;
21167 procedure AddImplicitContact(const p0,p1:TKraftVector3;const r0,r1:TKraftScalar;const FeatureID:TKraftContactFeatureID;const IsLocal:boolean); {$ifdef caninline}inline;{$endif}
21168 var Contact:PKraftContact;
21169 begin
21170 if Manifold.CountContacts<MAX_CONTACTS then begin
21171 Manifold.ContactManifoldType:=kcmtImplicit;
21172 Manifold.LocalRadius[0]:=r0;
21173 Manifold.LocalRadius[1]:=r1;
21174 Contact:[email protected][Manifold.CountContacts];
21175 inc(Manifold.CountContacts);
21176 if IsLocal then begin
21177 Contact^.LocalPoints[0]:=p0;
21178 Contact^.LocalPoints[1]:=p1;
21179 end else begin
21180 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(p0,Shapes[0].fWorldTransform);
21181 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(p1,Shapes[1].fWorldTransform);
21182 end;
21183 Contact^.FeatureID:=FeatureID;
21184 end;
21185 end;
21186 procedure AddFaceAContact(const Normal,p0,p1:TKraftVector3;const r0,r1:TKraftScalar;const FeatureID:TKraftContactFeatureID;const IsLocal:boolean); {$ifdef caninline}inline;{$endif}
21187 var Contact:PKraftContact;
21188 begin
21189 if Manifold.CountContacts<MAX_CONTACTS then begin
21190 Manifold.ContactManifoldType:=kcmtFaceA;
21191 Manifold.LocalNormal:=Normal;
21192 Manifold.LocalRadius[0]:=r0;
21193 Manifold.LocalRadius[1]:=r1;
21194 Contact:[email protected][Manifold.CountContacts];
21195 inc(Manifold.CountContacts);
21196 if IsLocal then begin
21197 Contact^.LocalPoints[0]:=p0;
21198 Contact^.LocalPoints[1]:=p1;
21199 end else begin
21200 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(p0,Shapes[0].fWorldTransform);
21201 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(p1,Shapes[1].fWorldTransform);
21202 end;
21203 Contact^.FeatureID:=FeatureID;
21204 end;
21205 end;
21206 procedure AddFaceBContact(const Normal,p0,p1:TKraftVector3;const r0,r1:TKraftScalar;const FeatureID:TKraftContactFeatureID;const IsLocal:boolean); {$ifdef caninline}inline;{$endif}
21207 var Contact:PKraftContact;
21208 begin
21209 if Manifold.CountContacts<MAX_CONTACTS then begin
21210 Manifold.ContactManifoldType:=kcmtFaceB;
21211 Manifold.LocalNormal:=Normal;
21212 Manifold.LocalRadius[0]:=r0;
21213 Manifold.LocalRadius[1]:=r1;
21214 Contact:[email protected][Manifold.CountContacts];
21215 inc(Manifold.CountContacts);
21216 if IsLocal then begin
21217 Contact^.LocalPoints[0]:=p0;
21218 Contact^.LocalPoints[1]:=p1;
21219 end else begin
21220 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(p0,Shapes[0].fWorldTransform);
21221 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(p1,Shapes[1].fWorldTransform);
21222 end;
21223 Contact^.FeatureID:=FeatureID;
21224 end;
21225 end;
21226 procedure AddImplicitEdgeContact(const Normal,p0,p1:TKraftVector3;const r0,r1:TKraftScalar;const FeatureID:TKraftContactFeatureID;const IsLocal:boolean); {$ifdef caninline}inline;{$endif}
21227 var Contact:PKraftContact;
21228 begin
21229 if Manifold.CountContacts<MAX_CONTACTS then begin
21230 Manifold.ContactManifoldType:=kcmtImplicitEdge;
21231 Manifold.LocalNormal:=Normal;
21232 Manifold.LocalRadius[0]:=r0;
21233 Manifold.LocalRadius[1]:=r1;
21234 Contact:[email protected][Manifold.CountContacts];
21235 inc(Manifold.CountContacts);
21236 if IsLocal then begin
21237 Contact^.LocalPoints[0]:=p0;
21238 Contact^.LocalPoints[1]:=p1;
21239 end else begin
21240 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(p0,Shapes[0].fWorldTransform);
21241 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(p1,Shapes[1].fWorldTransform);
21242 end;
21243 Contact^.FeatureID:=FeatureID;
21244 end;
21245 end;
21246 procedure AddImplicitNormalContact(const Normal,p0,p1:TKraftVector3;const r0,r1:TKraftScalar;const FeatureID:TKraftContactFeatureID;const IsLocal:boolean); {$ifdef caninline}inline;{$endif}
21247 var Contact:PKraftContact;
21248 begin
21249 if Manifold.CountContacts<MAX_CONTACTS then begin
21250 Manifold.ContactManifoldType:=kcmtImplicitNormal;
21251 Manifold.LocalNormal:=Normal;
21252 Manifold.LocalRadius[0]:=r0;
21253 Manifold.LocalRadius[1]:=r1;
21254 Contact:[email protected][Manifold.CountContacts];
21255 inc(Manifold.CountContacts);
21256 if IsLocal then begin
21257 Contact^.LocalPoints[0]:=p0;
21258 Contact^.LocalPoints[1]:=p1;
21259 end else begin
21260 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(p0,Shapes[0].fWorldTransform);
21261 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(p1,Shapes[1].fWorldTransform);
21262 end;
21263 Contact^.FeatureID:=FeatureID;
21264 end;
21265 end;
21266 procedure CollideSphereWithSphere(ShapeA,ShapeB:TKraftShapeSphere); {$ifdef caninline}inline;{$endif}
21267 var Distance:TKraftScalar;
21268 CenterA,CenterB:TKraftVector3;
21269 begin
21270 CenterA:=Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform);
21271 CenterB:=Vector3TermMatrixMul(ShapeB.fLocalCentroid,ShapeB.fWorldTransform);
21272 Distance:=Vector3Length(Vector3Sub(CenterB,CenterA));
21273 if Distance<(ShapeA.fRadius+ShapeB.fRadius) then begin
21274 AddImplicitContact(ShapeA.fLocalCentroid,ShapeB.fLocalCentroid,ShapeA.fRadius,ShapeB.fRadius,CreateFeatureID(0),true);
21275 end;
21276 end;
21277 procedure CollideSphereWithCapsule(ShapeA:TKraftShapeSphere;ShapeB:TKraftShapeCapsule); {$ifdef caninline}inline;{$endif}
21278 var Alpha,HalfLength,Distance:TKraftScalar;
21279 CenterA,CenterB,Position,GeometryDirection:TKraftVector3;
21280 begin
21281 GeometryDirection:=PKraftVector3(pointer(@ShapeB.fWorldTransform[1,0]))^;
21282 CenterA:=Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform);
21283 CenterB:=Vector3TermMatrixMul(ShapeB.fLocalCentroid,ShapeB.fWorldTransform);
21284 Alpha:=(GeometryDirection.x*(CenterA.x-CenterB.x))+(GeometryDirection.y*(Centera.y-CenterB.y))+(GeometryDirection.z*(CenterA.z-CenterB.z));
21285 HalfLength:=ShapeB.fHeight*0.5;
21286 if Alpha>HalfLength then begin
21287 Alpha:=HalfLength;
21288 end else if alpha<-HalfLength then begin
21289 Alpha:=-HalfLength;
21290 end;
21291 Position:=Vector3Add(CenterB,Vector3ScalarMul(GeometryDirection,Alpha));
21292 Distance:=Vector3DistSquared(Position,CenterA);
21293 if Distance<=sqr(ShapeA.fRadius+ShapeB.fRadius) then begin
21294 AddImplicitContact(CenterA,Position,ShapeA.fRadius,ShapeB.fRadius,CreateFeatureID(0),false);
21295 end;
21296 end;
21297 procedure CollideSphereWithConvexHull(ShapeA:TKraftShapeSphere;ShapeB:TKraftShapeConvexHull); {$ifdef caninline}inline;{$endif}
21298 var FaceIndex,ClosestFaceIndex,VertexIndex,BestClosestFaceIndex:longint;
21299 Distance,ClosestDistance,BestClosestPointDistance,d:TKraftScalar;
21300 Center,SphereCenter,Normal,ClosestPoint,BestClosestPointOnHull,BestClosestPointNormal,ab,ap,a,b,v,n:TKraftVector3;
21301 InsideSphere,InsidePolygon,HasBestClosestPoint:boolean;
21302 Face:PKraftConvexHullFace;
21303 GJK:TKraftGJK;
21304 begin
21305
21306 GJK.CachedSimplex:[email protected];
21307 GJK.Simplex.Count:=0;
21308 GJK.Shapes[0]:=ShapeA;
21309 GJK.Shapes[1]:=ShapeB;
21310 GJK.Transforms[0]:[email protected];
21311 GJK.Transforms[1]:[email protected];
21312 GJK.UseRadii:=false;
21313
21314 GJK.Run;
21315
21316 if (GJK.Distance>0.0) and not GJK.Failed then begin
21317
21318 // Shallow contact, the more simple way
21319
21320 if GJK.Distance<=ShapeA.fRadius then begin
21321 AddImplicitNormalContact(Vector3Neg(Vector3TermMatrixMulTransposedBasis(GJK.Normal,Shapes[1].fWorldTransform)),
21322 GJK.ClosestPoints[0],
21323 GJK.ClosestPoints[1],
21324 ShapeA.fRadius,
21325 0.0,
21326 CreateFeatureID(-2),
21327 false);
21328 end;
21329
21330 end else begin
21331
21332 // Deep contact, the more hard way, the followed code works also for shallow contacts, but GJK should be faster for shallow
21333 // contacts, I think.
21334
21335 BestClosestPointNormal:=Vector3Origin;
21336 BestClosestPointOnHull:=Vector3Origin;
21337 BestClosestPointDistance:=MAX_SCALAR;
21338 HasBestClosestPoint:=false;
21339 BestClosestFaceIndex:=-1;
21340 ClosestDistance:=MAX_SCALAR;
21341 ClosestFaceIndex:=-1;
21342 InsideSphere:=true;
21343 Center:=Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform);
21344 SphereCenter:=Vector3TermMatrixMulInverted(Center,ShapeB.fWorldTransform);
21345 for FaceIndex:=0 to ShapeB.fConvexHull.fCountFaces-1 do begin
21346 Face:[email protected][FaceIndex];
21347 Distance:=PlaneVectorDistance(Face^.Plane,SphereCenter);
21348 if Distance>0.0 then begin
21349 // sphere center is not inside in the convex hull . . .
21350 if Distance<ShapeA.fRadius then begin
21351 // but touching . . .
21352 if Face^.CountVertices>0 then begin
21353 InsidePolygon:=true;
21354 n:=Face^.Plane.Normal;
21355 b:=ShapeB.fConvexHull.fVertices[Face^.Vertices[Face^.CountVertices-1]].Position;
21356 ClosestPoint:=Vector3Origin;
21357 for VertexIndex:=0 to Face^.CountVertices-1 do begin
21358 a:=b;
21359 b:=ShapeB.fConvexHull.fVertices[Face^.Vertices[VertexIndex]].Position;
21360 ab:=Vector3Sub(b,a);
21361 ap:=Vector3Sub(SphereCenter,a);
21362 v:=Vector3Cross(ab,n);
21363 if Vector3Dot(ap,v)>0.0 then begin
21364 d:=Vector3LengthSquared(ab);
21365 if d<>0.0 then begin
21366 d:=Vector3Dot(ab,ap)/d;
21367 end else begin
21368 d:=0.0;
21369 end;
21370 ClosestPoint:=Vector3Lerp(a,b,d);
21371 InsidePolygon:=false;
21372 break;
21373 end;
21374 end;
21375 if InsidePolygon then begin
21376 // sphere is directly touching the convex hull . . .
21377 AddFaceBContact(n,
21378 Center,
21379 Vector3TermMatrixMul(Vector3Sub(SphereCenter,Vector3ScalarMul(n,Distance)),ShapeB.fWorldTransform),
21380 ShapeA.fRadius,
21381 0.0,
21382 CreateFeatureID(0,FaceIndex),
21383 false);
21384 exit;
21385 end else begin
21386 // the sphere may not be directly touching the polyhedron, but it may be touching a point or an edge, if the distance between
21387 // the closest point on the poly and the center of the sphere is less than the sphere radius we have a hit.
21388 Normal:=Vector3Sub(SphereCenter,ClosestPoint);
21389 if Vector3LengthSquared(Normal)<sqr(ShapeA.fRadius) then begin
21390 Distance:=Vector3LengthNormalize(Normal);
21391 if (not HasBestClosestPoint) or (BestClosestPointDistance>Distance) then begin
21392 HasBestClosestPoint:=true;
21393 BestClosestPointDistance:=Distance;
21394 BestClosestPointOnHull:=ClosestPoint;
21395 BestClosestPointNormal:=Normal;
21396 BestClosestFaceIndex:=FaceIndex;
21397 end;
21398 end;
21399 end;
21400 end;
21401 end;
21402 InsideSphere:=false;
21403 end else if InsideSphere and ((ClosestFaceIndex<0) or (ClosestDistance>abs(Distance))) then begin
21404 ClosestDistance:=abs(Distance);
21405 ClosestFaceIndex:=FaceIndex;
21406 end;
21407 end;
21408 if InsideSphere and (ClosestFaceIndex>=0) then begin
21409 // the sphere center is inside the convex hull . . .
21410 n:=ShapeB.fConvexHull.fFaces[ClosestFaceIndex].Plane.Normal;
21411 AddImplicitNormalContact(n,
21412 Center,
21413 Vector3TermMatrixMul(Vector3Add(SphereCenter,Vector3ScalarMul(n,-ClosestDistance)),ShapeB.fWorldTransform),
21414 ShapeA.fRadius,
21415 0.0,
21416 CreateFeatureID(1,ClosestFaceIndex),
21417 false);
21418 end else if HasBestClosestPoint then begin
21419 AddImplicitNormalContact(Vector3Neg(BestClosestPointNormal),
21420 Center,
21421 Vector3TermMatrixMul(BestClosestPointOnHull,ShapeB.fWorldTransform),
21422 ShapeA.fRadius,
21423 0.0,
21424 CreateFeatureID(2,BestClosestFaceIndex),
21425 false);
21426 end;
21427 end;
21428 end;
21429 procedure CollideSphereWithBox(ShapeA:TKraftShapeSphere;ShapeB:TKraftShapeBox); {$ifdef caninline}inline;{$endif}
21430 //const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
21431 var IntersectionDist,ContactDist,DistSqr,FaceDist,MinDist:TKraftScalar;
21432 Center,SphereRelativePosition,ClosestPoint,Normal:TKraftVector3;
21433 Axis,AxisSign,BestFaceIndex:longint;
21434 begin
21435 Center:=Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform);
21436 SphereRelativePosition:=Vector3TermMatrixMulInverted(Center,ShapeB.fWorldTransform);
21437 ClosestPoint.x:=Min(Max(SphereRelativePosition.x,-ShapeB.fExtents.x),ShapeB.fExtents.x);
21438 ClosestPoint.y:=Min(Max(SphereRelativePosition.y,-ShapeB.fExtents.y),ShapeB.fExtents.y);
21439 ClosestPoint.z:=Min(Max(SphereRelativePosition.z,-ShapeB.fExtents.z),ShapeB.fExtents.z);
21440 Normal:=Vector3Sub(SphereRelativePosition,ClosestPoint);
21441 DistSqr:=Vector3LengthSquared(Normal);
21442 IntersectionDist:=ShapeA.fRadius;
21443 ContactDist:=IntersectionDist+EPSILON;
21444 BestFaceIndex:=0;
21445 if DistSqr<=sqr(ContactDist) then begin
21446 if DistSqr<=EPSILON then begin
21447 begin
21448 FaceDist:=ShapeB.fExtents.x-SphereRelativePosition.x;
21449 MinDist:=FaceDist;
21450 Axis:=0;
21451 AxisSign:=1;
21452 BestFaceIndex:=1;
21453 end;
21454 begin
21455 FaceDist:=ShapeB.fExtents.x+SphereRelativePosition.x;
21456 if FaceDist<MinDist then begin
21457 MinDist:=FaceDist;
21458 Axis:=0;
21459 AxisSign:=-1;
21460 BestFaceIndex:=2;
21461 end;
21462 end;
21463 begin
21464 FaceDist:=ShapeB.fExtents.y-SphereRelativePosition.y;
21465 if FaceDist<MinDist then begin
21466 MinDist:=FaceDist;
21467 Axis:=1;
21468 AxisSign:=1;
21469 BestFaceIndex:=3;
21470 end;
21471 end;
21472 begin
21473 FaceDist:=ShapeB.fExtents.y+SphereRelativePosition.y;
21474 if FaceDist<MinDist then begin
21475 MinDist:=FaceDist;
21476 Axis:=1;
21477 AxisSign:=-1;
21478 BestFaceIndex:=4;
21479 end;
21480 end;
21481 begin
21482 FaceDist:=ShapeB.fExtents.z-SphereRelativePosition.z;
21483 if FaceDist<MinDist then begin
21484 MinDist:=FaceDist;
21485 Axis:=2;
21486 AxisSign:=1;
21487 BestFaceIndex:=5;
21488 end;
21489 end;
21490 begin
21491 FaceDist:=ShapeB.fExtents.z+SphereRelativePosition.z;
21492 if FaceDist<MinDist then begin
21493 // MinDist:=FaceDist;
21494 Axis:=2;
21495 AxisSign:=-1;
21496 BestFaceIndex:=6;
21497 end;
21498 end;
21499 ClosestPoint:=SphereRelativePosition;
21500 ClosestPoint.xyz[Axis]:=ShapeB.fExtents.xyz[Axis]*AxisSign;
21501 Normal:=Vector3Origin;
21502 Normal.xyz[Axis]:=AxisSign;
21503 // Distance:=-MinDist;
21504 end else begin
21505 {Distance:=}Vector3NormalizeEx(Normal);
21506 end;
21507 AddFaceBContact(Normal,Center,Vector3TermMatrixMul(ClosestPoint,ShapeB.fWorldTransform),ShapeA.fRadius,0.0,CreateFeatureID(BestFaceIndex),false);
21508 end;
21509 end;
21510 procedure CollideSphereWithPlane(ShapeA:TKraftShapeSphere;ShapeB:TKraftShapePlane); {$ifdef caninline}inline;{$endif}
21511 var Distance:TKraftScalar;
21512 Center,SphereCenter,Normal:TKraftVector3;
21513 begin
21514 Center:=Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform);
21515 SphereCenter:=Vector3TermMatrixMulInverted(Center,ShapeB.fWorldTransform);
21516 Distance:=PlaneVectorDistance(ShapeB.fPlane,SphereCenter);
21517 if Distance<=ShapeA.fRadius then begin
21518 Normal:=ShapeB.fPlane.Normal;
21519 AddFaceBContact(Normal,Center,Vector3TermMatrixMul(Vector3Sub(SphereCenter,Vector3ScalarMul(Normal,Distance)),ShapeB.fWorldTransform),ShapeA.fRadius,0.0,CreateFeatureID(0),false);
21520 end;
21521 end;
21522 procedure CollideSphereWithTriangle(ShapeA:TKraftShapeSphere;ShapeB:TKraftShapeTriangle); {$ifdef caninline}inline;{$endif}
21523 const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
21524 var i:longint;
21525 Radius,RadiusWithThreshold,DistanceFromPlane,ContactRadiusSqr,DistanceSqr:TKraftScalar;
21526 Center,SphereCenter,Normal,P0ToCenter,ContactPointOnTriangle,NearestOnEdge,ContactToCenter:TKraftVector3;
21527 IsInsideContactPlane,HasContact,IsEdge:boolean;
21528 v:array[0..2] of PKraftVector3;
21529 begin
21530 v[0]:[email protected][0].Position;
21531 v[1]:[email protected][1].Position;
21532 v[2]:[email protected][2].Position;
21533 Center:=Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform);
21534 SphereCenter:=Vector3TermMatrixMulInverted(Center,ShapeB.fWorldTransform);
21535 Radius:=ShapeA.fRadius;
21536 RadiusWithThreshold:=Radius+EPSILON;
21537 Normal:=Vector3SafeNorm(Vector3Cross(Vector3Sub(v[1]^,v[0]^),Vector3Sub(v[2]^,v[0]^)));
21538 P0ToCenter:=Vector3Sub(SphereCenter,v[0]^);
21539 DistanceFromPlane:=Vector3Dot(P0ToCenter,Normal);
21540 if DistanceFromPlane<0.0 then begin
21541 DistanceFromPlane:=-DistanceFromPlane;
21542 Normal:=Vector3Neg(Normal);
21543 end;
21544 IsInsideContactPlane:=DistanceFromPlane<RadiusWithThreshold;
21545 HasContact:=false;
21546 IsEdge:=false;
21547 ContactPointOnTriangle:=Vector3Origin;
21548 ContactRadiusSqr:=sqr(RadiusWithThreshold);
21549 if IsInsideContactPlane then begin
21550 if PointInTriangle(v[0]^,v[1]^,v[2]^,Normal,SphereCenter) then begin
21551 HasContact:=true;
21552 ContactPointOnTriangle:=Vector3Sub(SphereCenter,Vector3ScalarMul(Normal,DistanceFromPlane));
21553 end else begin
21554 for i:=0 to 2 do begin
21555 DistanceSqr:=SegmentSqrDistance(v[i]^,v[ModuloThree[i+1]]^,SphereCenter,NearestOnEdge);
21556 if DistanceSqr<ContactRadiusSqr then begin
21557 HasContact:=true;
21558 IsEdge:=true;
21559 ContactPointOnTriangle:=NearestOnEdge;
21560 end;
21561 end;
21562 end;
21563 end;
21564 if HasContact then begin
21565 ContactToCenter:=Vector3Sub(SphereCenter,ContactPointOnTriangle);
21566 DistanceSqr:=Vector3LengthSquared(ContactToCenter);
21567 if DistanceSqr<ContactRadiusSqr then begin
21568 if DistanceSqr>EPSILON then begin
21569 if IsEdge then begin
21570 AddImplicitNormalContact(Vector3Neg(Vector3Norm(ContactToCenter)),Center,Vector3TermMatrixMul(ContactPointOnTriangle,ShapeB.fWorldTransform),ShapeA.fRadius,0.0,CreateFeatureID(2),false);
21571 end else begin
21572 AddImplicitContact(Center,Vector3TermMatrixMul(ContactPointOnTriangle,ShapeB.fWorldTransform),ShapeA.fRadius,0.0,CreateFeatureID(0),false);
21573 end;
21574 end else begin
21575 AddFaceBContact(Normal,Center,Vector3TermMatrixMul(ContactPointOnTriangle,ShapeB.fWorldTransform),ShapeA.fRadius,0.0,CreateFeatureID(1),false);
21576 end;
21577 end;
21578 end;
21579 end;
21580 procedure CollideCapsuleWithCapsule(ShapeA,ShapeB:TKraftShapeCapsule); {$ifdef caninline}inline;{$endif}
21581 const Tolerance=0.005;
21582 var RadiusA,RadiusB,SquaredRadiiWithTolerance,HalfLengthA,HalfLengthB,TimeA,TimeB,SquaredDistance:TKraftScalar;
21583 CenterA,CenterB,GeometryDirectionA,GeometryDirectionB,HalfAxis,ClosestPointA,ClosestPointB:TKraftVector3;
21584 SegmentA,SegmentB:TKraftSegment;
21585 begin
21586
21587 CenterA:=Vector3TermMatrixMul(ShapeA.fLocalCenterOfMass,ShapeA.fWorldTransform);
21588 CenterB:=Vector3TermMatrixMul(ShapeB.fLocalCenterOfMass,ShapeB.fWorldTransform);
21589
21590 GeometryDirectionA:=PKraftVector3(pointer(@ShapeA.fWorldTransform[1,0]))^;
21591 GeometryDirectionB:=PKraftVector3(pointer(@ShapeB.fWorldTransform[1,0]))^;
21592
21593 RadiusA:=ShapeA.fRadius;
21594 RadiusB:=ShapeB.fRadius;
21595
21596 SquaredRadiiWithTolerance:=sqr((RadiusA+RadiusB)+EPSILON);
21597
21598 HalfLengthA:=ShapeA.fHeight*0.5;
21599 HalfLengthB:=ShapeB.fHeight*0.5;
21600
21601 HalfAxis:=Vector3ScalarMul(GeometryDirectionA,HalfLengthA);
21602 SegmentA.Points[0]:=Vector3Sub(CenterA,HalfAxis);
21603 SegmentA.Points[1]:=Vector3Add(CenterA,HalfAxis);
21604
21605 HalfAxis:=Vector3ScalarMul(GeometryDirectionB,HalfLengthB);
21606 SegmentB.Points[0]:=Vector3Sub(CenterB,HalfAxis);
21607 SegmentB.Points[1]:=Vector3Add(CenterB,HalfAxis);
21608
21609 // Find the closest points between the two capsules
21610 SIMDSegmentClosestPoints(SegmentA,SegmentB,TimeA,ClosestPointA,TimeB,ClosestPointB);
21611
21612 SquaredDistance:=Vector3DistSquared(ClosestPointA,ClosestPointB);
21613
21614 if SquaredDistance<SquaredRadiiWithTolerance then begin
21615
21616 AddImplicitContact(ClosestPointA,ClosestPointB,RadiusA,RadiusB,CreateFeatureID(0),false);
21617
21618 // If the two capsules are nearly parallel, an additional support point provides stability
21619 {if (Vector3Length(Vector3Cross(GeometryDirectionA,GeometryDirectionB))<(sqrt(Vector3LengthSquared(GeometryDirectionA)*Vector3LengthSquared(GeometryDirectionB))*Tolerance)) then{}begin
21620
21621 if abs(TimeA)<EPSILON then begin
21622 ClosestPointA:=SegmentA.Points[1];
21623 SIMDSegmentClosestPointTo(SegmentB,ClosestPointA,TimeB,ClosestPointB);
21624 end else if abs(1.0-TimeA)<EPSILON then begin
21625 ClosestPointA:=SegmentA.Points[0];
21626 SIMDSegmentClosestPointTo(SegmentB,ClosestPointA,TimeB,ClosestPointB);
21627 end else if abs(TimeB)<EPSILON then begin
21628 ClosestPointB:=SegmentB.Points[1];
21629 SIMDSegmentClosestPointTo(SegmentA,ClosestPointB,TimeA,ClosestPointA);
21630 end else if abs(1.0-TimeB)<EPSILON then begin
21631 ClosestPointB:=SegmentB.Points[0];
21632 SIMDSegmentClosestPointTo(SegmentA,ClosestPointB,TimeA,ClosestPointA);
21633 end else begin
21634 exit;
21635 end;
21636
21637 SquaredDistance:=Vector3DistSquared(ClosestPointA,ClosestPointB);
21638 if SquaredDistance<SquaredRadiiWithTolerance then begin
21639 AddImplicitContact(ClosestPointA,ClosestPointB,RadiusA,RadiusB,CreateFeatureID(1),false);
21640 end;
21641
21642 end;
21643
21644 end;
21645
21646
21647 end;
21648 procedure CollideCapsuleWithConvexHull(ShapeA:TKraftShapeCapsule;ShapeB:TKraftShapeConvexHull); {$ifdef caninline}inline;{$endif}
21649 const Tolerance=0.005;
21650 var FaceIndex,VertexIndex,OtherVertexIndex,PointIndex,MaxFaceIndex,MaxEdgeIndex,EdgeIndex:longint;
21651 CapsuleRadius,Distance,MaxFaceSeparation,MaxEdgeSeparation,Separation,L:TKraftScalar;
21652 CapsulePosition,CapsuleAxis,CapsulePointStart,CapsulePointEnd,Normal,FaceNormal,{MaxFaceSeparateAxis,}
21653 MaxEdgeSeparateAxis,CenterB,Ea,Eb,Ea_x_Eb:TKraftVector3;
21654 OK:boolean;
21655 Face:PKraftConvexHullFace;
21656 Edge:PKraftConvexHullEdge;
21657 Plane:TKraftPlane;
21658 ClosestPoints:array[0..1] of TKraftVector3;
21659 GJK:TKraftGJK;
21660 Transform:TKraftMatrix4x4;
21661 function GetEdgeContact(var CA,CB:TKraftVector3;const PA,QA,PB,QB:TKraftVector3):boolean;
21662 var DA,DB,r:TKraftVector3;
21663 a,e,f,c,b,d,TA,TB:TKraftScalar;
21664 begin
21665 DA:=Vector3Sub(QA,PA);
21666 DB:=Vector3Sub(QB,PB);
21667 r:=Vector3Sub(PA,PB);
21668 a:=Vector3LengthSquared(DA);
21669 e:=Vector3LengthSquared(DB);
21670 f:=Vector3Dot(DB,r);
21671 c:=Vector3Dot(DA,r);
21672 b:=Vector3Dot(DA,DB);
21673 d:=(a*e)-sqr(b);
21674 if (d<>0.0) and (e<>0.0) then begin
21675 TA:=Min(Max(((b*f)-(c*e))/d,0.0),1.0);
21676 TB:=Min(Max(((b*TA)+f)/e,0.0),1.0);
21677 CA:=Vector3Add(PA,Vector3ScalarMul(DA,TA));
21678 CB:=Vector3Add(PB,Vector3ScalarMul(DB,TB));
21679 result:=true;
21680 end else begin
21681 result:=false;
21682 end;
21683 end;
21684 begin
21685
21686 Manifold.CountContacts:=0;
21687
21688 GJK.CachedSimplex:[email protected];
21689 GJK.Simplex.Count:=0;
21690 GJK.Shapes[0]:=ShapeA;
21691 GJK.Shapes[1]:=ShapeB;
21692 GJK.Transforms[0]:[email protected];
21693 GJK.Transforms[1]:[email protected];
21694 GJK.UseRadii:=false;
21695
21696 GJK.Run;
21697
21698 if (GJK.Distance>0.0) and not GJK.Failed then begin
21699
21700 // Shallow contact
21701
21702 if GJK.Distance<=ShapeA.fRadius then begin
21703
21704 // Check for a parallel face first
21705 Normal:=GJK.Normal;
21706 for FaceIndex:=0 to ShapeB.fConvexHull.fCountFaces-1 do begin
21707 Face:[email protected][FaceIndex];
21708 FaceNormal:=Vector3Norm(Vector3TermMatrixMulBasis(Face^.Plane.Normal,ShapeB.fWorldTransform));
21709 if (Vector3Dot(FaceNormal,Normal)>0.0) and
21710 (Vector3Length(Vector3Cross(FaceNormal,Normal))<(sqrt(Vector3LengthSquared(FaceNormal)*Vector3LengthSquared(Normal))*Tolerance)) then begin
21711 CapsulePosition:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform),ShapeB.fWorldTransform);
21712 CapsuleAxis:=Vector3Norm(Vector3TermMatrixMulTransposedBasis(Vector3(ShapeA.fWorldTransform[1,0],ShapeA.fWorldTransform[1,1],ShapeA.fWorldTransform[1,2]),ShapeB.fWorldTransform));
21713 ClosestPoints[0]:=Vector3Sub(CapsulePosition,Vector3ScalarMul(CapsuleAxis,ShapeA.fHeight*0.5));
21714 ClosestPoints[1]:=Vector3Add(CapsulePosition,Vector3ScalarMul(CapsuleAxis,ShapeA.fHeight*0.5));
21715 if Face^.CountVertices>0 then begin
21716 OK:=true;
21717 OtherVertexIndex:=Face^.CountVertices-1;
21718 for VertexIndex:=0 to Face^.CountVertices-1 do begin
21719 Plane.Normal:=Vector3Norm(Vector3Cross(Face^.Plane.Normal,Vector3Sub(ShapeB.fConvexHull.fVertices[Face^.Vertices[VertexIndex]].Position,ShapeB.fConvexHull.fVertices[Face^.Vertices[OtherVertexIndex]].Position)));
21720 Plane.Distance:=-Vector3Dot(Plane.Normal,ShapeB.fConvexHull.fVertices[Face^.Vertices[VertexIndex]].Position);
21721 if not ClipSegmentToPlane(Plane,ClosestPoints[0],ClosestPoints[1]) then begin
21722 OK:=false;
21723 break;
21724 end;
21725 OtherVertexIndex:=VertexIndex;
21726 end;
21727 if OK then begin
21728 for PointIndex:=0 to 1 do begin
21729 Distance:=PlaneVectorDistance(Face^.Plane,ClosestPoints[PointIndex]);
21730 if Distance<=ShapeA.fRadius then begin
21731 FaceNormal:=Face^.Plane.Normal;
21732 AddFaceBContact(FaceNormal,
21733 Vector3TermMatrixMul(ClosestPoints[PointIndex],ShapeB.fWorldTransform),
21734 Vector3TermMatrixMul(Vector3Sub(ClosestPoints[PointIndex],Vector3ScalarMul(FaceNormal,Distance)),ShapeB.fWorldTransform),
21735 ShapeA.fRadius,
21736 0.0,
21737 CreateFeatureID(1,PointIndex),
21738 false);
21739 end;
21740 end;
21741 if Manifold.CountContacts>1 then begin
21742 exit;
21743 end else begin
21744 Manifold.CountContacts:=0;
21745 end;
21746 end;
21747 end;
21748 end;
21749 end;
21750
21751 // No parallel face plane with two contacts found, so use GJK closest points for one single implicit surface contact
21752 AddImplicitNormalContact(Vector3Neg(Vector3TermMatrixMulTransposedBasis(GJK.Normal,Shapes[1].fWorldTransform)),
21753 GJK.ClosestPoints[0],
21754 GJK.ClosestPoints[1],
21755 ShapeA.fRadius,
21756 0.0,
21757 CreateFeatureID(0),
21758 false);
21759 end;
21760
21761 end else begin
21762
21763 // Deep contact
21764
21765 CapsuleRadius:=ShapeA.fRadius;
21766
21767 CapsulePosition:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform),ShapeB.fWorldTransform);
21768 CapsuleAxis:=Vector3Norm(Vector3TermMatrixMulTransposedBasis(Vector3(ShapeA.fWorldTransform[1,0],ShapeA.fWorldTransform[1,1],ShapeA.fWorldTransform[1,2]),ShapeB.fWorldTransform));
21769
21770 CapsulePointStart:=Vector3Sub(CapsulePosition,Vector3ScalarMul(CapsuleAxis,ShapeA.fHeight*0.5));
21771 CapsulePointEnd:=Vector3Add(CapsulePosition,Vector3ScalarMul(CapsuleAxis,ShapeA.fHeight*0.5));
21772
21773 Transform:=Matrix4x4TermMulInverted(ShapeB.fWorldTransform,ShapeA.fWorldTransform);
21774 MaxFaceIndex:=-1;
21775 MaxFaceSeparation:=-MAX_SCALAR;
21776 for FaceIndex:=0 to ShapeB.fConvexHull.fCountFaces-1 do begin
21777 Face:[email protected][FaceIndex];
21778 Plane:=PlaneFastTransform(Face^.Plane,Transform);
21779 Separation:=PlaneVectorDistance(Plane,ShapeA.GetLocalFullSupport(Vector3Neg(Plane.Normal)));
21780 if Separation>0.0 then begin
21781 exit;
21782 end else if MaxFaceSeparation<Separation then begin
21783 MaxFaceIndex:=FaceIndex;
21784 MaxFaceSeparation:=Separation;
21785 //MaxFaceSeparateAxis:=Face^.Plane.Normal;
21786 end;
21787 end;
21788
21789 MaxEdgeIndex:=-1;
21790 MaxEdgeSeparation:=-MAX_SCALAR;
21791 MaxEdgeSeparateAxis:=Vector3Origin;
21792 Ea:=Vector3Sub(CapsulePointEnd,CapsulePointStart);
21793 CenterB:=ShapeB.fLocalCenterOfMass;
21794 for EdgeIndex:=0 to ShapeB.fConvexHull.fCountEdges-1 do begin
21795 Edge:[email protected][EdgeIndex];
21796 if (Vector3Dot(Ea,ShapeB.fConvexHull.fFaces[Edge^.Faces[0]].Plane.Normal)*Vector3Dot(Ea,ShapeB.fConvexHull.fFaces[Edge^.Faces[1]].Plane.Normal))<0.0 then begin
21797
21798 Eb:=Vector3Sub(ShapeB.fConvexHull.fVertices[Edge^.Vertices[1]].Position,ShapeB.fConvexHull.fVertices[Edge^.Vertices[0]].Position);
21799
21800 // Build search direction
21801 Ea_x_Eb:=Vector3Cross(Ea,Eb);
21802
21803 // Skip near parallel edges: |Ea x Eb| = sin(alpha) * |Ea| * |Eb|
21804 L:=Vector3Length(Ea_x_Eb);
21805 if L<(sqrt(Vector3LengthSquared(Ea)*Vector3LengthSquared(Eb))*Tolerance) then begin
21806 continue;
21807 end;
21808
21809 // Assure consistent normal orientation (here: HullA -> HullB)
21810 Normal:=Vector3ScalarMul(Ea_x_Eb,1.0/L);
21811 if Vector3Dot(Normal,Vector3Sub(ShapeB.fConvexHull.fVertices[Edge^.Vertices[0]].Position,CenterB))<0.0 then begin
21812 Normal:=Vector3Neg(Normal);
21813 end;
21814
21815 Separation:=Vector3Dot(Normal,Vector3Sub(CapsulePointStart,ShapeB.fConvexHull.fVertices[Edge^.Vertices[0]].Position))-CapsuleRadius;
21816 if Separation>0.0 then begin
21817 exit;
21818 end else if MaxEdgeSeparation<Separation then begin
21819 MaxEdgeSeparation:=Separation;
21820 MaxEdgeSeparateAxis:=Normal;
21821 MaxEdgeIndex:=EdgeIndex;
21822 end;
21823 end;
21824
21825 end;
21826
21827 if (MaxEdgeIndex>=0) and (MaxEdgeSeparation>(MaxFaceSeparation+0.05)) then begin
21828 Edge:[email protected][MaxEdgeIndex];
21829 if GetEdgeContact(ClosestPoints[0],
21830 ClosestPoints[1],
21831 CapsulePointStart,
21832 CapsulePointEnd,
21833 ShapeB.fConvexHull.fVertices[Edge^.Vertices[0]].Position,
21834 ShapeB.fConvexHull.fVertices[Edge^.Vertices[1]].Position) then begin
21835 AddImplicitEdgeContact(Vector3Neg(MaxEdgeSeparateAxis),
21836 ClosestPoints[0],
21837 ClosestPoints[1],
21838 CapsuleRadius,
21839 0.0,
21840 CreateFeatureID(2,MaxEdgeIndex),
21841 false);
21842 exit;
21843 end;
21844 end;
21845
21846 if MaxFaceIndex>=0 then begin
21847 ClosestPoints[0]:=CapsulePointStart;
21848 ClosestPoints[1]:=CapsulePointEnd;
21849 Face:[email protected][MaxFaceIndex];
21850 if Face^.CountVertices>0 then begin
21851 OK:=true;
21852 OtherVertexIndex:=Face^.CountVertices-1;
21853 for VertexIndex:=0 to Face^.CountVertices-1 do begin
21854 Plane.Normal:=Vector3Norm(Vector3Cross(Face^.Plane.Normal,Vector3Sub(ShapeB.fConvexHull.fVertices[Face^.Vertices[VertexIndex]].Position,ShapeB.fConvexHull.fVertices[Face^.Vertices[OtherVertexIndex]].Position)));
21855 Plane.Distance:=-Vector3Dot(Plane.Normal,ShapeB.fConvexHull.fVertices[Face^.Vertices[VertexIndex]].Position);
21856 if not ClipSegmentToPlane(Plane,ClosestPoints[0],ClosestPoints[1]) then begin
21857 OK:=false;
21858 break;
21859 end;
21860 OtherVertexIndex:=VertexIndex;
21861 end;
21862 if OK then begin
21863 FaceNormal:=Face^.Plane.Normal;
21864 for PointIndex:=0 to 1 do begin
21865 Distance:=PlaneVectorDistance(Face^.Plane,ClosestPoints[PointIndex]);
21866 if Distance<=ShapeA.fRadius then begin
21867 AddFaceBContact(FaceNormal,
21868 Vector3TermMatrixMul(ClosestPoints[PointIndex],ShapeB.fWorldTransform),
21869 Vector3TermMatrixMul(Vector3Sub(ClosestPoints[PointIndex],Vector3ScalarMul(FaceNormal,Distance)),ShapeB.fWorldTransform),
21870 CapsuleRadius,
21871 0.0,
21872 CreateFeatureID(3,PointIndex),
21873 false);
21874 end;
21875 end;
21876 end;
21877 end;
21878 end;
21879 end;
21880
21881 end;
21882 procedure CollideCapsuleWithTriangle(ShapeA:TKraftShapeCapsule;ShapeB:TKraftShapeTriangle); {$ifdef caninline}inline;{$endif}
21883 var Index,Count:longint;
21884 Radius,HalfLength,SquaredDistance,SquaredRadius,d:TKraftScalar;
21885 Center,GeometryDirection,HalfAxis,pa,pb,Normal:TKraftVector3;
21886 Segment:TKraftSegment;
21887 Triangle:TKraftTriangle;
21888 UseTriangleNormal:boolean;
21889 begin
21890
21891 Manifold.CountContacts:=0;
21892
21893 Center:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(ShapeA.fLocalCentroid,ShapeA.fWorldTransform),ShapeB.fWorldTransform);
21894
21895 GeometryDirection:=Vector3TermMatrixMulTransposedBasis(PKraftVector3(pointer(@ShapeA.fWorldTransform[1,0]))^,ShapeB.fWorldTransform);
21896
21897 Triangle.Points[0]:=ShapeB.fConvexHull.fVertices[0].Position;
21898 Triangle.Points[1]:=ShapeB.fConvexHull.fVertices[1].Position;
21899 Triangle.Points[2]:=ShapeB.fConvexHull.fVertices[2].Position;
21900 Triangle.Normal:=ShapeB.fConvexHull.fFaces[0].Plane.Normal;
21901
21902 Radius:=ShapeA.fRadius;
21903
21904 SquaredRadius:=sqr(Radius);
21905
21906 HalfLength:=ShapeA.fHeight*0.5;
21907
21908 HalfAxis:=Vector3ScalarMul(GeometryDirection,HalfLength);
21909 Segment.Points[0]:=Vector3Sub(Center,HalfAxis);
21910 Segment.Points[1]:=Vector3Add(Center,HalfAxis);
21911
21912 Count:=0;
21913 for Index:=0 to 1 do begin
21914 pa:=Segment.Points[Index];
21915 UseTriangleNormal:=SIMDTriangleClosestPointTo(Triangle,pa,pb);
21916 SquaredDistance:=Vector3DistSquared(pa,pb);
21917 if SquaredDistance<(SquaredRadius+EPSILON) then begin
21918 if UseTriangleNormal then begin
21919 Normal:=Triangle.Normal;
21920 end else begin
21921 Normal:=Vector3Sub(pa,pb);
21922 d:=Vector3Dot(Normal,Triangle.Normal);
21923 if d<-EPSILON then begin
21924 Normal:=Vector3Sub(pa,Vector3ScalarMul(Triangle.Normal,2.0*d));
21925 end;
21926 Vector3NormalizeEx(Normal);
21927 end;
21928 Normal:=Vector3TermMatrixMulBasis(Normal,ShapeB.fWorldTransform);
21929 AddFaceBContact(Normal,
21930 Vector3TermMatrixMul(pa,ShapeB.fWorldTransform),
21931 Vector3TermMatrixMul(pb,ShapeB.fWorldTransform),
21932 Radius,
21933 0.0,
21934 CreateFeatureID(1,Index),
21935 false);
21936 inc(Count);
21937 end;
21938 end;
21939
21940 if Count<2 then begin
21941
21942 UseTriangleNormal:=SIMDTriangleClosestPointTo(Triangle,Segment,d,pa,pb);
21943 SquaredDistance:=Vector3DistSquared(pa,pb);
21944 if ((d>=EPSILON) and (d<=(1.0-EPSILON))) and (SquaredDistance<(SquaredRadius+EPSILON)) then begin
21945 if UseTriangleNormal then begin
21946 Normal:=Triangle.Normal;
21947 end else begin
21948 Normal:=Vector3Sub(pa,pb);
21949 d:=Vector3Dot(Normal,Triangle.Normal);
21950 if d<-EPSILON then begin
21951 Normal:=Vector3Sub(pa,Vector3ScalarMul(Triangle.Normal,2.0*d));
21952 end;
21953 Vector3NormalizeEx(Normal);
21954 end;
21955 Normal:=Vector3TermMatrixMulBasis(Normal,ShapeB.fWorldTransform);
21956 AddFaceBContact(Normal,
21957 Vector3TermMatrixMul(pa,ShapeB.fWorldTransform),
21958 Vector3TermMatrixMul(pb,ShapeB.fWorldTransform),
21959 Radius,
21960 0.0,
21961 CreateFeatureID(0),
21962 false);
21963 end;
21964
21965 end;
21966
21967 end;
21968 procedure CollideConvexHullWithConvexHull(ShapeA,ShapeB:TKraftShapeConvexHull);
21969 const kTolerance=0.005; // Skip near parallel edges: |Ea x Eb| = sin(alpha) * |Ea| * |Eb|
21970 RelativeEdgeTolerance=0.90;
21971 RelativeFaceTolerance=0.98;
21972 TemporalCoherenceRelativeTransformTolerance=0.0001;
21973 var LinearSlop,SeparationTolerance,AbsoluteTolerance:single;
21974 function IsMinkowskiFace(const A,B,B_x_A,C,D,D_x_C:TKraftVector3):boolean; {$ifdef caninline}inline;{$endif}
21975 var CBA,DBA,ADC,BDC:TKraftScalar;
21976 begin
21977 // Test if arcs AB and CD intersect on the unit sphere
21978 CBA:=Vector3Dot(C,B_x_A);
21979 DBA:=Vector3Dot(D,B_x_A);
21980 ADC:=Vector3Dot(A,D_x_C);
21981 BDC:=Vector3Dot(B,D_x_C);
21982 result:=((CBA*DBA<0.0)) and ((ADC*BDC)<0.0) and ((CBA*BDC)>0.0);
21983 end;
21984 function TestEarlyFaceDirection(const HullA,HullB:TKraftShapeConvexHull;var FaceQuery:TKraftContactFaceQuery):boolean; {$ifdef caninline}inline;{$endif}
21985 var Plane:TKraftPlane;
21986 Transform:TKraftMatrix4x4;
21987 begin
21988 Transform:=Matrix4x4TermMulSimpleInverted(HullA.fWorldTransform,HullB.fWorldTransform);
21989 Plane:=PlaneFastTransform(HullA.fConvexHull.fFaces[FaceQuery.Index].Plane,Transform);
21990 FaceQuery.Separation:=PlaneVectorDistance(Plane,HullB.GetLocalFullSupport(Vector3Neg(Plane.Normal)));
21991 result:=FaceQuery.Separation>0.0;
21992 end;
21993 function TestEarlyEdgeDirection(const HullA,HullB:TKraftShapeConvexHull;var EdgeQuery:TKraftContactEdgeQuery):boolean; {$ifdef caninline}inline;{$endif}
21994 var EdgeA,EdgeB:PKraftConvexHullEdge;
21995 L:TKraftScalar;
21996 CenterA,Pa,Qa,Ea,Ua,Va,Pb,Qb,Eb,Ub,Vb,Ea_x_Eb,Normal:TKraftVector3;
21997 Transform:TKraftMatrix4x4;
21998 begin
21999 result:=false;
22000 Transform:=Matrix4x4TermMulSimpleInverted(HullA.fWorldTransform,HullB.fWorldTransform);
22001 CenterA:=HullA.GetCenter(Transform);
22002 EdgeA:[email protected][EdgeQuery.IndexA];
22003 Pa:=Vector3TermMatrixMul(HullA.fConvexHull.fVertices[EdgeA^.Vertices[0]].Position,Transform);
22004 Qa:=Vector3TermMatrixMul(HullA.fConvexHull.fVertices[EdgeA^.Vertices[1]].Position,Transform);
22005 Ea:=Vector3Sub(Qa,Pa);
22006 Ua:=Vector3Norm(Vector3TermMatrixMulBasis(HullA.fConvexHull.fFaces[EdgeA^.Faces[0]].Plane.Normal,Transform));
22007 Va:=Vector3Norm(Vector3TermMatrixMulBasis(HullA.fConvexHull.fFaces[EdgeA^.Faces[1]].Plane.Normal,Transform));
22008 EdgeB:[email protected][EdgeQuery.IndexB];
22009 Pb:=HullB.fConvexHull.fVertices[EdgeB^.Vertices[0]].Position;
22010 Qb:=HullB.fConvexHull.fVertices[EdgeB^.Vertices[1]].Position;
22011 Eb:=Vector3Sub(Qb,Pb);
22012 Ub:=HullB.fConvexHull.fFaces[EdgeB^.Faces[0]].Plane.Normal;
22013 Vb:=HullB.fConvexHull.fFaces[EdgeB^.Faces[1]].Plane.Normal;
22014 if IsMinkowskiFace(Ua,Va,Vector3Neg(Ea),Vector3Neg(Ub),Vector3Neg(Vb),Vector3Neg(Eb)) then begin
22015 // Build search direction
22016 Ea_x_Eb:=Vector3Cross(Ea,Eb);
22017
22018 // Skip near parallel edges: |Ea x Eb| = sin(alpha) * |Ea| * |Eb|
22019 L:=Vector3Length(Ea_x_Eb);
22020 if L<(sqrt(Vector3LengthSquared(Ea)*Vector3LengthSquared(Eb))*kTolerance) then begin
22021 result:=false;
22022 exit;
22023 end;
22024
22025 // Assure consistent normal orientation (here: HullA -> HullB)
22026 Normal:=Vector3ScalarMul(Ea_x_Eb,1.0/L);
22027 if Vector3Dot(Normal,Vector3Sub(Pa,CenterA))<0.0 then begin
22028 Normal:=Vector3Neg(Normal);
22029 end;
22030
22031 // s = Dot(Normal, Pb) - d = Dot(Normal, Pb) - Dot(Normal, Pa) = Dot(Normal, Pb - Pa)
22032 EdgeQuery.Separation:=Vector3Dot(Normal,Vector3Sub(Pb,Pa));
22033 if EdgeQuery.Separation>0.0 then begin
22034 EdgeQuery.Normal:=Normal;
22035 result:=true;
22036 end;
22037
22038 end;
22039 end;
22040 procedure QueryFaceDirections(const HullA,HullB:TKraftShapeConvexHull;out OutFaceQuery:TKraftContactFaceQuery); {$ifdef caninline}inline;{$endif}
22041 var MaxIndex,Index:longint;
22042 MaxSeparation,Separation:TKraftScalar;
22043 Plane:TKraftPlane;
22044 Transform:TKraftMatrix4x4;
22045 begin
22046 Transform:=Matrix4x4TermMulSimpleInverted(HullA.fWorldTransform,HullB.fWorldTransform);
22047 MaxIndex:=-1;
22048 MaxSeparation:=-MAX_SCALAR;
22049 for Index:=0 to HullA.fConvexHull.fCountFaces-1 do begin
22050 Plane:=PlaneFastTransform(HullA.fConvexHull.fFaces[Index].Plane,Transform);
22051 Separation:=PlaneVectorDistance(Plane,HullB.GetLocalFullSupport(Vector3Neg(Plane.Normal)));
22052 if (Index=0) or (MaxSeparation<Separation) then begin
22053 MaxSeparation:=Separation;
22054 MaxIndex:=Index;
22055 if MaxSeparation>0.0 then begin
22056 break;
22057 end;
22058 end;
22059 end;
22060 OutFaceQuery.Index:=MaxIndex;
22061 OutFaceQuery.Separation:=MaxSeparation;
22062 end;
22063 procedure QueryEdgeDirections(const HullA,HullB:TKraftShapeConvexHull;out OutEdgeQuery:TKraftContactEdgeQuery); {$ifdef caninline}inline;{$endif}
22064 var EdgeA,EdgeB:PKraftConvexHullEdge;
22065 IndexA,IndexB,MaxIndexA,MaxIndexB:longint;
22066 MaxSeparation,Separation,L:TKraftScalar;
22067 CenterA,Pa,Qa,Ea,Ua,Va,Pb,Qb,Eb,Ub,Vb,Ea_x_Eb,Normal,MaxNormal:TKraftVector3;
22068 Transform:TKraftMatrix4x4;
22069 First:boolean;
22070 begin
22071 MaxIndexA:=-1;
22072 MaxIndexB:=-1;
22073 MaxSeparation:=-MAX_SCALAR;
22074 MaxNormal:=Vector3Origin;
22075 Transform:=Matrix4x4TermMulSimpleInverted(HullA.fWorldTransform,HullB.fWorldTransform);
22076 CenterA:=HullA.GetCenter(Transform);
22077 First:=true;
22078 for IndexA:=0 to HullA.fConvexHull.fCountEdges-1 do begin
22079 EdgeA:[email protected][IndexA];
22080 Pa:=Vector3TermMatrixMul(HullA.fConvexHull.fVertices[EdgeA^.Vertices[0]].Position,Transform);
22081 Qa:=Vector3TermMatrixMul(HullA.fConvexHull.fVertices[EdgeA^.Vertices[1]].Position,Transform);
22082 Ea:=Vector3Sub(Qa,Pa);
22083 Ua:=Vector3Norm(Vector3TermMatrixMulBasis(HullA.fConvexHull.fFaces[EdgeA^.Faces[0]].Plane.Normal,Transform));
22084 Va:=Vector3Norm(Vector3TermMatrixMulBasis(HullA.fConvexHull.fFaces[EdgeA^.Faces[1]].Plane.Normal,Transform));
22085 for IndexB:=0 to HullB.fConvexHull.fCountEdges-1 do begin
22086 EdgeB:[email protected][IndexB];
22087 Pb:=HullB.fConvexHull.fVertices[EdgeB^.Vertices[0]].Position;
22088 Qb:=HullB.fConvexHull.fVertices[EdgeB^.Vertices[1]].Position;
22089 Eb:=Vector3Sub(Qb,Pb);
22090 Ub:=HullB.fConvexHull.fFaces[EdgeB^.Faces[0]].Plane.Normal;
22091 Vb:=HullB.fConvexHull.fFaces[EdgeB^.Faces[1]].Plane.Normal;
22092 if IsMinkowskiFace(Ua,Va,Vector3Neg(Ea),Vector3Neg(Ub),Vector3Neg(Vb),Vector3Neg(Eb)) then begin
22093 // Build search direction
22094 Ea_x_Eb:=Vector3Cross(Ea,Eb);
22095
22096 // Skip near parallel edges: |Ea x Eb| = sin(alpha) * |Ea| * |Eb|
22097 L:=Vector3Length(Ea_x_Eb);
22098 if L<(sqrt(Vector3LengthSquared(Ea)*Vector3LengthSquared(Eb))*kTolerance) then begin
22099 continue;
22100 end;
22101
22102 // Assure consistent normal orientation (here: HullA -> HullB)
22103 Normal:=Vector3ScalarMul(Ea_x_Eb,1.0/L);
22104 if Vector3Dot(Normal,Vector3Sub(Pa,CenterA))<0.0 then begin
22105 Normal:=Vector3Neg(Normal);
22106 end;
22107
22108 // s = Dot(Normal, Pb) - d = Dot(Normal, Pb) - Dot(Normal, Pa) = Dot(Normal, Pb - Pa)
22109 Separation:=Vector3Dot(Normal,Vector3Sub(Pb,Pa));
22110 if First or (MaxSeparation<Separation) then begin
22111 First:=false;
22112 MaxSeparation:=Separation;
22113 MaxIndexA:=IndexA;
22114 MaxIndexB:=IndexB;
22115 MaxNormal:=Normal;
22116 if MaxSeparation>0.0 then begin
22117 break;
22118 end;
22119 end;
22120
22121 end;
22122 end;
22123 end;
22124 OutEdgeQuery.IndexA:=MaxIndexA;
22125 OutEdgeQuery.IndexB:=MaxIndexB;
22126 OutEdgeQuery.Separation:=MaxSeparation;
22127 OutEdgeQuery.Normal:=MaxNormal;
22128 end;
22129 function GetEdgeContact(var CA,CB:TKraftVector3;const PA,QA,PB,QB:TKraftVector3):boolean; {$ifdef caninline}inline;{$endif}
22130 var DA,DB,r:TKraftVector3;
22131 a,e,f,c,b,d,TA,TB:TKraftScalar;
22132 begin
22133 DA:=Vector3Sub(QA,PA);
22134 DB:=Vector3Sub(QB,PB);
22135 r:=Vector3Sub(PA,PB);
22136 a:=Vector3LengthSquared(DA);
22137 e:=Vector3LengthSquared(DB);
22138 f:=Vector3Dot(DB,r);
22139 c:=Vector3Dot(DA,r);
22140 b:=Vector3Dot(DA,DB);
22141 d:=(a*e)-sqr(b);
22142 if (d<>0.0) and (e<>0.0) then begin
22143 TA:=Min(Max(((b*f)-(c*e))/d,0.0),1.0);
22144 TB:=Min(Max(((b*TA)+f)/e,0.0),1.0);
22145 CA:=Vector3Add(PA,Vector3ScalarMul(DA,TA));
22146 CB:=Vector3Add(PB,Vector3ScalarMul(DB,TB));
22147 result:=true;
22148 end else begin
22149 result:=false;
22150 end;
22151 end;
22152 function FindIncidentFaceIndex(const ReferenceHull:TKraftShapeConvexHull;const ReferenceFaceIndex:longint;const IncidentHull:TKraftShapeConvexHull):longint; {$ifdef caninline}inline;{$endif}
22153 var i:longint;
22154 MinDot,Dot:TKraftScalar;
22155 ReferenceNormal:TKraftVector3;
22156 begin
22157 ReferenceNormal:=Vector3TermMatrixMulTransposedBasis(Vector3TermMatrixMulBasis(ReferenceHull.fConvexHull.fFaces[ReferenceFaceIndex].Plane.Normal,
22158 ReferenceHull.fWorldTransform),
22159 IncidentHull.fWorldTransform);
22160 result:=-1;
22161 MinDot:=MAX_SCALAR;
22162 for i:=0 to IncidentHull.fConvexHull.fCountFaces-1 do begin
22163 Dot:=Vector3Dot(ReferenceNormal,IncidentHull.fConvexHull.fFaces[i].Plane.Normal);
22164 if MinDot>Dot then begin
22165 MinDot:=Dot;
22166 result:=i;
22167 end;
22168 end;
22169 end;
22170 procedure ClipFaceContactPoints(const ReferenceHull:TKraftShapeConvexHull;const ReferenceFaceIndex:longint;const IncidentHull:TKraftShapeConvexHull;const IncidentFaceIndex:longint;const Flip:boolean);
22171 var Contact:PKraftContact;
22172 ReferenceVertexIndex,OtherReferenceVertexIndex,IncidentVertexIndex,CliVertexIndex,ReferenceEdgeIndexOffset,IncidentEdgeIndexOffset:longint;
22173 ReferenceFace,IncidentFace:PKraftConvexHullFace;
22174 ClipVertex,PreviousClipVertex,CurrentClipVertex:PKraftClipVertex;
22175 PreviousClipVertexDistance,CurrentClipVertexDistance,Distance:TKraftScalar;
22176 ClipVertices:array[0..2] of TKraftClipVertexList;
22177 ReferencePoint:TKraftVector3;
22178 ReferenceWorldPlane,ReferenceEdgePlane:TKraftPlane;
22179 FeatureID:TKraftContactFeatureID;
22180 begin
22181
22182 ContactManager.fCountTemporaryContacts[ThreadIndex]:=0;
22183
22184 ReferenceFace:[email protected][ReferenceFaceIndex];
22185 ReferenceWorldPlane:=PlaneFastTransform(ReferenceFace^.Plane,ReferenceHull.fWorldTransform);
22186
22187 IncidentFace:[email protected][IncidentFaceIndex];
22188
22189 ClipVertices[0]:=ContactManager.fClipVertexLists[ThreadIndex,0];
22190 ClipVertices[0].Clear;
22191
22192 ReferenceEdgeIndexOffset:=ReferenceFace^.EdgeVertexOffset;
22193 IncidentEdgeIndexOffset:=IncidentFace^.EdgeVertexOffset;
22194
22195 for IncidentVertexIndex:=0 to IncidentFace^.CountVertices-1 do begin
22196 FeatureID.ElementA:=IncidentEdgeIndexOffset+IncidentVertexIndex;
22197 FeatureID.ElementB:=IncidentEdgeIndexOffset+(IncidentVertexIndex+1);
22198 ClipVertices[0].Add(Vector3TermMatrixMul(IncidentHull.fConvexHull.fVertices[IncidentFace^.Vertices[IncidentVertexIndex]].Position,IncidentHull.fWorldTransform),FeatureID);
22199 end;
22200
22201 {$ifdef DebugDraw}
22202 if (ContactManager.fPhysics.SingleThreaded or (ContactManager.fPhysics.fCountThreads<2)) and (ContactManager.fCountDebugClipVertexLists<length(ContactManager.fDebugClipVertexLists)) then begin
22203 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.r:=0.5;
22204 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.g:=1.0;
22205 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.b:=0.5;
22206 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.a:=1.0;
22207 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].Clear;
22208 for CliVertexIndex:=0 to ClipVertices[0].Count-1 do begin
22209 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].Add(ClipVertices[0].Vertices[CliVertexIndex]);
22210 end;
22211 inc(ContactManager.fCountDebugClipVertexLists);
22212 end;
22213 if (ContactManager.fPhysics.SingleThreaded or (ContactManager.fPhysics.fCountThreads<2)) and (ContactManager.fCountDebugClipVertexLists<length(ContactManager.fDebugClipVertexLists)) then begin
22214 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.r:=1.0;
22215 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.g:=0.5;
22216 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.b:=1.0;
22217 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.a:=1.0;
22218 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].Clear;
22219 for ReferenceVertexIndex:=0 to ReferenceFace^.CountVertices-1 do begin
22220 ReferencePoint:=Vector3TermMatrixMul(ReferenceHull.fConvexHull.fVertices[ReferenceFace^.Vertices[ReferenceVertexIndex]].Position,ReferenceHull.fWorldTransform);
22221 FeatureID.ElementA:=ReferenceEdgeIndexOffset+ReferenceVertexIndex;
22222 FeatureID.ElementB:=ReferenceEdgeIndexOffset+(ReferenceVertexIndex+1);
22223 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].Add(ReferencePoint,FeatureID);
22224 end;
22225 inc(ContactManager.fCountDebugClipVertexLists);
22226 end;
22227 {$endif}
22228
22229 ClipVertices[1]:=ContactManager.fClipVertexLists[ThreadIndex,1];
22230 ClipVertices[1].Clear;
22231
22232 OtherReferenceVertexIndex:=ReferenceFace^.CountVertices-1;
22233 for ReferenceVertexIndex:=0 to ReferenceFace^.CountVertices-1 do begin
22234 if ClipVertices[0].Count>=2 then begin
22235 ReferencePoint:=Vector3TermMatrixMul(ReferenceHull.fConvexHull.fVertices[ReferenceFace^.Vertices[ReferenceVertexIndex]].Position,ReferenceHull.fWorldTransform);
22236 ReferenceEdgePlane.Normal:=Vector3Neg(Vector3NormEx(Vector3Cross(ReferenceWorldPlane.Normal,Vector3Sub(ReferencePoint,Vector3TermMatrixMul(ReferenceHull.fConvexHull.fVertices[ReferenceFace^.Vertices[OtherReferenceVertexIndex]].Position,ReferenceHull.fWorldTransform)))));
22237 ReferenceEdgePlane.Distance:=-Vector3Dot(ReferenceEdgePlane.Normal,ReferencePoint);
22238 PreviousClipVertex:=@ClipVertices[0].Vertices[ClipVertices[0].Count-1];
22239 CurrentClipVertex:=@ClipVertices[0].Vertices[0];
22240 PreviousClipVertexDistance:=PlaneVectorDistance(ReferenceEdgePlane,PreviousClipVertex^.Position);
22241 for CliVertexIndex:=0 to ClipVertices[0].Count-1 do begin
22242 CurrentClipVertex:=@ClipVertices[0].Vertices[CliVertexIndex];
22243 CurrentClipVertexDistance:=PlaneVectorDistance(ReferenceEdgePlane,CurrentClipVertex^.Position);
22244 if PreviousClipVertexDistance<=0.0 then begin
22245 if CurrentClipVertexDistance<=0.0 then begin
22246 // Both vertices are behind the plane => keep CurrentClipVertex
22247 ClipVertices[1].Add(CurrentClipVertex^.Position,CurrentClipVertex^.FeatureID);
22248 end else begin
22249 // PreviousClipVertex is behind the plane, CurrentClipVertex is in front => intersection point
22250 FeatureID.ElementA:=CurrentClipVertex^.FeatureID.ElementA;
22251 FeatureID.ElementB:=ReferenceEdgeIndexOffset+ReferenceVertexIndex;
22252 ClipVertices[1].Add(Vector3Lerp(PreviousClipVertex^.Position,CurrentClipVertex^.Position,PreviousClipVertexDistance/(PreviousClipVertexDistance-CurrentClipVertexDistance)),FeatureID);
22253 end;
22254 end else if CurrentClipVertexDistance<=0.0 then begin
22255 // CurrentClipVertex is behind the plane, PreviousClipVertex is in front => intersection point
22256 FeatureID.ElementA:=ReferenceEdgeIndexOffset+ReferenceVertexIndex;
22257 FeatureID.ElementB:=CurrentClipVertex^.FeatureID.ElementA;
22258 ClipVertices[1].Add(Vector3Lerp(PreviousClipVertex^.Position,CurrentClipVertex^.Position,PreviousClipVertexDistance/(PreviousClipVertexDistance-CurrentClipVertexDistance)),FeatureID);
22259 ClipVertices[1].Add(CurrentClipVertex^.Position,CurrentClipVertex^.FeatureID);
22260 end;
22261 PreviousClipVertex:=CurrentClipVertex;
22262 PreviousClipVertexDistance:=CurrentClipVertexDistance;
22263 end;
22264 end;
22265 if ClipVertices[1].Count=0 then begin
22266 exit;
22267 end else begin
22268 ClipVertices[2]:=ClipVertices[0];
22269 ClipVertices[0]:=ClipVertices[1];
22270 ClipVertices[1]:=ClipVertices[2];
22271 ClipVertices[1].Clear;
22272 OtherReferenceVertexIndex:=ReferenceVertexIndex;
22273 end;
22274 end;
22275
22276 {$ifdef DebugDraw}
22277 if (ContactManager.fPhysics.SingleThreaded or (ContactManager.fPhysics.fCountThreads<2)) and (ContactManager.fCountDebugClipVertexLists<length(ContactManager.fDebugClipVertexLists)) then begin
22278 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.r:=0.5;
22279 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.g:=0.5;
22280 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.b:=1.0;
22281 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].fColor.a:=1.0;
22282 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].Clear;
22283 for CliVertexIndex:=0 to ClipVertices[0].Count-1 do begin
22284 ContactManager.fDebugClipVertexLists[ContactManager.fCountDebugClipVertexLists].Add(ClipVertices[0].Vertices[CliVertexIndex]);
22285 end;
22286 inc(ContactManager.fCountDebugClipVertexLists);
22287 end;
22288 {$endif}
22289
22290 for CliVertexIndex:=0 to ClipVertices[0].Count-1 do begin
22291 ClipVertex:=@ClipVertices[0].Vertices[CliVertexIndex];
22292 Distance:=PlaneVectorDistance(ReferenceWorldPlane,ClipVertex^.Position);
22293 if Distance<0.0 then begin
22294 if ContactManager.fCountTemporaryContacts[ThreadIndex]<MAX_TEMPORARY_CONTACTS then begin
22295 Contact:[email protected][ThreadIndex,ContactManager.fCountTemporaryContacts[ThreadIndex]];
22296 inc(ContactManager.fCountTemporaryContacts[ThreadIndex]);
22297 Contact^.Penetration:=Distance;
22298 if Flip then begin
22299 // Face BA contact, where B is the reference face and where A is the incident face
22300 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(ClipVertex^.Position,Shapes[0].fWorldTransform);
22301 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(Vector3Sub(ClipVertex^.Position,
22302 Vector3ScalarMul(ReferenceWorldPlane.Normal,
22303 Distance)),
22304 Shapes[1].fWorldTransform);
22305 Contact^.FeatureID.ElementA:=ClipVertex^.FeatureID.ElementB;
22306 Contact^.FeatureID.ElementB:=ClipVertex^.FeatureID.ElementA;
22307 end else begin
22308 // Face AB contact, where A is the reference face and where B is the incident face
22309 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(Vector3Sub(ClipVertex^.Position,
22310 Vector3ScalarMul(ReferenceWorldPlane.Normal,
22311 Distance)),
22312 Shapes[0].fWorldTransform);
22313 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(ClipVertex^.Position,Shapes[1].fWorldTransform);
22314 Contact^.FeatureID.ElementA:=ClipVertex^.FeatureID.ElementA;
22315 Contact^.FeatureID.ElementB:=ClipVertex^.FeatureID.ElementB;
22316 end;
22317 end else begin
22318 break;
22319 end;
22320 end;
22321 end;
22322
22323 end;
22324 var Physics:TKraft;
22325 Contact:PKraftContact;
22326 ReferenceFaceIndex,IncidentFaceIndex,Index,ValidContacts:longint;
22327 EdgeA,EdgeB:PKraftConvexHullEdge;
22328 PenetrationDepth:TKraftScalar;
22329 a0,a1,b0,b1,pa,pb,Normal:TKraftVector3;
22330 SolverContactManifold:TKraftSolverContactManifold;
22331 begin
22332
22333 Physics:=ContactManager.fPhysics;
22334
22335 LinearSlop:=Physics.fLinearSlop;
22336
22337 SeparationTolerance:=LinearSlop;
22338
22339 AbsoluteTolerance:=LinearSlop*0.5;
22340
22341 Manifold.CountContacts:=0;
22342
22343 Manifold.LocalRadius[0]:=0.0;
22344 Manifold.LocalRadius[1]:=0.0;
22345
22346 // Temporal coherence
22347 if Manifold.HaveData then begin
22348
22349 // If we detected a separating axis in the last frame we try this first in the current frame.
22350 // Chances are high it will still be a separating axis and we have an early out!
22351 if (Manifold.FaceQueryAB.Index>=0) and (Manifold.FaceQueryAB.Separation>SeparationTolerance) then begin
22352 if TestEarlyFaceDirection(ShapeA,ShapeB,Manifold.FaceQueryAB) then begin
22353 // Still existent seperating axis from last frame found, so exit!
22354 exit;
22355 end;
22356 end else if (Manifold.FaceQueryBA.Index>=0) and (Manifold.FaceQueryBA.Separation>SeparationTolerance) then begin
22357 if TestEarlyFaceDirection(ShapeB,ShapeA,Manifold.FaceQueryBA) then begin
22358 // Still existent seperating axis from last frame found, so exit!
22359 exit;
22360 end;
22361 end else if ((Manifold.EdgeQuery.IndexA>=0) and (Manifold.EdgeQuery.IndexB>=0)) and (Manifold.EdgeQuery.Separation>SeparationTolerance) then begin
22362 if TestEarlyEdgeDirection(ShapeA,ShapeB,Manifold.EdgeQuery) then begin
22363 // Still existent seperating axis from last frame found, so exit!
22364 exit;
22365 end;
22366 end;
22367
22368 // If we detected overlap in the last frame we try to rebuild the contact manifold from the last features again.
22369 // Chance are high they still realize the contact manifold and we can skip the whole SAT!
22370 if (OldContactManifoldType<>kcmtUnknown) and
22371 (OldManifoldCountContacts>0) and
22372 (Matrix4x4Difference(Manifold.RelativeTransform,
22373 Matrix4x4TermMulSimpleInverted(ShapeB.fWorldTransform,
22374 ShapeA.fWorldTransform))<TemporalCoherenceRelativeTransformTolerance) then begin
22375
22376 // Restore manifold meta data
22377 Manifold.ContactManifoldType:=OldContactManifoldType;
22378 Manifold.CountContacts:=OldManifoldCountContacts;
22379
22380 // Verify last frame manifold contacts
22381 GetSolverContactManifold(SolverContactManifold,ShapeA.fWorldTransform,ShapeB.fWorldTransform,kcpcmmTemporalCoherence);
22382 if SolverContactManifold.CountContacts>0 then begin
22383
22384 ValidContacts:=0;
22385 for Index:=0 to SolverContactManifold.CountContacts-1 do begin
22386 if SolverContactManifold.Contacts[Index].Separation<SeparationTolerance then begin
22387 inc(ValidContacts);
22388 end;
22389 end;
22390
22391 if ValidContacts=SolverContactManifold.CountContacts then begin
22392 // We've still valid contacts, so we can reuse the contact manifold directly from the last frame and we can skip the whole SAT
22393 // writeln(ContactManager.fPhysics.HighResolutionTimer.GetTime);
22394 exit;
22395 end;
22396
22397 end;
22398
22399 end;
22400
22401 // We must process a full seperating axis test, when there are no last frame contact manifold data yet, or when the
22402 // temporal coherence checks have failed
22403
22404 end;
22405
22406 // Seperating axis test
22407 begin
22408
22409 Manifold.ContactManifoldType:=kcmtUnknown;
22410 Manifold.CountContacts:=0;
22411
22412 Manifold.FaceQueryAB.Index:=-1;
22413 Manifold.FaceQueryAB.Separation:=MAX_SCALAR;
22414
22415 Manifold.FaceQueryBA.Index:=-1;
22416 Manifold.FaceQueryBA.Separation:=MAX_SCALAR;
22417
22418 Manifold.EdgeQuery.IndexA:=-1;
22419 Manifold.EdgeQuery.IndexB:=-1;
22420 Manifold.EdgeQuery.Separation:=MAX_SCALAR;
22421
22422 Manifold.HaveData:=true;
22423
22424 Manifold.RelativeTransform:=Matrix4x4TermMulSimpleInverted(ShapeB.fWorldTransform,ShapeA.fWorldTransform);
22425
22426 QueryFaceDirections(ShapeA,ShapeB,Manifold.FaceQueryAB);
22427 if Manifold.FaceQueryAB.Separation>SeparationTolerance then begin
22428 exit;
22429 end;
22430
22431 QueryFaceDirections(ShapeB,ShapeA,Manifold.FaceQueryBA);
22432 if Manifold.FaceQueryBA.Separation>SeparationTolerance then begin
22433 exit;
22434 end;
22435
22436 QueryEdgeDirections(ShapeA,ShapeB,Manifold.EdgeQuery);
22437 if Manifold.EdgeQuery.Separation>SeparationTolerance then begin
22438 exit;
22439 end;
22440
22441 end;
22442
22443 // Contact generation
22444 begin
22445
22446 ContactManager.fCountTemporaryContacts[ThreadIndex]:=0;
22447
22448 if ((Manifold.EdgeQuery.IndexA>=0) and
22449 (Manifold.EdgeQuery.IndexB>=0)) and
22450 (Manifold.EdgeQuery.Separation>((Max(Manifold.FaceQueryAB.Separation,Manifold.FaceQueryBA.Separation)*RelativeEdgeTolerance)+AbsoluteTolerance)) then begin
22451
22452 // Edge contact
22453
22454 Manifold.HaveData:=false;
22455
22456 EdgeA:[email protected][Manifold.EdgeQuery.IndexA];
22457 EdgeB:[email protected][Manifold.EdgeQuery.IndexB];
22458
22459 a0:=Vector3TermMatrixMul(ShapeA.fConvexHull.fVertices[EdgeA^.Vertices[0]].Position,ShapeA.fWorldTransform);
22460 a1:=Vector3TermMatrixMul(ShapeA.fConvexHull.fVertices[EdgeA^.Vertices[1]].Position,ShapeA.fWorldTransform);
22461 b0:=Vector3TermMatrixMul(ShapeB.fConvexHull.fVertices[EdgeB^.Vertices[0]].Position,ShapeB.fWorldTransform);
22462 b1:=Vector3TermMatrixMul(ShapeB.fConvexHull.fVertices[EdgeB^.Vertices[1]].Position,ShapeB.fWorldTransform);
22463
22464 if GetEdgeContact(pa,pb,a0,a1,b0,b1) then begin
22465 { Normal:=Vector3NormEx(Vector3Cross(Vector3Sub(a1,a0),Vector3Sub(b1,b0)));
22466 if Vector3Dot(Normal,Vector3Sub(ShapeB.GetCenter(ShapeB.fWorldTransform),ShapeA.GetCenter(ShapeA.fWorldTransform)))<0.0 then begin
22467 Normal:=Vector3Neg(Normal);
22468 end;
22469 //{}Normal:=Vector3TermMatrixMulBasis(Manifold.EdgeQuery.Normal,Shapes[1].fWorldTransform);
22470 PenetrationDepth:=Vector3Dot(Vector3Sub(pb,pa),Normal);
22471 if PenetrationDepth<0.0 then begin
22472 Manifold.ContactManifoldType:=kcmtEdges;
22473 Manifold.LocalNormal:=Vector3TermMatrixMulTransposedBasis(Normal,Shapes[0].fWorldTransform);
22474 Contact:[email protected][ThreadIndex,ContactManager.fCountTemporaryContacts[ThreadIndex]];
22475 inc(ContactManager.fCountTemporaryContacts[ThreadIndex]);
22476 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(pa,Shapes[0].fWorldTransform);
22477 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(pb,Shapes[1].fWorldTransform);
22478 Contact^.Penetration:=PenetrationDepth;
22479 Contact^.FeatureID.ElementA:=longword(Manifold.EdgeQuery.IndexA) or longword($80000000);
22480 Contact^.FeatureID.ElementB:=longword(Manifold.EdgeQuery.IndexB) or longword($80000000);
22481 end;
22482 end;
22483
22484 end else begin
22485
22486 // Face contact
22487
22488 if Manifold.FaceQueryBA.Separation>((Manifold.FaceQueryAB.Separation*RelativeFaceTolerance)+AbsoluteTolerance) then begin
22489
22490 // Face contact BA
22491
22492 ReferenceFaceIndex:=FindIncidentFaceIndex(ShapeB,Manifold.FaceQueryBA.Index,ShapeA);
22493 IncidentFaceIndex:=Manifold.FaceQueryBA.Index;
22494
22495 Manifold.ContactManifoldType:=kcmtFaceB;
22496 Manifold.LocalNormal:=ShapeB.fConvexHull.fFaces[Manifold.FaceQueryBA.Index].Plane.Normal;
22497
22498 ClipFaceContactPoints(ShapeB,IncidentFaceIndex,ShapeA,ReferenceFaceIndex,true);
22499
22500 end else begin
22501
22502 // Face contact AB
22503
22504 ReferenceFaceIndex:=Manifold.FaceQueryAB.Index;
22505 IncidentFaceIndex:=FindIncidentFaceIndex(ShapeA,Manifold.FaceQueryAB.Index,ShapeB);
22506
22507 Manifold.ContactManifoldType:=kcmtFaceA;
22508 Manifold.LocalNormal:=ShapeA.fConvexHull.fFaces[Manifold.FaceQueryAB.Index].Plane.Normal;
22509
22510 ClipFaceContactPoints(ShapeA,ReferenceFaceIndex,ShapeB,IncidentFaceIndex,false);
22511
22512 end;
22513
22514 end;
22515
22516 if ContactManager.fCountTemporaryContacts[ThreadIndex]>0 then begin
22517 // Contacts found, reduce these down to four contacts with the largest area
22518 Manifold.CountContacts:=ContactManager.ReduceContacts(pointer(@ContactManager.fTemporaryContacts[ThreadIndex,0]),ContactManager.fCountTemporaryContacts[ThreadIndex],pointer(@Manifold.Contacts[0]));
22519 end;
22520
22521 end;
22522
22523 end;
22524 procedure CollideWithMPRAndPerturbation(ShapeA,ShapeB:TKraftShape);
22525 const PerturbationAngleLimit=pi*0.125;
22526 pi2=pi*2.0;
22527 var PerturbationIterations,PreturbIteration,ContactIndex:longint;
22528 Contact:PKraftContact;
22529 PenetrationDepth,RadiusA,RadiusB,PerturbationAngle,IterationAngle:TKraftScalar;
22530 Normal,pa,pb,tpa,tpb,tp,v0,v1,SeperateNormalWorldSpace:TKraftVector3;
22531 PerturbationA,OK:boolean;
22532 UnperturbatedTransform,PerturbatedTransform:TKraftMatrix4x4;
22533 ShapeTransformMatrices:array[0..1] of PKraftMatrix4x4;
22534 PerturbationRotationQuaternion0,PerturbationRotationQuaternion1,PerturbationRotationQuaternion2,UnpreturbedQuaternion:TKraftQuaternion;
22535 begin
22536 Manifold.Persistent:=false;
22537
22538 PerturbationIterations:=ContactManager.fPhysics.fPerturbationIterations;
22539 if PerturbationIterations<MAX_CONTACTS then begin
22540 PerturbationIterations:=MAX_CONTACTS;
22541 end;
22542
22543 Manifold.CountContacts:=0;
22544
22545 if MPRPenetration(ShapeA,ShapeB,ShapeA.fWorldTransform,ShapeB.fWorldTransform,pa,pb,Normal,PenetrationDepth) then begin
22546
22547 Manifold.LocalNormal:=Vector3TermMatrixMulTransposedBasis(Vector3Neg(Normal),Shapes[1].fWorldTransform);
22548
22549 SeperateNormalWorldSpace:=Normal;
22550 GetPlaneSpace(SeperateNormalWorldSpace,v0,v1);
22551 if Vector3LengthSquared(v0)>EPSILON then begin
22552 RadiusA:=ShapeA.fAngularMotionDisc;
22553 RadiusB:=ShapeB.fAngularMotionDisc;
22554 if {$ifndef UseTriangleMeshFullPerturbation}assigned(MeshContactPair) or{$endif} (RadiusA<RadiusB) then begin
22555 PerturbationAngle:=Min(PerturbationAngleLimit,ContactManager.fPhysics.fContactBreakingThreshold/RadiusA);
22556 PerturbationA:=true;
22557 UnperturbatedTransform:=ShapeA.fWorldTransform;
22558 end else begin
22559 PerturbationAngle:=Min(PerturbationAngleLimit,ContactManager.fPhysics.fContactBreakingThreshold/RadiusB);
22560 PerturbationA:=false;
22561 UnperturbatedTransform:=ShapeB.fWorldTransform;
22562 end;
22563 UnpreturbedQuaternion:=QuaternionFromMatrix4x4(UnperturbatedTransform);
22564 end else begin
22565 Contact:[email protected][0];
22566 Manifold.CountContacts:=1;
22567 Manifold.ContactManifoldType:=kcmtPersistentImplicit;
22568 Manifold.LocalRadius[0]:=0.0;
22569 Manifold.LocalRadius[1]:=0.0;
22570 tp:=Vector3Avg(pa,pb);
22571 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(tp,Shapes[0].fWorldTransform);
22572 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(tp,Shapes[1].fWorldTransform);
22573 Contact^.Penetration:=-PenetrationDepth;
22574 Contact^.FeatureID:=CreateFeatureID(-1);
22575 exit;
22576 end;
22577
22578 ContactManager.fCountTemporaryContacts[ThreadIndex]:=0;
22579 for PreturbIteration:=0 to PerturbationIterations-1 do begin
22580 IterationAngle:=(PreturbIteration*pi2)/PerturbationIterations;
22581 PerturbationRotationQuaternion0:=QuaternionFromAxisAngle(v0,PerturbationAngle);
22582 PerturbationRotationQuaternion1:=QuaternionFromAxisAngle(SeperateNormalWorldSpace,IterationAngle);
22583 PerturbationRotationQuaternion2:=QuaternionMul(QuaternionMul(QuaternionInverse(PerturbationRotationQuaternion1),PerturbationRotationQuaternion0),PerturbationRotationQuaternion1);
22584 PerturbatedTransform:=QuaternionToMatrix4x4(QuaternionMul(UnpreturbedQuaternion,PerturbationRotationQuaternion2));
22585 if PerturbationA then begin
22586 PKraftVector3(pointer(@PerturbatedTransform[3,0]))^:=PKraftVector3(pointer(@ShapeA.fWorldTransform[3,0]))^;
22587 ShapeTransformMatrices[0]:=@PerturbatedTransform;
22588 ShapeTransformMatrices[1]:[email protected];
22589 end else begin
22590 PKraftVector3(pointer(@PerturbatedTransform[3,0]))^:=PKraftVector3(pointer(@ShapeB.fWorldTransform[3,0]))^;
22591 ShapeTransformMatrices[0]:[email protected];
22592 ShapeTransformMatrices[1]:=@PerturbatedTransform;
22593 end;
22594 if MPRPenetration(ShapeA,ShapeB,ShapeTransformMatrices[0]^,ShapeTransformMatrices[1]^,tpa,tpb,Normal,PenetrationDepth) then begin
22595 if PerturbationA then begin
22596 Vector3MatrixMul(tpa,Matrix4x4TermMul(Matrix4x4TermInverse(PerturbatedTransform),ShapeA.fWorldTransform));
22597 end else begin
22598 Vector3MatrixMul(tpb,Matrix4x4TermMul(Matrix4x4TermInverse(PerturbatedTransform),ShapeB.fWorldTransform));
22599 end;
22600 if ContactManager.fCountTemporaryContacts[ThreadIndex]<MAX_TEMPORARY_CONTACTS then begin
22601 OK:=true;
22602 tp:=Vector3Avg(tpa,tpb);
22603 v0:=Vector3TermMatrixMulInverted(tp,Shapes[0].fWorldTransform);
22604 for ContactIndex:=0 to ContactManager.fCountTemporaryContacts[ThreadIndex]-1 do begin
22605 Contact:[email protected][ThreadIndex,ContactIndex];
22606 if Vector3Dist(Contact^.LocalPoints[0],v0)<ContactManager.fPhysics.fContactBreakingThreshold then begin
22607 OK:=false;
22608 break;
22609 end;
22610 end;
22611 if OK then begin
22612 Contact:[email protected][ThreadIndex,ContactManager.fCountTemporaryContacts[ThreadIndex]];
22613 inc(ContactManager.fCountTemporaryContacts[ThreadIndex]);
22614 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(tp,Shapes[0].fWorldTransform);
22615 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(tp,Shapes[1].fWorldTransform);
22616 Contact^.Penetration:=-PenetrationDepth;
22617 Contact^.FeatureID:=CreateFeatureID(-1);
22618 end;
22619 end else begin
22620 break;
22621 end;
22622 end;
22623 end;
22624
22625 if ContactManager.fCountTemporaryContacts[ThreadIndex]>0 then begin
22626 Manifold.CountContacts:=ContactManager.ReduceContacts(pointer(@ContactManager.fTemporaryContacts[ThreadIndex,0]),ContactManager.fCountTemporaryContacts[ThreadIndex],pointer(@Manifold.Contacts[0]));
22627 Manifold.ContactManifoldType:=kcmtPersistentImplicit;
22628 Manifold.LocalRadius[0]:=0.0;
22629 Manifold.LocalRadius[1]:=0.0;
22630 end else begin
22631 Manifold.CountContacts:=0;
22632 end;
22633
22634 if Manifold.CountContacts=0 then begin
22635 Contact:[email protected][0];
22636 Manifold.CountContacts:=1;
22637 Manifold.ContactManifoldType:=kcmtPersistentImplicit;
22638 Manifold.LocalRadius[0]:=0.0;
22639 Manifold.LocalRadius[1]:=0.0;
22640 tp:=Vector3Avg(pa,pb);
22641 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(tp,Shapes[0].fWorldTransform);
22642 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(tp,Shapes[1].fWorldTransform);
22643 Contact^.Penetration:=-PenetrationDepth;
22644 Contact^.FeatureID:=CreateFeatureID(-1);
22645 end;
22646
22647 end;
22648 end;
22649 procedure ProcessPersistentContactManifold(ShapeA,ShapeB:TKraftShape);
22650 function FindReplacableContact(const NewContact:TKraftContact):longint;
22651 const Indices:array[0..3,0..2] of longint=((1,2,3),(0,2,3),(0,1,3),(0,1,2));
22652 var i,MaxPenetrationIndex:longint;
22653 MaxPenetration,Area,BiggestArea:single;
22654 Contact:PKraftContact;
22655 begin
22656 MaxPenetrationIndex:=-1;
22657 MaxPenetration:=NewContact.Penetration;
22658 for i:=0 to 3 do begin
22659 Contact:[email protected][i];
22660 if MaxPenetration<Contact^.Penetration then begin
22661 MaxPenetrationIndex:=i;
22662 MaxPenetration:=Contact^.Penetration;
22663 end;
22664 end;
22665 result:=-1;
22666 BiggestArea:=CalculateAreaFromFourPoints(Manifold.Contacts[0].LocalPoints[0],
22667 Manifold.Contacts[1].LocalPoints[0],
22668 Manifold.Contacts[2].LocalPoints[0],
22669 Manifold.Contacts[3].LocalPoints[0]);
22670 for i:=0 to 3 do begin
22671 if MaxPenetrationIndex<>i then begin
22672 Area:=CalculateAreaFromFourPoints(NewContact.LocalPoints[0],
22673 Manifold.Contacts[Indices[i,0]].LocalPoints[0],
22674 Manifold.Contacts[Indices[i,1]].LocalPoints[0],
22675 Manifold.Contacts[Indices[i,2]].LocalPoints[0]);
22676 if BiggestArea<Area then begin
22677 BiggestArea:=Area;
22678 result:=i;
22679 end;
22680 end;
22681 end;
22682 end;
22683 {$ifdef UseTriangleMeshFullPerturbation}
22684 procedure PreprocessTriangle;
22685 var Center:TKraftVector3;
22686 begin
22687 Center.x:=(ShapeTriangle.fConvexHull.fVertices[0].Position.x+ShapeTriangle.fConvexHull.fVertices[1].Position.x+ShapeTriangle.fConvexHull.fVertices[2].Position.x)/3.0;
22688 Center.y:=(ShapeTriangle.fConvexHull.fVertices[0].Position.y+ShapeTriangle.fConvexHull.fVertices[1].Position.y+ShapeTriangle.fConvexHull.fVertices[2].Position.y)/3.0;
22689 Center.z:=(ShapeTriangle.fConvexHull.fVertices[0].Position.z+ShapeTriangle.fConvexHull.fVertices[1].Position.z+ShapeTriangle.fConvexHull.fVertices[2].Position.z)/3.0;
22690 ShapeTriangle.fConvexHull.fVertices[0].Position:=Vector3Sub(ShapeTriangle.fConvexHull.fVertices[0].Position,Center);
22691 ShapeTriangle.fConvexHull.fVertices[1].Position:=Vector3Sub(ShapeTriangle.fConvexHull.fVertices[1].Position,Center);
22692 ShapeTriangle.fConvexHull.fVertices[2].Position:=Vector3Sub(ShapeTriangle.fConvexHull.fVertices[2].Position,Center);
22693 Center:=Vector3TermMatrixMulBasis(Center,ShapeTriangle.fWorldTransform);
22694 ShapeTriangle.fWorldTransform[3,0]:=ShapeTriangle.fWorldTransform[3,0]+Center.x;
22695 ShapeTriangle.fWorldTransform[3,1]:=ShapeTriangle.fWorldTransform[3,1]+Center.y;
22696 ShapeTriangle.fWorldTransform[3,2]:=ShapeTriangle.fWorldTransform[3,2]+Center.z;
22697 ShapeTriangle.UpdateData;
22698 end;
22699 {$endif}
22700 var WorldPositions,LocalPoints:array[0..1] of TKraftVector3;
22701 Normal,Point:TKraftVector3;
22702 PenetrationDepth,ShortestDistance,Distance:TKraftScalar;
22703 Nearest,Index,SubIndex:longint;
22704 Contact:PKraftContact;
22705 NewContact:TKraftContact;
22706 begin
22707 {$ifdef UseTriangleMeshFullPerturbation}
22708 if ShapeB=TriangleShape then begin
22709 PreprocessTriangle;
22710 end;
22711 {$endif}
22712 if ((OldManifoldCountContacts=0) or ContactManager.fPhysics.fAlwaysPerturbating) and (ContactManager.fPhysics.fPerturbationIterations>0) then begin
22713 CollideWithMPRAndPerturbation(ShapeA,ShapeB);
22714 end else begin
22715
22716 Manifold.CountContacts:=OldManifoldCountContacts;
22717 Manifold.Persistent:=true;
22718
22719 if MPRPenetration(ShapeA,ShapeB,ShapeA.fWorldTransform,ShapeB.fWorldTransform,WorldPositions[0],WorldPositions[1],Normal,PenetrationDepth) then begin
22720
22721 Point:=Vector3Avg(WorldPositions[0],WorldPositions[1]);
22722 WorldPositions[0]:=Point;
22723 WorldPositions[1]:=Point;{}
22724
22725 Normal:=Vector3Neg(Normal);
22726 PenetrationDepth:=-PenetrationDepth;
22727
22728 Manifold.LocalNormal:=Vector3TermMatrixMulTransposedBasis(Normal,Shapes[1].fWorldTransform);
22729
22730 // writeln(PenetrationDepth:1:8,' ',Vector3Dot(Manifold.Normal,Vector3Sub(WorldPositions[1],WorldPositions[0])):1:8);
22731
22732 // Find the nearest point to replace with it, if possible
22733 Nearest:=-1;
22734 LocalPoints[0]:=Vector3TermMatrixMulInverted(WorldPositions[0],Shapes[0].fWorldTransform);
22735 LocalPoints[1]:=Vector3TermMatrixMulInverted(WorldPositions[1],Shapes[1].fWorldTransform);
22736 if Manifold.CountContacts>0 then begin
22737 ShortestDistance:=ContactManager.fPhysics.fContactBreakingThreshold;
22738 for Index:=0 to Manifold.CountContacts-1 do begin
22739 Contact:[email protected][Index];
22740 Distance:=Vector3Dist(LocalPoints[0],Contact^.LocalPoints[0]);
22741 if ShortestDistance>Distance then begin
22742 ShortestDistance:=Distance;
22743 Nearest:=Index;
22744 end;
22745 end;
22746 end;
22747
22748 // Select contact data target
22749 if (Manifold.CountContacts=0) or (Nearest<0) then begin
22750 if Manifold.CountContacts=0 then begin
22751 // First contact
22752 Contact:[email protected][0];
22753 Manifold.CountContacts:=1;
22754 Manifold.ContactManifoldType:=kcmtPersistentImplicit;
22755 Manifold.LocalRadius[0]:=0.0;
22756 Manifold.LocalRadius[1]:=0.0;
22757 Contact^.FeatureID:=CreateFeatureID(1);
22758 end else begin
22759 // Non-first contact without old nearest found contact
22760 Contact:=@NewContact;
22761 end;
22762 Contact^.NormalImpulse:=0.0;
22763 Contact^.TangentImpulse[0]:=0.0;
22764 Contact^.TangentImpulse[1]:=0.0;
22765 Contact^.WarmStartState:=0;
22766 end else begin
22767 // Non-first contact with old nearest found contact, for replace it with this new contact
22768 Contact:[email protected][Nearest];
22769 Contact^.FeatureID:=CreateFeatureID(Nearest+1);
22770 end;
22771
22772 if assigned(Contact) then begin
22773 // Generate contact
22774 Contact^.LocalPoints[0]:=LocalPoints[0];
22775 Contact^.LocalPoints[1]:=LocalPoints[1];
22776 Contact^.Penetration:=PenetrationDepth;
22777 if Contact=@NewContact then begin
22778 // Replace old nearest found contact with this new contact
22779 Index:=Manifold.CountContacts;
22780 if Index>=MAX_CONTACTS then begin
22781 Index:=FindReplacableContact(NewContact);
22782 end else begin
22783 inc(Manifold.CountContacts);
22784 end;
22785 if (Index>=0) and (Index<MAX_CONTACTS) then begin
22786 Manifold.Contacts[Index]:=NewContact;
22787 Manifold.Contacts[Index].FeatureID:=CreateFeatureID(Index+1);
22788 end;
22789 end;
22790 end;
22791
22792 end;
22793
22794 // Contacts becomes invalid when signed distance exceeds margin (projected on contact normal direction) or
22795 // when relative movement orthogonal to normal exceeds margin
22796 Index:=0;
22797 while Index<Manifold.CountContacts do begin
22798 Contact:[email protected][Index];
22799
22800 // First refresh world-space positions
22801 WorldPositions[0]:=Vector3TermMatrixMul(Contact^.LocalPoints[0],Shapes[0].fWorldTransform);
22802 WorldPositions[1]:=Vector3TermMatrixMul(Contact^.LocalPoints[1],Shapes[1].fWorldTransform);
22803
22804 // Then check
22805 if (Vector3Dot(Normal,Vector3Sub(WorldPositions[0],WorldPositions[1]))>ContactManager.fPhysics.fContactBreakingThreshold) or
22806 (Vector3Dist(Vector3Add(WorldPositions[0],
22807 Vector3ScalarMul(Normal,Vector3Dot(Normal,
22808 Vector3Sub(WorldPositions[1],
22809 WorldPositions[0])))),
22810 WorldPositions[1])>ContactManager.fPhysics.fContactBreakingThreshold) then begin
22811 for SubIndex:=Index to Manifold.CountContacts-2 do begin
22812 Manifold.Contacts[SubIndex]:=Manifold.Contacts[SubIndex+1];
22813 end;
22814 dec(Manifold.CountContacts);
22815 end else begin
22816 inc(Index);
22817 end;
22818 end;
22819
22820 end;
22821
22822 if Manifold.CountContacts>0 then begin
22823 Manifold.ContactManifoldType:=kcmtPersistentImplicit;
22824 Manifold.LocalRadius[0]:=0.0;
22825 Manifold.LocalRadius[1]:=0.0;
22826 end else begin
22827 Manifold.ContactManifoldType:=kcmtUnknown;
22828 end;
22829
22830 end;
22831 procedure FindSpeculativeContacts(ShapeA,ShapeB:TKraftShape);
22832 var Index:longint;
22833 VelocityLength,t0,t1:TKraftScalar;
22834 Sweeps:array[0..1] of TKraftSweep;
22835 Transforms:array[0..1,0..1] of TKraftMatrix4x4;
22836 Contact:PKraftContact;
22837 Velocity:TKraftVector3;
22838 LinearVelocities:array[0..1] of TKraftVector3;
22839 GJK:TKraftGJK;
22840 begin
22841 if (Manifold.CountContacts=0) and SpeculativeContacts and (ContactManager.fPhysics.fContinuousMode=kcmSpeculativeContacts) and
22842 (assigned(Shapes[0].fRigidBody) and assigned(Shapes[1].fRigidBody)) and
22843 ((krbfContinuous in Shapes[0].fRigidBody.fFlags) or (krbfContinuous in Shapes[1].fRigidBody.fFlags)) then begin
22844 if not (((Shapes[0].fRigidBody.fRigidBodyType=krbtDYNAMIC) and (Shapes[1].fRigidBody.fRigidBodyType=krbtDYNAMIC)) and not
22845 (ContactManager.fPhysics.fContinuousAgainstDynamics and
22846 ((krbfContinuousAgainstDynamics in Shapes[0].fRigidBody.fFlags) or (krbfContinuousAgainstDynamics in Shapes[1].fRigidBody.fFlags)))) then begin
22847 for Index:=0 to 1 do begin
22848 Sweeps[Index]:=Shapes[Index].fRigidBody.fSweep;
22849 Sweeps[Index].c0:=Sweeps[Index].c;
22850 Sweeps[Index].q0:=Sweeps[Index].q;
22851 ContactManager.fPhysics.Integrate(Sweeps[Index].c,Sweeps[Index].q,Shapes[Index].fRigidBody.fLinearVelocity,Shapes[Index].fRigidBody.fAngularVelocity,DeltaTime);
22852 Sweeps[Index].Alpha0:=0.0;
22853 Transforms[Index,0]:=Matrix4x4TermMul(Shapes[Index].fLocalTransform,SweepTransform(Sweeps[Index],0.0));
22854 Transforms[Index,1]:=Matrix4x4TermMul(Shapes[Index].fLocalTransform,SweepTransform(Sweeps[Index],1.0));
22855 LinearVelocities[Index]:=Vector3Sub(Vector3TermMatrixMul(Vector3Origin,Transforms[Index,1]),Vector3TermMatrixMul(Vector3Origin,Transforms[Index,0]));
22856 end;
22857 Velocity:=Vector3Sub(LinearVelocities[0],LinearVelocities[1]);
22858 VelocityLength:=Vector3Length(Velocity);
22859 if VelocityLength>Max(1e-5,Min(ShapeA.fAngularMotionDisc,ShapeB.fAngularMotionDisc)*0.125) then begin
22860 if SweepSphereSphere(Vector3TermMatrixMul(ShapeA.fLocalCenterOfMass,Transforms[0,0]),
22861 Vector3TermMatrixMul(ShapeA.fLocalCenterOfMass,Transforms[0,1]),
22862 ShapeA.fShapeSphere.Radius,
22863 Vector3TermMatrixMul(ShapeB.fLocalCenterOfMass,Transforms[1,0]),
22864 Vector3TermMatrixMul(ShapeB.fLocalCenterOfMass,Transforms[1,1]),
22865 ShapeB.fShapeSphere.Radius,
22866 t0,
22867 t1) then begin
22868 GJK.CachedSimplex:[email protected];
22869 GJK.Simplex.Count:=0;
22870 GJK.Shapes[0]:=ShapeA;
22871 GJK.Shapes[1]:=ShapeB;
22872 GJK.Transforms[0]:[email protected];
22873 GJK.Transforms[1]:[email protected];
22874 GJK.UseRadii:=false;
22875 GJK.Run;
22876 if (GJK.Distance>0.0) and (GJK.Distance<(VelocityLength+EPSILON)) and not GJK.Failed then begin
22877 if MPRSweep(ShapeA,ShapeB,Sweeps[0],Sweeps[1]) then begin
22878 Manifold.ContactManifoldType:=kcmtSpeculative;
22879 Manifold.CountContacts:=1;
22880 Manifold.LocalNormal:=Vector3SafeNorm(Vector3TermMatrixMulTransposedBasis(Vector3Neg(GJK.Normal),Shapes[1].fWorldTransform));
22881 Contact:[email protected][0];
22882 Contact^.LocalPoints[0]:=Vector3TermMatrixMulInverted(GJK.ClosestPoints[0],Shapes[0].fWorldTransform);
22883 Contact^.LocalPoints[1]:=Vector3TermMatrixMulInverted(GJK.ClosestPoints[1],Shapes[1].fWorldTransform);
22884 Contact^.Penetration:=GJK.Distance;
22885 Contact^.FeatureID:=CreateFeatureID(-1);
22886 end;
22887 end;
22888 end;
22889 end;
22890 end;
22891 end;
22892 end;
22893 var Index,SubIndex:longint;
22894 ShapeA,ShapeB:TKraftShape;
22895 MeshShape:TKraftShapeMesh;
22896 HasContact:boolean;
22897 MeshTriangle:PKraftMeshTriangle;
22898 Contact,BestOldContact,OldContact:PKraftContact;
22899 BestContactDistance,ContactDistance:TKraftScalar;
22900 OldManifoldContacts:array[0..MAX_CONTACTS-1] of TKraftContact;
22901 begin
22902
22903 Flags:=Flags+[kcfEnabled];
22904
22905 OldManifoldCountContacts:=Manifold.CountContacts;
22906 OldContactManifoldType:=Manifold.ContactManifoldType;
22907 for Index:=0 to OldManifoldCountContacts-1 do begin
22908 OldManifoldContacts[Index]:=Manifold.Contacts[Index];
22909 end;
22910
22911 Manifold.ContactManifoldType:=kcmtUnknown;
22912
22913 Manifold.CountContacts:=0;
22914
22915 ShapeA:=Shapes[0];
22916 ShapeB:=Shapes[1];
22917
22918 if assigned(MeshContactPair) then begin
22919 if (ElementIndex>=0) and assigned(TriangleShape) and (ShapeB is TKraftShapeMesh) then begin
22920 MeshShape:=TKraftShapeMesh(ShapeB);
22921 ShapeB:=TriangleShape;
22922 ShapeTriangle:=TKraftShapeTriangle(TriangleShape);
22923 MeshTriangle:[email protected][ElementIndex];
22924 ShapeTriangle.fWorldTransform:=MeshShape.fWorldTransform;
22925 ShapeTriangle.fConvexHull.fVertices[0].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[0]];
22926 ShapeTriangle.fConvexHull.fVertices[1].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[1]];
22927 ShapeTriangle.fConvexHull.fVertices[2].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[2]];
22928 ShapeTriangle.UpdateData;
22929 end else begin
22930 exit;
22931 end;
22932 end;
22933
22934 HasContact:=false;
22935
22936 if (Shapes[0]<>Shapes[1]) and
22937 (Shapes[0].fRigidBody<>Shapes[1].fRigidBody) and
22938 (ksfCollision in Shapes[0].fFlags) and
22939 (ksfCollision in Shapes[1].fFlags) then begin
22940
22941 if ContactManager.fPhysics.fPersistentContactManifold then begin
22942
22943 // Incremental persistent contact manifold
22944 ProcessPersistentContactManifold(ShapeA,ShapeB);
22945
22946 end else begin
22947
22948 // Full one-shot contact manifold (default)
22949
22950 case ShapeA.fShapeType of
22951 kstSphere:begin
22952 case ShapeB.fShapeType of
22953 kstSphere:begin
22954 CollideSphereWithSphere(TKraftShapeSphere(ShapeA),TKraftShapeSphere(ShapeB));
22955 end;
22956 kstCapsule:begin
22957 CollideSphereWithCapsule(TKraftShapeSphere(ShapeA),TKraftShapeCapsule(ShapeB));
22958 end;
22959 kstConvexHull:begin
22960 CollideSphereWithConvexHull(TKraftShapeSphere(ShapeA),TKraftShapeConvexHull(ShapeB));
22961 end;
22962 kstBox:begin
22963 CollideSphereWithBox(TKraftShapeSphere(ShapeA),TKraftShapeBox(ShapeB));
22964 end;
22965 kstPlane:begin
22966 CollideSphereWithPlane(TKraftShapeSphere(ShapeA),TKraftShapePlane(ShapeB));
22967 end;
22968 kstTriangle:begin
22969 CollideSphereWithTriangle(TKraftShapeSphere(ShapeA),TKraftShapeTriangle(ShapeB));
22970 end;
22971 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
22972 end;
22973 end;
22974 kstCapsule:begin
22975 case ShapeB.fShapeType of
22976 kstCapsule:begin
22977 CollideCapsuleWithCapsule(TKraftShapeCapsule(ShapeA),TKraftShapeCapsule(ShapeB));
22978 end;
22979 kstConvexHull,kstBox,kstPlane,kstTriangle:begin
22980 CollideCapsuleWithConvexHull(TKraftShapeCapsule(ShapeA),TKraftShapeConvexHull(ShapeB));
22981 end;{}
22982 { kstConvexHull,kstBox,kstPlane:begin
22983 CollideCapsuleWithConvexHull(TKraftShapeCapsule(ShapeA),TKraftShapeConvexHull(ShapeB));
22984 end;
22985 kstTriangle:begin
22986 CollideCapsuleWithTriangle(TKraftShapeCapsule(ShapeA),TKraftShapeTriangle(ShapeB));
22987 end;{}
22988 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
22989 end;
22990 end;
22991 kstConvexHull,kstBox,kstPlane,kstTriangle:begin
22992 case ShapeB.fShapeType of
22993 kstConvexHull,kstBox,kstPlane,kstTriangle:begin
22994 CollideConvexHullWithConvexHull(TKraftShapeConvexHull(ShapeA),TKraftShapeConvexHull(ShapeB));
22995 end;
22996 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
22997 end;
22998 end;
22999 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
23000 end;
23001
23002 end;
23003
23004 if SpeculativeContacts then begin
23005 FindSpeculativeContacts(ShapeA,ShapeB);
23006 end;
23007
23008 if ((ksfSensor in Shapes[0].fFlags) or (ksfSensor in Shapes[1].fFlags)) or
23009 ((krbfSensor in RigidBodies[0].fFlags) or (krbfSensor in RigidBodies[1].fFlags)) then begin
23010
23011 HasContact:=Manifold.CountContacts>0;
23012
23013 Manifold.ContactManifoldType:=kcmtUnknown;
23014 Manifold.CountContacts:=0;
23015
23016 end else begin
23017
23018 HasContact:=Manifold.CountContacts>0;
23019
23020 if Manifold.Persistent then begin
23021
23022 for Index:=0 to Manifold.CountContacts-1 do begin
23023 Contact:[email protected][Index];
23024 Contact^.WarmStartState:=Max(Contact^.WarmStartState,Contact^.WarmStartState+1);
23025 end;
23026
23027 end else begin
23028
23029 for Index:=0 to Manifold.CountContacts-1 do begin
23030 Contact:[email protected][Index];
23031 BestOldContact:=nil;
23032 if Contact^.FeatureID.Key=-1 then begin
23033 BestContactDistance:=ContactManager.fPhysics.fContactBreakingThreshold;
23034 for SubIndex:=0 to OldManifoldCountContacts-1 do begin
23035 OldContact:=@OldManifoldContacts[SubIndex];
23036 ContactDistance:=Vector3Dist(Contact^.LocalPoints[0],OldContact^.LocalPoints[0]);
23037 if (OldContact^.FeatureID.Key=-1) and (BestContactDistance>ContactDistance) then begin
23038 BestContactDistance:=ContactDistance;
23039 BestOldContact:=OldContact;
23040 end;
23041 end;
23042 end else begin
23043 for SubIndex:=0 to OldManifoldCountContacts-1 do begin
23044 OldContact:=@OldManifoldContacts[SubIndex];
23045 if Contact^.FeatureID.Key=OldContact^.FeatureID.Key then begin
23046 BestOldContact:=OldContact;
23047 break;
23048 end;
23049 end;
23050 end;
23051 if assigned(BestOldContact) then begin
23052 Contact^.NormalImpulse:=BestOldContact^.NormalImpulse;
23053 Contact^.TangentImpulse[0]:=BestOldContact^.TangentImpulse[0];
23054 Contact^.TangentImpulse[1]:=BestOldContact^.TangentImpulse[1];
23055 Contact^.WarmStartState:=Max(BestOldContact^.WarmStartState,BestOldContact^.WarmStartState+1);
23056 end else begin
23057 Contact^.NormalImpulse:=0.0;
23058 Contact^.TangentImpulse[0]:=0.0;
23059 Contact^.TangentImpulse[1]:=0.0;
23060 Contact^.WarmStartState:=0;
23061 end;
23062 end;
23063 end;
23064
23065 end;
23066
23067 end;
23068
23069 if HasContact then begin
23070 if kcfColliding in Flags then begin
23071 Include(Flags,kcfWasColliding);
23072 end else begin
23073 Include(Flags,kcfColliding);
23074 end;
23075 end else begin
23076 if kcfColliding in Flags then begin
23077 Flags:=(Flags-[kcfColliding])+[kcfWasColliding];
23078 end else begin
23079 Exclude(Flags,kcfWasColliding);
23080 end;
23081 end;
23082
23083 {if ShapeB.fShapeType=kstPlane then begin
23084 writeln(ContactManager.fPhysics.HighResolutionTimer.GetTime:16,' ',Manifold.CountContacts:4);
23085 end;{}
23086
23087 end;
23088
23089 constructor TKraftMeshContactPair.Create(const AContactManager:TKraftContactManager);
23090 begin
23091 inherited Create;
23092
23093 fContactManager:=AContactManager;
23094
23095 if assigned(fContactManager.fMeshContactPairLast) then begin
23096 fContactManager.fMeshContactPairLast.fNext:=self;
23097 fPrevious:=fContactManager.fMeshContactPairLast;
23098 end else begin
23099 fContactManager.fMeshContactPairFirst:=self;
23100 fPrevious:=nil;
23101 end;
23102 fContactManager.fMeshContactPairLast:=self;
23103 fNext:=nil;
23104
23105 fHashBucket:=-1;
23106 fHashPrevious:=nil;
23107 fHashNext:=nil;
23108
23109 fIsOnFreeList:=false;
23110
23111 fFlags:=[];
23112
23113 inc(fContactManager.fCountMeshContactPairs);
23114
23115 fShapeConvex:=nil;
23116 fShapeMesh:=nil;
23117
23118 fRigidBodyConvex:=nil;
23119 fRigidBodyMesh:=nil;
23120
23121 end;
23122
23123 destructor TKraftMeshContactPair.Destroy;
23124 begin
23125
23126 RemoveFromHashTable;
23127
23128 if fIsOnFreeList then begin
23129 if assigned(fPrevious) then begin
23130 fPrevious.fNext:=fNext;
23131 end else if fContactManager.fMeshContactPairFirstFree=self then begin
23132 fContactManager.fMeshContactPairFirstFree:=fNext;
23133 end;
23134 if assigned(fNext) then begin
23135 fNext.fPrevious:=fPrevious;
23136 end else if fContactManager.fMeshContactPairLastFree=self then begin
23137 fContactManager.fMeshContactPairLastFree:=fPrevious;
23138 end;
23139 fPrevious:=nil;
23140 fNext:=nil;
23141 end else begin
23142 if assigned(fPrevious) then begin
23143 fPrevious.fNext:=fNext;
23144 end else if fContactManager.fMeshContactPairFirst=self then begin
23145 fContactManager.fMeshContactPairFirst:=fNext;
23146 end;
23147 if assigned(fNext) then begin
23148 fNext.fPrevious:=fPrevious;
23149 end else if fContactManager.fMeshContactPairLast=self then begin
23150 fContactManager.fMeshContactPairLast:=fPrevious;
23151 end;
23152 fPrevious:=nil;
23153 fNext:=nil;
23154 end;
23155
23156 dec(fContactManager.fCountMeshContactPairs);
23157
23158 inherited Destroy;
23159 end;
23160
23161 procedure TKraftMeshContactPair.MoveToFreeList;
23162 begin
23163 if not fIsOnFreeList then begin
23164
23165 fIsOnFreeList:=true;
23166
23167 if assigned(fPrevious) then begin
23168 fPrevious.fNext:=fNext;
23169 end else if fContactManager.fMeshContactPairFirst=self then begin
23170 fContactManager.fMeshContactPairFirst:=fNext;
23171 end;
23172 if assigned(fNext) then begin
23173 fNext.fPrevious:=fPrevious;
23174 end else if fContactManager.fMeshContactPairLast=self then begin
23175 fContactManager.fMeshContactPairLast:=fPrevious;
23176 end;
23177
23178 if assigned(fContactManager.fMeshContactPairLastFree) then begin
23179 fContactManager.fMeshContactPairLastFree.fNext:=self;
23180 fPrevious:=fContactManager.fMeshContactPairLastFree;
23181 end else begin
23182 fContactManager.fMeshContactPairFirstFree:=self;
23183 fPrevious:=nil;
23184 end;
23185 fContactManager.fMeshContactPairLastFree:=self;
23186 fNext:=nil;
23187
23188 end;
23189 end;
23190
23191 procedure TKraftMeshContactPair.MoveFromFreeList;
23192 begin
23193 if fIsOnFreeList then begin
23194
23195 fIsOnFreeList:=false;
23196
23197 fFlags:=[];
23198
23199 if assigned(fPrevious) then begin
23200 fPrevious.fNext:=fNext;
23201 end else if fContactManager.fMeshContactPairFirstFree=self then begin
23202 fContactManager.fMeshContactPairFirstFree:=fNext;
23203 end;
23204 if assigned(fNext) then begin
23205 fNext.fPrevious:=fPrevious;
23206 end else if fContactManager.fMeshContactPairLastFree=self then begin
23207 fContactManager.fMeshContactPairLastFree:=fPrevious;
23208 end;
23209
23210 if assigned(fContactManager.fMeshContactPairLast) then begin
23211 fContactManager.fMeshContactPairLast.fNext:=self;
23212 fPrevious:=fContactManager.fMeshContactPairLast;
23213 end else begin
23214 fContactManager.fMeshContactPairFirst:=self;
23215 fPrevious:=nil;
23216 end;
23217 fContactManager.fMeshContactPairLast:=self;
23218 fNext:=nil;
23219
23220 end;
23221 end;
23222
23223 procedure TKraftMeshContactPair.AddToHashTable; {$ifdef caninline}inline;{$endif}
23224 var HashTableBucket:PKraftMeshContactPairHashTableBucket;
23225 begin
23226 if fHashBucket<0 then begin
23227 fHashBucket:=HashTwoPointers(fShapeConvex,fShapeMesh) and high(TKraftMeshContactPairHashTable);
23228 HashTableBucket:[email protected][fHashBucket];
23229 if assigned(HashTableBucket^.First) then begin
23230 HashTableBucket^.First.fHashPrevious:=self;
23231 fHashNext:=HashTableBucket^.First;
23232 end else begin
23233 HashTableBucket^.Last:=self;
23234 fHashNext:=nil;
23235 end;
23236 HashTableBucket^.First:=self;
23237 fHashPrevious:=nil;
23238 end;
23239 end;
23240
23241 procedure TKraftMeshContactPair.RemoveFromHashTable; {$ifdef caninline}inline;{$endif}
23242 var HashTableBucket:PKraftMeshContactPairHashTableBucket;
23243 begin
23244 if fHashBucket>=0 then begin
23245 HashTableBucket:[email protected][fHashBucket];
23246 fHashBucket:=-1;
23247 if assigned(fHashPrevious) then begin
23248 fHashPrevious.fHashNext:=fHashNext;
23249 end else if HashTableBucket^.First=self then begin
23250 HashTableBucket^.First:=fHashNext;
23251 end;
23252 if assigned(fHashNext) then begin
23253 fHashNext.fHashPrevious:=fHashPrevious;
23254 end else if HashTableBucket^.Last=self then begin
23255 HashTableBucket^.Last:=fHashPrevious;
23256 end;
23257 fHashPrevious:=nil;
23258 fHashNext:=nil;
23259 end;
23260 end;
23261
23262 procedure TKraftMeshContactPair.Query;
23263 var SkipListNodeIndex,TriangleIndex:longint;
23264 SkipListNode:PKraftMeshSkipListNode;
23265 Triangle:PKraftMeshTriangle;
23266 begin
23267 SkipListNodeIndex:=0;
23268 while SkipListNodeIndex<TKraftShapeMesh(fShapeMesh).fMesh.fCountSkipListNodes do begin
23269 SkipListNode:=@TKraftShapeMesh(fShapeMesh).fMesh.fSkipListNodes[SkipListNodeIndex];
23270 if AABBIntersect(SkipListNode^.AABB,fConvexAABBInMeshLocalSpace) then begin
23271 TriangleIndex:=SkipListNode^.TriangleIndex;
23272 while TriangleIndex>=0 do begin
23273 Triangle:=@TKraftShapeMesh(fShapeMesh).fMesh.fTriangles[TriangleIndex];
23274 if AABBIntersect(Triangle^.AABB,fConvexAABBInMeshLocalSpace) and not fContactManager.HasDuplicateContact(fRigidBodyConvex,fRigidBodyMesh,fShapeConvex,fShapeMesh,TriangleIndex) then begin
23275 fContactManager.AddConvexContact(fRigidBodyConvex,fRigidBodyMesh,fShapeConvex,fShapeMesh,TriangleIndex,self);
23276 end;
23277 TriangleIndex:=Triangle^.Next;
23278 end;
23279 inc(SkipListNodeIndex);
23280 end else begin
23281 SkipListNodeIndex:=SkipListNode^.SkipToNodeIndex;
23282 end;
23283 end;
23284 end;
23285
23286 procedure TKraftMeshContactPair.Update;
23287 var NewConvexAABBInMeshLocalSpace:TKraftAABB;
23288 Transform:TKraftMatrix4x4;
23289 Displacement,BoundsExpansion:TKraftVector3;
23290 begin
23291 Transform:=Matrix4x4TermMulSimpleInverted(fShapeConvex.fWorldTransform,fShapeMesh.fWorldTransform);
23292 NewConvexAABBInMeshLocalSpace:=AABBTransform(fShapeConvex.fShapeAABB,Transform);
23293 if not AABBContains(fConvexAABBInMeshLocalSpace,NewConvexAABBInMeshLocalSpace) then begin
23294 Displacement:=Vector3TermMatrixMulBasis(Vector3ScalarMul(fRigidBodyConvex.fLinearVelocity,fRigidBodyConvex.fPhysics.fWorldDeltaTime),Transform);
23295 BoundsExpansion:=Vector3ScalarMul(Vector3(fShapeConvex.fAngularMotionDisc,fShapeConvex.fAngularMotionDisc,fShapeConvex.fAngularMotionDisc),Vector3Length(fRigidBodyConvex.fAngularVelocity)*fRigidBodyConvex.fPhysics.fWorldDeltaTime);
23296 fConvexAABBInMeshLocalSpace:=AABBStretch(NewConvexAABBInMeshLocalSpace,Displacement,BoundsExpansion);
23297 Query;
23298 end;
23299 end;
23300
23301 constructor TKraftContactManager.Create(const APhysics:TKraft);
23302 var ThreadIndex:longint;
23303 begin
23304 inherited Create;
23305
23306 fPhysics:=APhysics;
23307
23308 fContactPairFirst:=nil;
23309 fContactPairLast:=nil;
23310
23311 fFreeContactPairs:=nil;
23312
23313 fCountContactPairs:=0;
23314
23315 fMeshContactPairFirst:=nil;
23316 fMeshContactPairLast:=nil;
23317
23318 fMeshContactPairFirstFree:=nil;
23319 fMeshContactPairLastFree:=nil;
23320
23321 fCountMeshContactPairs:=0;
23322
23323 fOnContactBegin:=nil;
23324 fOnContactEnd:=nil;
23325 fOnContactStay:=nil;
23326
23327 fOnCanCollide:=nil;
23328
23329 for ThreadIndex:=0 to MAX_THREADS-1 do begin
23330 fClipVertexLists[ThreadIndex,0]:=TKraftClipVertexList.Create;
23331 fClipVertexLists[ThreadIndex,1]:=TKraftClipVertexList.Create;
23332 end;
23333
23334 {$ifdef DebugDraw}
23335 fCountDebugClipVertexLists:=0;
23336 for ThreadIndex:=0 to high(fDebugClipVertexLists) do begin
23337 fDebugClipVertexLists[ThreadIndex]:=TKraftClipVertexList.Create;
23338 end;
23339 {$endif}
23340
23341 fActiveContactPairs:=nil;
23342 SetLength(fActiveContactPairs,256);
23343 fCountActiveContactPairs:=0;
23344
23345 FillChar(fConvexConvexContactPairHashTable,SizeOf(TKraftContactPairHashTable),AnsiChar(#0));
23346
23347 FillChar(fConvexMeshTriangleContactPairHashTable,SizeOf(TKraftContactPairHashTable),AnsiChar(#0));
23348
23349 FillChar(fMeshContactPairHashTable,SizeOf(TKraftMeshContactPairHashTable),AnsiChar(#0));
23350
23351 end;
23352
23353 destructor TKraftContactManager.Destroy;
23354 var ThreadIndex:longint;
23355 NextContactPair:PKraftContactPair;
23356 begin
23357
23358 SetLength(fActiveContactPairs,0);
23359
23360 while assigned(fContactPairFirst) do begin
23361 RemoveContact(fContactPairFirst);
23362 end;
23363
23364 while assigned(fFreeContactPairs) do begin
23365 NextContactPair:=fFreeContactPairs^.Next;
23366 FreeMem(fFreeContactPairs);
23367 fFreeContactPairs:=NextContactPair;
23368 end;
23369
23370 while assigned(fMeshContactPairFirst) do begin
23371 fMeshContactPairFirst.Free;
23372 end;
23373
23374 while assigned(fMeshContactPairFirstFree) do begin
23375 fMeshContactPairFirstFree.Free;
23376 end;
23377
23378 //Assert(CountContactPairs=0);
23379 //Assert(fCountMeshContactPairs=0);
23380
23381 for ThreadIndex:=0 to MAX_THREADS-1 do begin
23382 FreeAndNil(fClipVertexLists[ThreadIndex,0]);
23383 FreeAndNil(fClipVertexLists[ThreadIndex,1]);
23384 end;
23385
23386 {$ifdef DebugDraw}
23387 for ThreadIndex:=0 to high(fDebugClipVertexLists) do begin
23388 fDebugClipVertexLists[ThreadIndex].Free;
23389 end;
23390 {$endif}
23391
23392 inherited Destroy;
23393 end;
23394
23395 function TKraftContactManager.HasDuplicateContact(const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AShapeA,AShapeB:TKraftShape;const AElementIndex:longint=-1):boolean;
23396 var HashTableBucket:PKraftContactPairHashTableBucket;
23397 ContactPair:PKraftContactPair;
23398 begin
23399 result:=false;
23400 if AElementIndex<0 then begin
23401 if ptruint(AShapeA)<ptruint(AShapeB) then begin
23402 HashTableBucket:=@fConvexConvexContactPairHashTable[HashTwoPointers(AShapeA,AShapeB) and high(TKraftContactPairHashTable)];
23403 end else begin
23404 HashTableBucket:=@fConvexConvexContactPairHashTable[HashTwoPointers(AShapeB,AShapeA) and high(TKraftContactPairHashTable)];
23405 end;
23406 ContactPair:=HashTableBucket^.First;
23407 while assigned(ContactPair) do begin
23408 if ((ContactPair^.Shapes[0]=AShapeA) and (ContactPair^.Shapes[1]=AShapeB)) or
23409 ((ContactPair^.Shapes[0]=AShapeB) and (ContactPair^.Shapes[1]=AShapeA)) then begin
23410 result:=true;
23411 exit;
23412 end;
23413 ContactPair:=ContactPair^.Next;
23414 end;
23415 end else begin
23416 if ptruint(AShapeA)<ptruint(AShapeB) then begin
23417 HashTableBucket:=@fConvexMeshTriangleContactPairHashTable[HashTwoPointersAndOneLongword(AShapeA,AShapeB,AElementIndex) and high(TKraftContactPairHashTable)];
23418 end else begin
23419 HashTableBucket:=@fConvexMeshTriangleContactPairHashTable[HashTwoPointersAndOneLongword(AShapeB,AShapeA,AElementIndex) and high(TKraftContactPairHashTable)];
23420 end;
23421 ContactPair:=HashTableBucket^.First;
23422 while assigned(ContactPair) do begin
23423 if (ContactPair^.ElementIndex=AElementIndex) and
23424 (((ContactPair^.Shapes[0]=AShapeA) and (ContactPair^.Shapes[1]=AShapeB)) or
23425 ((ContactPair^.Shapes[0]=AShapeB) and (ContactPair^.Shapes[1]=AShapeA))) then begin
23426 result:=true;
23427 exit;
23428 end;
23429 ContactPair:=ContactPair^.Next;
23430 end;
23431 end;
23432 end;
23433
23434 procedure TKraftContactManager.AddConvexContact(const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AShapeA,AShapeB:TKraftShape;const AElementIndex:longint=-1;const AMeshContactPair:TKraftMeshContactPair=nil);
23435 var i:longint;
23436 ContactPair:PKraftContactPair;
23437 HashTableBucket:PKraftContactPairHashTableBucket;
23438 begin
23439
23440 if assigned(fFreeContactPairs) then begin
23441 ContactPair:=fFreeContactPairs;
23442 fFreeContactPairs:=ContactPair^.Next;
23443 end else begin
23444 GetMem(ContactPair,SizeOf(TKraftContactPair));
23445 end;
23446 FillChar(ContactPair^,SizeOf(TKraftContactPair),AnsiChar(#0));
23447
23448 ContactPair^.Manifold.HaveData:=false;
23449
23450 ContactPair^.Manifold.Persistent:=false;
23451
23452 ContactPair^.Manifold.GJKCachedSimplex.Count:=0;
23453
23454 ContactPair^.Island:=nil;
23455
23456 ContactPair^.Shapes[0]:=AShapeA;
23457 ContactPair^.Shapes[1]:=AShapeB;
23458
23459 ContactPair^.ElementIndex:=AElementIndex;
23460
23461 if AElementIndex<0 then begin
23462 if ptruint(AShapeA)<ptruint(AShapeB) then begin
23463 ContactPair^.HashBucket:=HashTwoPointers(AShapeA,AShapeB) and high(TKraftContactPairHashTable);
23464 end else begin
23465 ContactPair^.HashBucket:=HashTwoPointers(AShapeB,AShapeA) and high(TKraftContactPairHashTable);
23466 end;
23467 HashTableBucket:=@fConvexConvexContactPairHashTable[ContactPair^.HashBucket];
23468 end else begin
23469 if ptruint(AShapeA)<ptruint(AShapeB) then begin
23470 ContactPair^.HashBucket:=HashTwoPointersAndOneLongword(AShapeA,AShapeB,AElementIndex) and high(TKraftContactPairHashTable);
23471 end else begin
23472 ContactPair^.HashBucket:=HashTwoPointersAndOneLongword(AShapeB,AShapeA,AElementIndex) and high(TKraftContactPairHashTable);
23473 end;
23474 HashTableBucket:=@fConvexMeshTriangleContactPairHashTable[ContactPair^.HashBucket];
23475 end;
23476 if assigned(HashTableBucket^.First) then begin
23477 HashTableBucket^.First.HashPrevious:=ContactPair;
23478 ContactPair^.HashNext:=HashTableBucket^.First;
23479 end else begin
23480 HashTableBucket^.Last:=ContactPair;
23481 ContactPair^.HashNext:=nil;
23482 end;
23483 HashTableBucket^.First:=ContactPair;
23484 ContactPair^.HashPrevious:=nil;
23485
23486 ContactPair^.MeshContactPair:=AMeshContactPair;
23487
23488 ContactPair^.RigidBodies[0]:=ARigidBodyA;
23489 ContactPair^.RigidBodies[1]:=ARigidBodyB;
23490
23491 ContactPair^.Manifold.CountContacts:=0;
23492
23493 for i:=low(ContactPair^.Manifold.Contacts) to high(ContactPair^.Manifold.Contacts) do begin
23494 ContactPair^.Manifold.Contacts[i].WarmStartState:=0;
23495 end;
23496
23497 ContactPair^.Flags:=[kcfEnabled];
23498
23499 ContactPair^.Friction:=sqrt(AShapeA.fFriction*AShapeB.fFriction);
23500
23501 ContactPair^.Restitution:=max(AShapeA.fRestitution,AShapeB.fRestitution);
23502
23503 if assigned(fContactPairLast) then begin
23504 ContactPair^.Previous:=fContactPairLast;
23505 fContactPairLast^.Next:=ContactPair;
23506 end else begin
23507 ContactPair^.Previous:=nil;
23508 fContactPairFirst:=ContactPair;
23509 end;
23510 ContactPair^.Next:=nil;
23511 fContactPairLast:=ContactPair;
23512
23513 ContactPair^.Edges[0].OtherRigidBody:=ARigidBodyB;
23514 ContactPair^.Edges[0].ContactPair:=ContactPair;
23515
23516 if assigned(ARigidBodyA.fContactPairEdgeLast) then begin
23517 ContactPair^.Edges[0].Previous:=ARigidBodyA.fContactPairEdgeLast;
23518 ARigidBodyA.fContactPairEdgeLast^.Next:=@ContactPair^.Edges[0];
23519 end else begin
23520 ContactPair^.Edges[0].Previous:=nil;
23521 ARigidBodyA.fContactPairEdgeFirst:=@ContactPair^.Edges[0];
23522 end;
23523 ContactPair^.Edges[0].Next:=nil;
23524 ARigidBodyA.fContactPairEdgeLast:=@ContactPair^.Edges[0];
23525
23526 ContactPair^.Edges[1].OtherRigidBody:=ARigidBodyA;
23527 ContactPair^.Edges[1].ContactPair:=ContactPair;
23528
23529 if assigned(ARigidBodyB.fContactPairEdgeLast) then begin
23530 ContactPair^.Edges[1].Previous:=ARigidBodyB.fContactPairEdgeLast;
23531 ARigidBodyB.fContactPairEdgeLast^.Next:=@ContactPair^.Edges[1];
23532 end else begin
23533 ContactPair^.Edges[1].Previous:=nil;
23534 ARigidBodyB.fContactPairEdgeFirst:=@ContactPair^.Edges[1];
23535 end;
23536 ContactPair^.Edges[1].Next:=nil;
23537 ARigidBodyB.fContactPairEdgeLast:=@ContactPair^.Edges[1];
23538
23539 if not ((ksfSensor in AShapeA.Flags) or (ksfSensor in AShapeB.Flags)) then begin
23540 ARigidBodyB.SetToAwake;
23541 ARigidBodyA.SetToAwake;
23542 end;
23543
23544 inc(fCountContactPairs);
23545
23546 end;
23547
23548 procedure TKraftContactManager.AddMeshContact(const ARigidBodyConvex,ARigidBodyMesh:TKraftRigidBody;const AShapeConvex,AShapeMesh:TKraftShape);
23549 var HashTableBucket:PKraftMeshContactPairHashTableBucket;
23550 MeshContactPair:TKraftMeshContactPair;
23551 Transform:TKraftMatrix4x4;
23552 Displacement,BoundsExpansion:TKraftVector3;
23553 begin
23554
23555 HashTableBucket:=@fMeshContactPairHashTable[HashTwoPointers(AShapeConvex,AShapeMesh) and high(TKraftMeshContactPairHashTable)];
23556 MeshContactPair:=HashTableBucket.First;
23557 while assigned(MeshContactPair) do begin
23558 if (MeshContactPair.fShapeConvex=AShapeConvex) and (MeshContactPair.fShapeMesh=AShapeMesh) then begin
23559 exit;
23560 end;
23561 MeshContactPair:=MeshContactPair.fHashNext;
23562 end;
23563
23564 if assigned(fMeshContactPairFirstFree) then begin
23565 MeshContactPair:=fMeshContactPairFirstFree;
23566 MeshContactPair.MoveFromFreeList;
23567 end else begin
23568 MeshContactPair:=TKraftMeshContactPair.Create(self);
23569 end;
23570
23571 MeshContactPair.fRigidBodyConvex:=ARigidBodyConvex;
23572 MeshContactPair.fRigidBodyMesh:=ARigidBodyMesh;
23573
23574 MeshContactPair.fShapeConvex:=AShapeConvex;
23575 MeshContactPair.fShapeMesh:=AShapeMesh;
23576
23577 MeshContactPair.AddToHashTable;
23578
23579 Transform:=Matrix4x4TermMulSimpleInverted(MeshContactPair.fShapeConvex.fWorldTransform,MeshContactPair.fShapeMesh.fWorldTransform);
23580 Displacement:=Vector3TermMatrixMulBasis(Vector3ScalarMul(MeshContactPair.fRigidBodyConvex.fLinearVelocity,MeshContactPair.fRigidBodyConvex.fPhysics.fWorldDeltaTime),Transform);
23581 BoundsExpansion:=Vector3ScalarMul(Vector3(MeshContactPair.fShapeConvex.fAngularMotionDisc,MeshContactPair.fShapeConvex.fAngularMotionDisc,MeshContactPair.fShapeConvex.fAngularMotionDisc),Vector3Length(MeshContactPair.fRigidBodyConvex.fAngularVelocity)*MeshContactPair.fRigidBodyConvex.fPhysics.fWorldDeltaTime);
23582 MeshContactPair.fConvexAABBInMeshLocalSpace:=AABBStretch(AABBTransform(MeshContactPair.fShapeConvex.fShapeAABB,Transform),Displacement,BoundsExpansion);
23583
23584 MeshContactPair.Query;
23585
23586 end;
23587
23588 procedure TKraftContactManager.AddContact(const AShapeA,AShapeB:TKraftShape);
23589 var RigidBodyA,RigidBodyB:TKraftRigidBody;
23590 begin
23591
23592 RigidBodyA:=AShapeA.fRigidBody;
23593 RigidBodyB:=AShapeB.fRigidBody;
23594
23595 if (not RigidBodyA.CanCollideWith(RigidBodyB)) or
23596 (assigned(fOnCanCollide) and not fOnCanCollide(AShapeA,AShapeB)) then begin
23597 exit;
23598 end;
23599
23600 if (ksfCollision in AShapeA.fFlags) and
23601 (ksfCollision in AShapeB.fFlags) then begin
23602
23603 if AShapeA.fIsMesh then begin
23604
23605 AddMeshContact(RigidBodyB,RigidBodyA,AShapeB,AShapeA);
23606
23607 end else if AShapeB.fIsMesh then begin
23608
23609 AddMeshContact(RigidBodyA,RigidBodyB,AShapeA,AShapeB);
23610
23611 end else begin
23612
23613 if not HasDuplicateContact(RigidBodyA,RigidBodyB,AShapeA,AShapeB,-1) then begin
23614 AddConvexContact(RigidBodyA,RigidBodyB,AShapeA,AShapeB,-1);
23615 end;
23616
23617 end;
23618
23619 end;
23620
23621 end;
23622
23623 procedure TKraftContactManager.RemoveContact(AContactPair:PKraftContactPair);
23624 var RigidBodyA,RigidBodyB:TKraftRigidBody;
23625 HashTableBucket:PKraftContactPairHashTableBucket;
23626 begin
23627
23628 if AContactPair^.ElementIndex<0 then begin
23629 HashTableBucket:=@fConvexConvexContactPairHashTable[AContactPair^.HashBucket];
23630 end else begin
23631 HashTableBucket:=@fConvexMeshTriangleContactPairHashTable[AContactPair^.HashBucket];
23632 end;
23633 AContactPair^.HashBucket:=-1;
23634 if assigned(AContactPair^.HashPrevious) then begin
23635 AContactPair^.HashPrevious^.HashNext:=AContactPair^.HashNext;
23636 end else if HashTableBucket^.First=AContactPair then begin
23637 HashTableBucket^.First:=AContactPair^.HashNext;
23638 end;
23639 if assigned(AContactPair^.HashNext) then begin
23640 AContactPair^.HashNext^.HashPrevious:=AContactPair^.HashPrevious;
23641 end else if HashTableBucket^.Last=AContactPair then begin
23642 HashTableBucket^.Last:=AContactPair^.HashPrevious;
23643 end;
23644 AContactPair^.HashPrevious:=nil;
23645 AContactPair^.HashNext:=nil;
23646
23647 RigidBodyA:=AContactPair.Shapes[0].fRigidBody;
23648 RigidBodyB:=AContactPair.Shapes[1].fRigidBody;
23649
23650 if assigned(AContactPair^.Edges[0].Previous) then begin
23651 AContactPair^.Edges[0].Previous^.Next:=AContactPair^.Edges[0].Next;
23652 end else if RigidBodyA.fContactPairEdgeFirst=@AContactPair^.Edges[0] then begin
23653 RigidBodyA.fContactPairEdgeFirst:=AContactPair^.Edges[0].Next;
23654 end;
23655 if assigned(AContactPair^.Edges[0].Next) then begin
23656 AContactPair^.Edges[0].Next^.Previous:=AContactPair^.Edges[0].Previous;
23657 end else if RigidBodyA.fContactPairEdgeLast=@AContactPair^.Edges[0] then begin
23658 RigidBodyA.fContactPairEdgeLast:=AContactPair^.Edges[0].Previous;
23659 end;
23660 AContactPair^.Edges[0].Previous:=nil;
23661 AContactPair^.Edges[0].Next:=nil;
23662
23663 if assigned(AContactPair^.Edges[1].Previous) then begin
23664 AContactPair^.Edges[1].Previous^.Next:=AContactPair^.Edges[1].Next;
23665 end else if RigidBodyB.fContactPairEdgeFirst=@AContactPair^.Edges[1] then begin
23666 RigidBodyB.fContactPairEdgeFirst:=AContactPair^.Edges[1].Next;
23667 end;
23668 if assigned(AContactPair^.Edges[1].Next) then begin
23669 AContactPair^.Edges[1].Next^.Previous:=AContactPair^.Edges[1].Previous;
23670 end else if RigidBodyB.fContactPairEdgeLast=@AContactPair^.Edges[1] then begin
23671 RigidBodyB.fContactPairEdgeLast:=AContactPair^.Edges[1].Previous;
23672 end;
23673 AContactPair^.Edges[1].Previous:=nil;
23674 AContactPair^.Edges[1].Next:=nil;
23675
23676 RigidBodyA.SetToAwake;
23677 RigidBodyB.SetToAwake;
23678
23679 if assigned(AContactPair^.Previous) then begin
23680 AContactPair^.Previous^.Next:=AContactPair^.Next;
23681 end else if fContactPairFirst=AContactPair then begin
23682 fContactPairFirst:=AContactPair^.Next;
23683 end;
23684 if assigned(AContactPair^.Next) then begin
23685 AContactPair^.Next^.Previous:=AContactPair^.Previous;
23686 end else if fContactPairLast=AContactPair then begin
23687 fContactPairLast:=AContactPair^.Previous;
23688 end;
23689 AContactPair^.Previous:=nil;
23690 AContactPair^.Next:=fFreeContactPairs;
23691 fFreeContactPairs:=AContactPair;
23692
23693 dec(fCountContactPairs);
23694
23695 end;
23696
23697 procedure TKraftContactManager.RemoveMeshContact(AMeshContactPair:TKraftMeshContactPair);
23698 begin
23699 AMeshContactPair.RemoveFromHashTable;
23700 AMeshContactPair.MoveToFreeList;
23701 end;
23702
23703 procedure TKraftContactManager.RemoveContactsFromRigidBody(ARigidBody:TKraftRigidBody);
23704 var ContactPairEdge,NextContactPairEdge:PKraftContactPairEdge;
23705 MeshContactPair,NextMeshContactPair:TKraftMeshContactPair;
23706 begin
23707 ContactPairEdge:=ARigidBody.fContactPairEdgeFirst;
23708 while assigned(ContactPairEdge) do begin
23709 NextContactPairEdge:=ContactPairEdge^.Next;
23710 RemoveContact(ContactPairEdge^.ContactPair);
23711 ContactPairEdge:=NextContactPairEdge;
23712 end;
23713 ARigidBody.fContactPairEdgeFirst:=nil;
23714 ARigidBody.fContactPairEdgeLast:=nil;
23715 MeshContactPair:=fMeshContactPairFirst;
23716 while assigned(MeshContactPair) do begin
23717 NextMeshContactPair:=MeshContactPair.fNext;
23718 if (MeshContactPair.fRigidBodyConvex=ARigidBody) or (MeshContactPair.fRigidBodyMesh=ARigidBody) then begin
23719 RemoveMeshContact(MeshContactPair);
23720 end;
23721 MeshContactPair:=NextMeshContactPair;
23722 end;
23723 end;
23724
23725 procedure TKraftContactManager.DoBroadPhase;
23726 var StartTime:int64;
23727 begin
23728 StartTime:=fPhysics.fHighResolutionTimer.GetTime;
23729 fPhysics.fBroadPhase.UpdatePairs;
23730 inc(fPhysics.fBroadPhaseTime,fPhysics.fHighResolutionTimer.GetTime-StartTime);
23731 end;
23732
23733 procedure TKraftContactManager.DoMidPhase;
23734 var MeshContactPair:TKraftMeshContactPair;
23735 StartTime:int64;
23736 begin
23737 StartTime:=fPhysics.fHighResolutionTimer.GetTime;
23738 MeshContactPair:=fMeshContactPairFirst;
23739 while assigned(MeshContactPair) do begin
23740 MeshContactPair.Update;
23741 MeshContactPair:=MeshContactPair.fNext;
23742 end;
23743 inc(fPhysics.fMidPhaseTime,fPhysics.fHighResolutionTimer.GetTime-StartTime);
23744 end;
23745
23746 procedure TKraftContactManager.ProcessContactPair(const ContactPair:PKraftContactPair;const ThreadIndex:longint=0);
23747 begin
23748 ContactPair^.DetectCollisions(self,fPhysics.fTriangleShapes[ThreadIndex],ThreadIndex,true,fPhysics.fWorldDeltaTime);
23749 end;
23750
23751 {$ifdef KraftPasMP}
23752 procedure TKraftContactManager.ProcessContactPairParallelForFunction(const Job:PPasMPJob;const ThreadIndex:longint;const Data:pointer;const FromIndex,ToIndex:TPasMPNativeInt);
23753 var Index:longint;
23754 begin
23755 for Index:=FromIndex to ToIndex do begin
23756 ProcessContactPair(fActiveContactPairs[Index],ThreadIndex);
23757 end;
23758 end;
23759 {$else}
23760 procedure TKraftContactManager.ProcessContactPairJob(const JobIndex,ThreadIndex:longint);
23761 begin
23762 ProcessContactPair(fActiveContactPairs[JobIndex],ThreadIndex);
23763 end;
23764 {$endif}
23765
23766 procedure TKraftContactManager.DoNarrowPhase;
23767 var ActiveContactPairIndex:longint;
23768 ContactPair,NextContactPair:PKraftContactPair;
23769 MeshContactPair,NextMeshContactPair:TKraftMeshContactPair;
23770 ShapeA,ShapeB:TKraftShape;
23771 RigidBodyA,RigidBodyB:TKraftRigidBody;
23772 StartTime:int64;
23773 Flags:TKraftContactFlags;
23774 begin
23775
23776 StartTime:=fPhysics.fHighResolutionTimer.GetTime;
23777
23778 fCountActiveContactPairs:=0;
23779
23780 ContactPair:=fContactPairFirst;
23781
23782 while assigned(ContactPair) do begin
23783
23784 ShapeA:=ContactPair^.Shapes[0];
23785 ShapeB:=ContactPair^.Shapes[1];
23786
23787 RigidBodyA:=ContactPair^.RigidBodies[0];
23788 RigidBodyB:=ContactPair^.RigidBodies[1];
23789
23790 if kcfFiltered in ContactPair^.Flags then begin
23791 if (not RigidBodyA.CanCollideWith(RigidBodyB)) or (assigned(fOnCanCollide) and not fOnCanCollide(ShapeA,ShapeB)) then begin
23792 if (ContactPair^.Flags*[kcfColliding,kcfWasColliding])<>[] then begin
23793 if (ContactPair^.Flags*[kcfColliding,kcfWasColliding])=[kcfColliding] then begin
23794 if assigned(fOnContactBegin) then begin
23795 fOnContactBegin(ContactPair);
23796 end;
23797 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactBegin) then begin
23798 ContactPair^.Shapes[0].fOnContactBegin(ContactPair,ContactPair^.Shapes[1]);
23799 end;
23800 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactBegin) then begin
23801 ContactPair^.Shapes[1].fOnContactBegin(ContactPair,ContactPair^.Shapes[0]);
23802 end;
23803 end;
23804 if assigned(fOnContactEnd) then begin
23805 fOnContactEnd(ContactPair);
23806 end;
23807 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactEnd) then begin
23808 ContactPair^.Shapes[0].fOnContactEnd(ContactPair,ContactPair^.Shapes[1]);
23809 end;
23810 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactEnd) then begin
23811 ContactPair^.Shapes[1].fOnContactEnd(ContactPair,ContactPair^.Shapes[0]);
23812 end;
23813 end;
23814 NextContactPair:=ContactPair^.Next;
23815 RemoveContact(ContactPair);
23816 ContactPair:=NextContactPair;
23817 continue;
23818 end;
23819 ContactPair^.Flags:=ContactPair^.Flags-[kcfFiltered];
23820 end;
23821
23822 if ((RigidBodyA.fFlags*[krbfAwake,krbfActive])<>[krbfAwake,krbfActive]) and
23823 ((RigidBodyB.fFlags*[krbfAwake,krbfActive])<>[krbfAwake,krbfActive]) then begin
23824 ContactPair:=ContactPair^.Next;
23825 continue;
23826 end;
23827
23828 if not AABBIntersect(ShapeA.ProxyFatWorldAABB^,ShapeB.ProxyFatWorldAABB^) then begin
23829 if (ContactPair^.Flags*[kcfColliding,kcfWasColliding])<>[] then begin
23830 if (ContactPair^.Flags*[kcfColliding,kcfWasColliding])=[kcfColliding] then begin
23831 if assigned(fOnContactBegin) then begin
23832 fOnContactBegin(ContactPair);
23833 end;
23834 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactBegin) then begin
23835 ContactPair^.Shapes[0].fOnContactBegin(ContactPair,ContactPair^.Shapes[1]);
23836 end;
23837 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactBegin) then begin
23838 ContactPair^.Shapes[1].fOnContactBegin(ContactPair,ContactPair^.Shapes[0]);
23839 end;
23840 end;
23841 if assigned(fOnContactEnd) then begin
23842 fOnContactEnd(ContactPair);
23843 end;
23844 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactEnd) then begin
23845 ContactPair^.Shapes[0].fOnContactEnd(ContactPair,ContactPair^.Shapes[1]);
23846 end;
23847 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactEnd) then begin
23848 ContactPair^.Shapes[1].fOnContactEnd(ContactPair,ContactPair^.Shapes[0]);
23849 end;
23850 end;
23851 NextContactPair:=ContactPair^.Next;
23852 RemoveContact(ContactPair);
23853 ContactPair:=NextContactPair;
23854 continue;
23855 end;
23856
23857 if assigned(ContactPair^.MeshContactPair) and (ContactPair^.ElementIndex>=0) then begin
23858 if not AABBIntersect(TKraftShapeMesh(ContactPair^.MeshContactPair.fShapeMesh).fMesh.fTriangles[ContactPair^.ElementIndex].AABB,
23859 ContactPair^.MeshContactPair.fConvexAABBInMeshLocalSpace) then begin
23860 if (ContactPair^.Flags*[kcfColliding,kcfWasColliding])<>[] then begin
23861 if (ContactPair^.Flags*[kcfColliding,kcfWasColliding])=[kcfColliding] then begin
23862 if assigned(fOnContactBegin) then begin
23863 fOnContactBegin(ContactPair);
23864 end;
23865 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactBegin) then begin
23866 ContactPair^.Shapes[0].fOnContactBegin(ContactPair,ContactPair^.MeshContactPair.fShapeMesh);
23867 end;
23868 if assigned(ContactPair^.MeshContactPair.fShapeMesh) and assigned(ContactPair^.MeshContactPair.fShapeMesh.fOnContactBegin) then begin
23869 ContactPair^.Shapes[1].fOnContactBegin(ContactPair,ContactPair^.Shapes[0]);
23870 end;
23871 end;
23872 if assigned(fOnContactEnd) then begin
23873 fOnContactEnd(ContactPair);
23874 end;
23875 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactEnd) then begin
23876 ContactPair^.Shapes[0].fOnContactEnd(ContactPair,ContactPair^.MeshContactPair.fShapeMesh);
23877 end;
23878 if assigned(ContactPair^.MeshContactPair.fShapeMesh) and assigned(ContactPair^.MeshContactPair.fShapeMesh.fOnContactEnd) then begin
23879 ContactPair^.MeshContactPair.fShapeMesh.fOnContactEnd(ContactPair,ContactPair^.Shapes[0]);
23880 end;
23881 end;
23882 NextContactPair:=ContactPair^.Next;
23883 RemoveContact(ContactPair);
23884 ContactPair:=NextContactPair;
23885 continue;
23886 end;
23887 end;
23888
23889 ActiveContactPairIndex:=fCountActiveContactPairs;
23890 inc(fCountActiveContactPairs);
23891 if fCountActiveContactPairs>length(fActiveContactPairs) then begin
23892 SetLength(fActiveContactPairs,fCountActiveContactPairs*2);
23893 end;
23894 fActiveContactPairs[ActiveContactPairIndex]:=ContactPair;
23895
23896 ContactPair:=ContactPair^.Next;
23897
23898 end;
23899
23900 fCountRemainActiveContactPairsToDo:=fCountActiveContactPairs;
23901
23902 {$ifdef KraftPasMP}
23903 if assigned(fPhysics.fPasMP) and (fCountActiveContactPairs>64) and not fPhysics.fSingleThreaded then begin
23904 fPhysics.fPasMP.Invoke(fPhysics.fPasMP.ParallelFor(nil,0,fCountActiveContactPairs-1,ProcessContactPairParallelForFunction,Max(64,fCountActiveContactPairs div (fPhysics.fCountThreads*16)),4));
23905 {$else}
23906 if assigned(fPhysics.fJobManager) and (fCountActiveContactPairs>64) and not fPhysics.fSingleThreaded then begin
23907 fPhysics.fJobManager.fOnProcessJob:=ProcessContactPairJob;
23908 fPhysics.fJobManager.fCountRemainJobs:=fCountActiveContactPairs;
23909 fPhysics.fJobManager.fGranularity:=Max(64,fCountActiveContactPairs div (fPhysics.fCountThreads*16));
23910 fPhysics.fJobManager.ProcessJobs;
23911 {$endif}
23912 end else begin
23913 for ActiveContactPairIndex:=0 to fCountActiveContactPairs-1 do begin
23914 ProcessContactPair(fActiveContactPairs[ActiveContactPairIndex],0);
23915 end;
23916 end;
23917
23918 for ActiveContactPairIndex:=0 to fCountActiveContactPairs-1 do begin
23919 ContactPair:=fActiveContactPairs[ActiveContactPairIndex];
23920 Flags:=ContactPair^.Flags*[kcfColliding,kcfWasColliding];
23921 if Flags=[kcfColliding] then begin
23922 if assigned(fOnContactBegin) then begin
23923 fOnContactBegin(ContactPair);
23924 end;
23925 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactBegin) then begin
23926 ContactPair^.Shapes[0].fOnContactBegin(ContactPair,ContactPair^.Shapes[1]);
23927 end;
23928 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactBegin) then begin
23929 ContactPair^.Shapes[1].fOnContactBegin(ContactPair,ContactPair^.Shapes[0]);
23930 end;
23931 end else if Flags=[kcfWasColliding] then begin
23932 if assigned(fOnContactEnd) then begin
23933 fOnContactEnd(ContactPair);
23934 end;
23935 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactEnd) then begin
23936 ContactPair^.Shapes[0].fOnContactEnd(ContactPair,ContactPair^.Shapes[1]);
23937 end;
23938 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactEnd) then begin
23939 ContactPair^.Shapes[1].fOnContactEnd(ContactPair,ContactPair^.Shapes[0]);
23940 end;
23941 end else if Flags=[kcfColliding,kcfWasColliding] then begin
23942 if assigned(fOnContactStay) then begin
23943 fOnContactStay(ContactPair);
23944 end;
23945 if assigned(ContactPair^.Shapes[0]) and assigned(ContactPair^.Shapes[0].fOnContactStay) then begin
23946 ContactPair^.Shapes[0].fOnContactStay(ContactPair,ContactPair^.Shapes[1]);
23947 end;
23948 if assigned(ContactPair^.Shapes[1]) and assigned(ContactPair^.Shapes[1].fOnContactStay) then begin
23949 ContactPair^.Shapes[1].fOnContactStay(ContactPair,ContactPair^.Shapes[0]);
23950 end;
23951 end;
23952 end;
23953
23954 MeshContactPair:=fMeshContactPairFirst;
23955 while assigned(MeshContactPair) do begin
23956
23957 ShapeA:=MeshContactPair.fShapeConvex;
23958 ShapeB:=MeshContactPair.fShapeMesh;
23959
23960 RigidBodyA:=MeshContactPair.fRigidBodyConvex;
23961 RigidBodyB:=MeshContactPair.fRigidBodyMesh;
23962
23963 if kcfFiltered in MeshContactPair.fFlags then begin
23964 if (not RigidBodyA.CanCollideWith(RigidBodyB)) or (assigned(fOnCanCollide) and not fOnCanCollide(ShapeA,ShapeB)) then begin
23965 NextMeshContactPair:=MeshContactPair.fNext;
23966 RemoveMeshContact(MeshContactPair);
23967 MeshContactPair:=NextMeshContactPair;
23968 continue;
23969 end;
23970 MeshContactPair.fFlags:=MeshContactPair.fFlags-[kcfFiltered];
23971 end;
23972
23973 if ((RigidBodyA.fFlags*[krbfAwake,krbfActive])<>[krbfAwake,krbfActive]) and
23974 ((RigidBodyB.fFlags*[krbfAwake,krbfActive])<>[krbfAwake,krbfActive]) then begin
23975 MeshContactPair:=MeshContactPair.fNext;
23976 continue;
23977 end;
23978
23979 if not AABBIntersect(ShapeA.ProxyFatWorldAABB^,ShapeB.ProxyFatWorldAABB^) then begin
23980 NextMeshContactPair:=MeshContactPair.fNext;
23981 RemoveMeshContact(MeshContactPair);
23982 MeshContactPair:=NextMeshContactPair;
23983 continue;
23984 end;
23985
23986 MeshContactPair:=MeshContactPair.fNext;
23987
23988 end;
23989
23990 inc(fPhysics.fNarrowPhaseTime,fPhysics.fHighResolutionTimer.GetTime-StartTime);
23991
23992 end;
23993
23994 {$ifdef DebugDraw}
23995 procedure TKraftContactManager.DebugDraw(const CameraMatrix:TKraftMatrix4x4);
23996 var i,j:longint;
23997 ContactPair:PKraftContactPair;
23998 ContactManifold:PKraftContactManifold;
23999 Contact:PKraftContact;
24000 SolverContact:PKraftSolverContact;
24001 SolverContactManifold:TKraftSolverContactManifold;
24002 f:TKraftScalar;
24003 begin
24004
24005 glPushMatrix;
24006 glMatrixMode(GL_MODELVIEW);
24007
24008 {$ifdef UseDouble}
24009 glLoadMatrixd(pointer(@CameraMatrix));
24010 {$else}
24011 glLoadMatrixf(pointer(@CameraMatrix));
24012 {$endif}
24013
24014 ContactPair:=fContactPairFirst;
24015
24016 while assigned(ContactPair) do begin
24017
24018 if kcfColliding in ContactPair^.Flags then begin
24019
24020 ContactManifold:=@ContactPair^.Manifold;
24021
24022 ContactPair^.GetSolverContactManifold(SolverContactManifold,ContactPair^.RigidBodies[0].fWorldTransform,ContactPair^.RigidBodies[1].fWorldTransform,kcpcmmBaumgarte);
24023
24024 for i:=0 to ContactManifold^.CountContacts-1 do begin
24025
24026 SolverContact:[email protected][i];
24027
24028 Contact:[email protected][i];
24029
24030 f:=(1024-Min(Max(Contact^.WarmStartState,0),1024))/1024.0;
24031
24032 if ContactPair^.Manifold.ContactManifoldType=kcmtSPECULATIVE then begin
24033
24034 if krbfAwake in ContactPair^.Shapes[0].fRigidBody.fFlags then begin
24035 glColor4f(0.0,f,1.0-f,1.0);
24036 end else begin
24037 glColor4f(0.0,1.0,0.0,1.0);
24038 end;
24039 glBegin(GL_POINTS);
24040 {$ifdef UseDouble}
24041 glVertex3fd(@SolverContactManifold.Points[0]);
24042 glVertex3fd(@SolverContactManifold.Points[1]);
24043 {$else}
24044 glVertex3fv(@SolverContactManifold.Points[0]);
24045 glVertex3fv(@SolverContactManifold.Points[1]);
24046 {$endif}
24047 glEnd;
24048
24049 if krbfAwake in ContactPair^.Shapes[0].fRigidBody.fFlags then begin
24050 glColor4f(1.0,1.0,1.0,1.0);
24051 end else begin
24052 glColor4f(0.2,0.2,0.2,1.0);
24053 end;
24054 glBegin(GL_LINES);
24055 {$ifdef UseDouble}
24056 glVertex3fd(@SolverContactManifold.Points[0]);
24057 glVertex3fd(@SolverContactManifold.Points[1]);
24058 {$else}
24059 glVertex3fv(@SolverContactManifold.Points[0]);
24060 glVertex3fv(@SolverContactManifold.Points[1]);
24061 {$endif}
24062 glEnd;
24063
24064 end else begin
24065
24066 if krbfAwake in ContactPair^.Shapes[0].fRigidBody.fFlags then begin
24067 glColor4f(1.0-f,f,f,1.0);
24068 end else begin
24069 glColor4f(1.0,1.0,0.0,1.0);
24070 end;
24071 glBegin(GL_POINTS);
24072 {$ifdef UseDouble}
24073 glVertex3dv(@SolverContact^.Point);
24074 {$else}
24075 glVertex3fv(@SolverContact^.Point);
24076 {$endif}
24077 glEnd;
24078
24079 if krbfAwake in ContactPair^.Shapes[0].fRigidBody.fFlags then begin
24080 glColor4f(1.0,1.0,1.0,1.0);
24081 end else begin
24082 glColor4f(0.2,0.2,0.2,1.0);
24083 end;
24084 glBegin(GL_LINES);
24085 {$ifdef UseDouble}
24086 glVertex3dv(@SolverContact^.Point);
24087 {$else}
24088 glVertex3fv(@SolverContact^.Point);
24089 {$endif}
24090 glVertex3f(SolverContact^.Point.x+(SolverContactManifold.Normal.x*SolverContact^.Separation),
24091 SolverContact^.Point.y+(SolverContactManifold.Normal.y*SolverContact^.Separation),
24092 SolverContact^.Point.z+(SolverContactManifold.Normal.z*SolverContact^.Separation));
24093 glEnd;
24094
24095 end;
24096
24097 end;
24098
24099 end;
24100
24101 ContactPair:=ContactPair^.Next;
24102
24103 end;
24104
24105 glLineWidth(2);
24106 glBegin(GL_LINES);
24107 for i:=0 to fCountDebugClipVertexLists-1 do begin
24108 {$ifdef UseDouble}
24109 glColor4dv(@fDebugClipVertexLists[i].Color);
24110 for j:=0 to fDebugClipVertexLists[i].Count-1 do begin
24111 if j=0 then begin
24112 glVertex3dv(@fDebugClipVertexLists[i].Vertices[fDebugClipVertexLists[i].Count-1].Position);
24113 end else begin
24114 glVertex3dv(@fDebugClipVertexLists[i].Vertices[j-1].Position);
24115 end;
24116 glVertex3dv(@fDebugClipVertexLists[i].Vertices[j].Position);
24117 end;
24118 {$else}
24119 glColor4fv(@fDebugClipVertexLists[i].Color);
24120 for j:=0 to fDebugClipVertexLists[i].Count-1 do begin
24121 if j=0 then begin
24122 glVertex3fv(@fDebugClipVertexLists[i].Vertices[fDebugClipVertexLists[i].Count-1].Position);
24123 end else begin
24124 glVertex3fv(@fDebugClipVertexLists[i].Vertices[j-1].Position);
24125 end;
24126 glVertex3fv(@fDebugClipVertexLists[i].Vertices[j].Position);
24127 end;
24128 {$endif}
24129 end;
24130 glEnd;
24131
24132 glPopMatrix;
24133
24134 end;
24135 {$endif}
24136
24137 function TKraftContactManager.ReduceContacts(const AInputContacts:PKraftContacts;const ACountInputContacts:longint;const AOutputContacts:PKraftContacts):longint;
24138 var Index,MaxPenetrationIndex:longint;
24139 MaxPenetration,MaxDistance,Distance,MaxArea,Area:TKraftScalar;
24140 Contact:PKraftContact;
24141 Contacts:array[0..MAX_CONTACTS-1] of PKraftContact;
24142 begin
24143 if ACountInputContacts<=0 then begin
24144
24145 result:=0;
24146
24147 end else if ACountInputContacts<=MAX_CONTACTS then begin
24148
24149 result:=ACountInputContacts;
24150
24151 for Index:=0 to ACountInputContacts-1 do begin
24152 AOutputContacts^[Index]:=AInputContacts^[Index];
24153 end;
24154
24155 end else begin
24156
24157 result:=MAX_CONTACTS;
24158
24159 MaxPenetrationIndex:=0;
24160 MaxPenetration:=AInputContacts^[0].Penetration;
24161 for Index:=1 to ACountInputContacts-1 do begin
24162 Contact:=@AInputContacts^[Index];
24163 if MaxPenetration<Contact^.Penetration then begin
24164 MaxPenetrationIndex:=Index;
24165 MaxPenetration:=Contact^.Penetration;
24166 end;
24167 end;
24168 Contacts[0]:=@AInputContacts^[MaxPenetrationIndex];
24169
24170 Contacts[1]:=nil;
24171 MaxDistance:=0.0;
24172 for Index:=0 to ACountInputContacts-1 do begin
24173 Contact:=@AInputContacts^[Index];
24174 if Contact<>Contacts[0] then begin
24175 Distance:=Vector3DistSquared(Contact^.LocalPoints[0],Contacts[0]^.LocalPoints[0]);
24176 if (not assigned(Contacts[1])) or (MaxDistance<Distance) then begin
24177 MaxDistance:=Distance;
24178 Contacts[1]:=Contact;
24179 end;
24180 end;
24181 end;
24182
24183 Contacts[2]:=nil;
24184 MaxArea:=0.0;
24185 for Index:=0 to ACountInputContacts-1 do begin
24186 Contact:=@AInputContacts^[Index];
24187 if (Contact<>Contacts[0]) and (Contact<>Contacts[1]) then begin
24188 Area:=CalculateAreaFromThreePoints(Contact^.LocalPoints[0],Contacts[0]^.LocalPoints[0],Contacts[1]^.LocalPoints[0]);
24189 if (not assigned(Contacts[2])) or (MaxArea<Area) then begin
24190 MaxArea:=Area;
24191 Contacts[2]:=Contact;
24192 end;
24193 end;
24194 end;
24195
24196 Contacts[3]:=nil;
24197 MaxArea:=0.0;
24198 for Index:=0 to ACountInputContacts-1 do begin
24199 Contact:=@AInputContacts^[Index];
24200 if (Contact<>Contacts[0]) and (Contact<>Contacts[1]) and (Contact<>Contacts[2]) then begin
24201 Area:=CalculateAreaFromFourPoints(Contact^.LocalPoints[0],Contacts[0]^.LocalPoints[0],Contacts[1]^.LocalPoints[0],Contacts[2]^.LocalPoints[0]);
24202 if (not assigned(Contacts[3])) or (MaxArea<Area) then begin
24203 MaxArea:=Area;
24204 Contacts[3]:=Contact;
24205 end;
24206 end;
24207 end;
24208
24209 for Index:=0 to MAX_CONTACTS-1 do begin
24210 AOutputContacts^[Index]:=Contacts[Index]^;
24211 end;
24212
24213 end;
24214 end;
24215
24216 function TKraftContactManager.GetMaximizedAreaReducedContactIndices(const AInputContactPositions:PPKraftVector3s;const ACountInputContactPositions:longint;var AOutputContactIndices:TKraftContactIndices):longint;
24217 var Index,StartIndex:longint;
24218 MaxDistance,Distance,MaxArea,Area:TKraftScalar;
24219 Position:PKraftVector3;
24220 Positions:array[0..MAX_CONTACTS-1] of PKraftVector3;
24221 Contacts:array[0..MAX_CONTACTS-1] of longint;
24222 begin
24223 if ACountInputContactPositions<=0 then begin
24224
24225 result:=0;
24226
24227 end else if ACountInputContactPositions<=MAX_CONTACTS then begin
24228
24229 result:=ACountInputContactPositions;
24230
24231 for Index:=0 to ACountInputContactPositions-1 do begin
24232 AOutputContactIndices[Index]:=Index;
24233 end;
24234
24235 end else begin
24236
24237 result:=MAX_CONTACTS-1;
24238
24239 StartIndex:=0;
24240 Positions[0]:=AInputContactPositions^[StartIndex];
24241 for Index:=1 to ACountInputContactPositions-1 do begin
24242 Position:=AInputContactPositions^[Index];
24243 if (Position^.x<Positions[0]^.x) or (Position^.y<Positions[0]^.y) or (Position^.z<Positions[0]^.z) then begin
24244 StartIndex:=Index;
24245 Positions[0]:=AInputContactPositions^[Index];
24246 end;
24247 end;
24248 Contacts[0]:=StartIndex;
24249
24250 Contacts[1]:=-1;
24251 MaxDistance:=0.0;
24252 for Index:=0 to ACountInputContactPositions-1 do begin
24253 Position:=AInputContactPositions^[Index];
24254 if Index<>Contacts[0] then begin
24255 Distance:=Vector3DistSquared(Position^,Positions[0]^);
24256 if (Contacts[1]<0) or (MaxDistance<Distance) then begin
24257 MaxDistance:=Distance;
24258 Contacts[1]:=Index;
24259 end;
24260 end;
24261 end;
24262 Positions[1]:=AInputContactPositions^[Contacts[1]];
24263
24264 Contacts[2]:=-1;
24265 MaxArea:=0.0;
24266 for Index:=0 to ACountInputContactPositions-1 do begin
24267 Position:=AInputContactPositions^[Index];
24268 if (Index<>Contacts[0]) and (Index<>Contacts[1]) then begin
24269 Area:=CalculateAreaFromThreePoints(Position^,Positions[0]^,Positions[1]^);
24270 if (Contacts[2]<0) or (MaxArea<Area) then begin
24271 MaxArea:=Area;
24272 Contacts[2]:=Index;
24273 end;
24274 end;
24275 end;
24276 Positions[2]:=AInputContactPositions^[Contacts[2]];
24277
24278 Contacts[3]:=-1;
24279 MaxArea:=0.0;
24280 for Index:=0 to ACountInputContactPositions-1 do begin
24281 Position:=AInputContactPositions^[Index];
24282 if (Index<>Contacts[0]) and (Index<>Contacts[1]) and (Index<>Contacts[2]) then begin
24283 Area:=CalculateAreaFromFourPoints(Position^,Positions[0]^,Positions[1]^,Positions[2]^);
24284 if (Contacts[3]<0) or (MaxArea<Area) then begin
24285 MaxArea:=Area;
24286 Contacts[3]:=Index;
24287 end;
24288 end;
24289 end;
24290
24291 for Index:=0 to MAX_CONTACTS-1 do begin
24292 AOutputContactIndices[Index]:=Contacts[Index];
24293 end;
24294
24295 end;
24296 end;
24297
24298 constructor TKraftBroadPhase.Create(const APhysics:TKraft);
24299 var ThreadIndex,CountThreads:longint;
24300 begin
24301 inherited Create;
24302
24303 fPhysics:=APhysics;
24304
24305 CountThreads:=Max(1,fPhysics.fCountThreads);
24306
24307 for ThreadIndex:=0 to MAX_THREADS-1 do begin
24308
24309 if ThreadIndex<CountThreads then begin
24310 fStackCapacity[ThreadIndex]:=16;
24311 GetMem(fStack[ThreadIndex],fStackCapacity[ThreadIndex]*SizeOf(longint));
24312 end else begin
24313 fStack[ThreadIndex]:=nil;
24314 fStackCapacity[ThreadIndex]:=0;
24315 end;
24316
24317 fContactPairs[ThreadIndex]:=nil;
24318 if ThreadIndex<CountThreads then begin
24319 SetLength(fContactPairs[ThreadIndex],4096);
24320 end else begin
24321 SetLength(fContactPairs[ThreadIndex],0);
24322 end;
24323 fCountContactPairs[ThreadIndex]:=0;
24324
24325 end;
24326
24327 fStaticMoveBuffer:=nil;
24328 SetLength(fStaticMoveBuffer,64);
24329 fStaticMoveBufferSize:=0;
24330
24331 fDynamicMoveBuffer:=nil;
24332 SetLength(fDynamicMoveBuffer,64);
24333 fDynamicMoveBufferSize:=0;
24334
24335 fKinematicMoveBuffer:=nil;
24336 SetLength(fKinematicMoveBuffer,64);
24337 fKinematicMoveBufferSize:=0;
24338
24339 end;
24340
24341 destructor TKraftBroadPhase.Destroy;
24342 var ThreadIndex:longint;
24343 begin
24344 for ThreadIndex:=0 to MAX_THREADS-1 do begin
24345 if assigned(fStack[ThreadIndex]) then begin
24346 FreeMem(fStack[ThreadIndex]);
24347 fStack[ThreadIndex]:=nil;
24348 end;
24349 SetLength(fContactPairs[ThreadIndex],0);
24350 end;
24351 SetLength(fStaticMoveBuffer,0);
24352 SetLength(fDynamicMoveBuffer,0);
24353 SetLength(fKinematicMoveBuffer,0);
24354 inherited Destroy;
24355 end;
24356
24357 function CompareContactPairs(const a,b:pointer):longint;
24358 begin
24359 result:=PtrInt(PKraftBroadPhaseContactPair(a)^[0])-PtrInt(PKraftBroadPhaseContactPair(b)^[0]);
24360 if result=0 then begin
24361 result:=PtrInt(PKraftBroadPhaseContactPair(a)^[1])-PtrInt(PKraftBroadPhaseContactPair(b)^[1]);
24362 end;
24363 end;
24364
24365 procedure TKraftBroadPhase.AddPair(const ThreadIndex:longint;ShapeA,ShapeB:TKraftShape); {$ifdef caninline}inline;{$endif}
24366 var TempShape:TKraftShape;
24367 Index:longint;
24368 ContactPair:PKraftBroadPhaseContactPair;
24369 begin
24370 if (ShapeA<>ShapeB) and (ShapeA.RigidBody<>ShapeB.RigidBody) then begin
24371 if (ShapeA.fShapeType>ShapeB.fShapeType) or ((ShapeA.fShapeType=ShapeB.fShapeType) and (ptruint(ShapeA)>ptruint(ShapeB))) then begin
24372 TempShape:=ShapeA;
24373 ShapeA:=ShapeB;
24374 ShapeB:=TempShape;
24375 end;
24376 Index:=fCountContactPairs[ThreadIndex];
24377 inc(fCountContactPairs[ThreadIndex]);
24378 if fCountContactPairs[ThreadIndex]>length(fContactPairs[ThreadIndex]) then begin
24379 SetLength(fContactPairs[ThreadIndex],fCountContactPairs[ThreadIndex]*2);
24380 end;
24381 ContactPair:=@fContactPairs[ThreadIndex,Index];
24382 ContactPair[0]:=ShapeA;
24383 ContactPair[1]:=ShapeB;
24384 end;
24385 end;
24386
24387 procedure TKraftBroadPhase.QueryShapeWithTree(const ThreadIndex:longint;const Shape:TKraftShape;const AABBTree:TKraftDynamicAABBTree);
24388 {$ifdef KraftSingleThreadedUsage}
24389 var ShapeAABB:PKraftAABB;
24390 LocalStack:PKraftDynamicAABBTreeLongintArray;
24391 LocalStackPointer,NodeID:longint;
24392 Node:PKraftDynamicAABBTreeNode;
24393 OtherShape:TKraftShape;
24394 begin
24395 if assigned(Shape) and assigned(AABBTree) then begin
24396 ShapeAABB:=Shape.ProxyFatWorldAABB;
24397 if AABBTree.fRoot>=0 then begin
24398 LocalStack:=fStack[ThreadIndex];
24399 LocalStack^[0]:=AABBTree.fRoot;
24400 LocalStackPointer:=1;
24401 while LocalStackPointer>0 do begin
24402 dec(LocalStackPointer);
24403 NodeID:=LocalStack^[LocalStackPointer];
24404 if NodeID>=0 then begin
24405 Node:[email protected][NodeID];
24406 if AABBIntersect(Node^.AABB,ShapeAABB^) then begin
24407 if Node^.Children[0]<0 then begin
24408 OtherShape:=Node^.UserData;
24409 if assigned(OtherShape) and (Shape<>OtherShape) then begin
24410 AddPair(ThreadIndex,Shape,OtherShape);
24411 end;
24412 end else begin
24413 if fStackCapacity[ThreadIndex]<=(LocalStackPointer+2) then begin
24414 fStackCapacity[ThreadIndex]:=RoundUpToPowerOfTwo(LocalStackPointer+2);
24415 ReallocMem(fStack[ThreadIndex],fStackCapacity[ThreadIndex]*SizeOf(longint));
24416 LocalStack:=fStack[ThreadIndex];
24417 end;
24418 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
24419 LocalStack^[LocalStackPointer+1]:=Node^.Children[1];
24420 inc(LocalStackPointer,2);
24421 end;
24422 end;
24423 end;
24424 end;
24425 end;
24426 end;
24427 end;
24428 {$else}
24429 var ShapeAABB:PKraftAABB;
24430 procedure ProcessNode(const NodeID:longint);
24431 var Node:PKraftDynamicAABBTreeNode;
24432 OtherShape:TKraftShape;
24433 begin
24434 if NodeID>=0 then begin
24435 Node:[email protected][NodeID];
24436 if AABBIntersect(Node^.AABB,ShapeAABB^) then begin
24437 if Node^.Children[0]<0 then begin
24438 OtherShape:=Node^.UserData;
24439 if assigned(OtherShape) and (Shape<>OtherShape) then begin
24440 AddPair(ThreadIndex,Shape,OtherShape);
24441 end;
24442 end else begin
24443 ProcessNode(Node^.Children[0]);
24444 ProcessNode(Node^.Children[1]);
24445 end;
24446 end;
24447 end;
24448 end;
24449 begin
24450 if assigned(Shape) and assigned(AABBTree) then begin
24451 ShapeAABB:=Shape.ProxyFatWorldAABB;
24452 if AABBTree.fRoot>=0 then begin
24453 ProcessNode(AABBTree.fRoot);
24454 end;
24455 end;
24456 end;
24457 {$endif}
24458
24459 {$ifdef KraftPasMP}
24460 procedure TKraftBroadPhase.ProcessMoveBufferItemParallelForFunction(const Job:PPasMPJob;const ThreadIndex:longint;const Data:pointer;const FromIndex,ToIndex:TPasMPNativeInt);
24461 {$else}
24462 procedure TKraftBroadPhase.ProcessMoveBufferItem(const JobIndex,ThreadIndex:longint);
24463 {$endif}
24464 var {$ifdef KraftPasMP}JobIndex,{$endif}Index:longint;
24465 Shape:TKraftShape;
24466 begin
24467 {$ifdef KraftPasMP}for JobIndex:=FromIndex to ToIndex do{$endif}begin
24468 Index:=JobIndex;
24469 if Index<fStaticMoveBufferSize then begin
24470 // Static shapes against dynamic shapes
24471 if fStaticMoveBuffer[Index]>=0 then begin
24472 Shape:=fPhysics.fStaticAABBTree.fNodes[fStaticMoveBuffer[Index]].UserData;
24473 if assigned(Shape) then begin
24474 QueryShapeWithTree(ThreadIndex,Shape,fPhysics.fDynamicAABBTree);
24475 end;
24476 end;
24477 end else if Index<(fStaticMoveBufferSize+fDynamicMoveBufferSize) then begin
24478 // Dynamic shapes against static, dynamic and kinematic shapes
24479 dec(Index,fStaticMoveBufferSize);
24480 if fDynamicMoveBuffer[Index]>=0 then begin
24481 Shape:=fPhysics.fDynamicAABBTree.fNodes[fDynamicMoveBuffer[Index]].UserData;
24482 if assigned(Shape) then begin
24483 QueryShapeWithTree(ThreadIndex,Shape,fPhysics.fStaticAABBTree);
24484 QueryShapeWithTree(ThreadIndex,Shape,fPhysics.fDynamicAABBTree);
24485 QueryShapeWithTree(ThreadIndex,Shape,fPhysics.fKinematicAABBTree);
24486 end;
24487 end;
24488 end else if Index<(fStaticMoveBufferSize+fDynamicMoveBufferSize+fKinematicMoveBufferSize) then begin
24489 // Kinematic shapes against dynamic shapes
24490 dec(Index,fStaticMoveBufferSize+fDynamicMoveBufferSize);
24491 if fKinematicMoveBuffer[Index]>=0 then begin
24492 Shape:=fPhysics.fKinematicAABBTree.fNodes[fKinematicMoveBuffer[Index]].UserData;
24493 if assigned(Shape) then begin
24494 QueryShapeWithTree(ThreadIndex,Shape,fPhysics.fDynamicAABBTree);
24495 end;
24496 end;
24497 end;
24498 end;
24499 end;
24500
24501 procedure TKraftBroadPhase.UpdatePairs;
24502 var ThreadIndex,Count,Index:longint;
24503 ContactPair,OtherContactPair:PKraftBroadPhaseContactPair;
24504 begin
24505
24506 // Reset found thread contact pair arrays
24507 for ThreadIndex:=0 to Max(1,fPhysics.CountThreads)-1 do begin
24508 fCountContactPairs[ThreadIndex]:=0;
24509 end;
24510
24511 // Run the thread jobs
24512 fAllMoveBufferSize:=fStaticMoveBufferSize+fDynamicMoveBufferSize+fKinematicMoveBufferSize;
24513 {$ifdef KraftPasMP}
24514 if assigned(fPhysics.fPasMP) and (fAllMoveBufferSize>1024) and not fPhysics.fSingleThreaded then begin
24515 fPhysics.fPasMP.Invoke(fPhysics.fPasMP.ParallelFor(nil,0,fAllMoveBufferSize-1,ProcessMoveBufferItemParallelForFunction,Max(64,fAllMoveBufferSize div (fPhysics.fCountThreads*16)),4));
24516 end else begin
24517 ProcessMoveBufferItemParallelForFunction(nil,0,nil,0,fAllMoveBufferSize-1);
24518 end;
24519 {$else}
24520 if assigned(fPhysics.fJobManager) and (fAllMoveBufferSize>1024) and not fPhysics.fSingleThreaded then begin
24521 fPhysics.fJobManager.fOnProcessJob:=ProcessMoveBufferItem;
24522 fPhysics.fJobManager.fCountRemainJobs:=fAllMoveBufferSize;
24523 fPhysics.fJobManager.fGranularity:=Max(64,fAllMoveBufferSize div (fPhysics.fCountThreads*16));
24524 fPhysics.fJobManager.ProcessJobs;
24525 end else begin
24526 for Index:=0 to fAllMoveBufferSize-1 do begin
24527 ProcessMoveBufferItem(Index,0);
24528 end;
24529 end;
24530 {$endif}
24531
24532 // Reset move buffer sizes
24533 fStaticMoveBufferSize:=0;
24534 fDynamicMoveBufferSize:=0;
24535 fKinematicMoveBufferSize:=0;
24536
24537 // Merge thread contact pair lists into the first single contact pair list
24538 for ThreadIndex:=1 to fPhysics.CountThreads-1 do begin
24539 if fCountContactPairs[ThreadIndex]>0 then begin
24540 Count:=fCountContactPairs[0]+fCountContactPairs[ThreadIndex];
24541 if Count>length(fContactPairs[0]) then begin
24542 SetLength(fContactPairs[0],RoundUpToPowerOfTwo(Count+1));
24543 end;
24544 Move(fContactPairs[ThreadIndex,0],fContactPairs[0,fCountContactPairs[0]],fCountContactPairs[ThreadIndex]*SizeOf(TKraftBroadPhaseContactPair));
24545 fCountContactPairs[0]:=Count;
24546 end;
24547 end;
24548
24549 // Process the found contact pairs, when there are any...
24550 if fCountContactPairs[0]>0 then begin
24551
24552 // Sort pairs to expose duplicates
24553 DirectIntroSort(@fContactPairs[0,0],0,fCountContactPairs[0]-1,SizeOf(TKraftBroadPhaseContactPair),CompareContactPairs);
24554
24555 // Queue manifolds for solving
24556 Index:=0;
24557 while Index<fCountContactPairs[0] do begin
24558
24559 ContactPair:=@fContactPairs[0,Index];
24560 inc(Index);
24561
24562 // Add contact pair to contact manager
24563 fPhysics.fContactManager.AddContact(ContactPair^[0],ContactPair^[1]);
24564
24565 // Skip duplicate pairs until we find a unique pair
24566 while Index<fCountContactPairs[0] do begin
24567 OtherContactPair:=@fContactPairs[0,Index];
24568 if (ContactPair^[0]<>OtherContactPair^[0]) or (ContactPair^[1]<>OtherContactPair^[1]) then begin
24569 break;
24570 end;
24571 inc(Index);
24572 end;
24573
24574 end;
24575
24576 end;
24577
24578 end;
24579
24580 procedure TKraftBroadPhase.StaticBufferMove(ProxyID:longint);
24581 var Index:longint;
24582 begin
24583 Index:=fStaticMoveBufferSize;
24584 inc(fStaticMoveBufferSize);
24585 if fStaticMoveBufferSize>length(fStaticMoveBuffer) then begin
24586 SetLength(fStaticMoveBuffer,fStaticMoveBufferSize*2);
24587 end;
24588 fStaticMoveBuffer[Index]:=ProxyID;
24589 end;
24590
24591 procedure TKraftBroadPhase.StaticBufferClearMove(ProxyID:longint);
24592 var I:integer;
24593 begin
24594 I:=0;
24595 while I<fStaticMoveBufferSize do begin
24596 if fStaticMoveBuffer[I]=ProxyID then begin
24597 if I<>fStaticMoveBufferSize-1 then
24598 move(fStaticMoveBuffer[I+1],fStaticMoveBuffer[I],SizeOf(fStaticMoveBuffer[I])*(fStaticMoveBufferSize-I));
24599 Dec(fStaticMoveBufferSize);
24600 continue;
24601 end;
24602 Inc(I);
24603 end;
24604 end;
24605
24606 procedure TKraftBroadPhase.DynamicBufferMove(ProxyID:longint);
24607 var Index:longint;
24608 begin
24609 Index:=fDynamicMoveBufferSize;
24610 inc(fDynamicMoveBufferSize);
24611 if fDynamicMoveBufferSize>length(fDynamicMoveBuffer) then begin
24612 SetLength(fDynamicMoveBuffer,fDynamicMoveBufferSize*2);
24613 end;
24614 fDynamicMoveBuffer[Index]:=ProxyID;
24615 end;
24616
24617 procedure TKraftBroadPhase.DynamicBufferClearMove(ProxyID:longint);
24618 var I:integer;
24619 begin
24620 I:=0;
24621 while I<fDynamicMoveBufferSize do begin
24622 if fDynamicMoveBuffer[I]=ProxyID then begin
24623 if I<>fDynamicMoveBufferSize-1 then
24624 move(fDynamicMoveBuffer[I+1],fDynamicMoveBuffer[I],SizeOf(fDynamicMoveBuffer[I])*(fDynamicMoveBufferSize-I));
24625 Dec(fDynamicMoveBufferSize);
24626 continue;
24627 end;
24628 Inc(I);
24629 end;
24630 end;
24631
24632 procedure TKraftBroadPhase.KinematicBufferMove(ProxyID:longint);
24633 var Index:longint;
24634 begin
24635 Index:=fKinematicMoveBufferSize;
24636 inc(fKinematicMoveBufferSize);
24637 if fKinematicMoveBufferSize>length(fKinematicMoveBuffer) then begin
24638 SetLength(fKinematicMoveBuffer,fKinematicMoveBufferSize*2);
24639 end;
24640 fKinematicMoveBuffer[Index]:=ProxyID;
24641 end;
24642
24643 procedure TKraftBroadPhase.KinematicBufferClearMove(ProxyID:longint);
24644 var I:integer;
24645 begin
24646 I:=0;
24647 while I<fKinematicMoveBufferSize do begin
24648 if fKinematicMoveBuffer[I]=ProxyID then begin
24649 if I<>fKinematicMoveBufferSize-1 then
24650 move(fKinematicMoveBuffer[I+1],fKinematicMoveBuffer[I],SizeOf(fKinematicMoveBuffer[I])*(fKinematicMoveBufferSize-I));
24651 Dec(fKinematicMoveBufferSize);
24652 continue;
24653 end;
24654 Inc(I);
24655 end;
24656 end;
24657
24658 constructor TKraftRigidBody.Create(const APhysics:TKraft);
24659 begin
24660 inherited Create;
24661
24662 fPhysics:=APhysics;
24663
24664 fIsland:=nil;
24665
24666 fIslandIndices:=nil;
24667 SetLength(fIslandIndices,4);
24668
24669 inc(fPhysics.fCountRigidBodies);
24670
24671 fID:=fPhysics.fRigidBodyIDCounter;
24672 inc(fPhysics.fRigidBodyIDCounter);
24673
24674 fRigidBodyType:=krbtUnknown;
24675
24676 if assigned(fPhysics.fRigidBodyLast) then begin
24677 fPhysics.fRigidBodyLast.fRigidBodyNext:=self;
24678 fRigidBodyPrevious:=fPhysics.fRigidBodyLast;
24679 end else begin
24680 fPhysics.fRigidBodyFirst:=self;
24681 fRigidBodyPrevious:=nil;
24682 end;
24683 fPhysics.fRigidBodyLast:=self;
24684 fRigidBodyNext:=nil;
24685
24686 fStaticRigidBodyIsOnList:=false;
24687 fStaticRigidBodyPrevious:=nil;
24688 fStaticRigidBodyNext:=nil;
24689
24690 fDynamicRigidBodyIsOnList:=false;
24691 fDynamicRigidBodyPrevious:=nil;
24692 fDynamicRigidBodyNext:=nil;
24693
24694 fKinematicRigidBodyIsOnList:=false;
24695 fKinematicRigidBodyPrevious:=nil;
24696 fKinematicRigidBodyNext:=nil;
24697
24698 fShapeFirst:=nil;
24699 fShapeLast:=nil;
24700
24701 fShapeCount:=0;
24702
24703 fFlags:=[krbfContinuous,krbfAllowSleep,krbfAwake,krbfActive];
24704
24705 fWorldDisplacement:=Vector3Origin;
24706
24707 fSweep.LocalCenter:=Vector3Origin;
24708 fSweep.c0:=Vector3Origin;
24709 fSweep.c:=Vector3Origin;
24710 fSweep.q0:=QuaternionIdentity;
24711 fSweep.q:=QuaternionIdentity;
24712 fSweep.Alpha0:=0.0;
24713
24714 fWorldTransform:=Matrix4x4Identity;
24715
24716 fGravity.x:=0.0;
24717 fGravity.y:=-9.83;
24718 fGravity.z:=0.0;
24719
24720 fGravityProperty:=TKraftVector3Property.Create(@fGravity);
24721
24722 fLinearFactor.x:=1.0;
24723 fLinearFactor.y:=1.0;
24724 fLinearFactor.z:=1.0;
24725
24726 fUserData:=nil;
24727
24728 fNextOnIslandBuildStack:=nil;
24729 fNextStaticRigidBody:=nil;
24730
24731 fBodyInertiaTensor:=Matrix3x3Identity;
24732 fBodyInverseInertiaTensor:=Matrix3x3Identity;
24733
24734 fWorldInertiaTensor:=Matrix3x3Identity;
24735 fWorldInverseInertiaTensor:=Matrix3x3Identity;
24736
24737 fForcedMass:=0.0;
24738
24739 fMass:=0.0;
24740 fInverseMass:=0.0;
24741
24742 fLinearVelocity:=Vector3Origin;
24743 fAngularVelocity:=Vector3Origin;
24744
24745 fMaximalLinearVelocity:=0.0;
24746 fMaximalAngularVelocity:=0.0;
24747
24748 fLinearVelocityDamp:=0.1;
24749 fAngularVelocityDamp:=0.1;
24750 fAdditionalDamping:=false;
24751 fAdditionalDamp:=0.005;
24752 fLinearVelocityAdditionalDamp:=0.01;
24753 fAngularVelocityAdditionalDamp:=0.01;
24754 fLinearVelocityAdditionalDampThresholdSqr:=0.01;
24755 fAngularVelocityAdditionalDampThresholdSqr:=0.01;
24756
24757 fForce:=Vector3Origin;
24758 fTorque:=Vector3Origin;
24759
24760 fSleepTime:=0.0;
24761
24762 fGravityScale:=1.0;
24763
24764 fEnableGyroscopicForce:=false;
24765
24766 fMaximalGyroscopicForce:=0.0;
24767
24768 fCollisionGroups:=[0];
24769
24770 fCollideWithCollisionGroups:=[low(TKraftRigidBodyCollisionGroup)..high(TKraftRigidBodyCollisionGroup)];
24771
24772 fCountConstraints:=0;
24773
24774 fConstraintEdgeFirst:=nil;
24775 fConstraintEdgeLast:=nil;
24776
24777 fContactPairEdgeFirst:=nil;
24778 fContactPairEdgeLast:=nil;
24779
24780 fOnPreStep:=nil;
24781 fOnPostStep:=nil;
24782
24783 end;
24784
24785 destructor TKraftRigidBody.Destroy;
24786 var ConstraintEdge,NextConstraintEdge:PKraftConstraintEdge;
24787 Constraint:TKraftConstraint;
24788 begin
24789
24790 ConstraintEdge:=fConstraintEdgeFirst;
24791 while assigned(ConstraintEdge) do begin
24792 NextConstraintEdge:=ConstraintEdge^.Next;
24793 Constraint:=ConstraintEdge^.Constraint;
24794 if assigned(Constraint) then begin
24795 Constraint.Free;
24796 end;
24797 ConstraintEdge:=NextConstraintEdge;
24798 end;
24799
24800 fCountConstraints:=0;
24801
24802 while assigned(fShapeLast) do begin
24803 fShapeLast.Free;
24804 end;
24805
24806 fPhysics.fContactManager.RemoveContactsFromRigidBody(self);
24807
24808 if assigned(fRigidBodyPrevious) then begin
24809 fRigidBodyPrevious.fRigidBodyNext:=fRigidBodyNext;
24810 end else if fPhysics.fRigidBodyFirst=self then begin
24811 fPhysics.fRigidBodyFirst:=fRigidBodyNext;
24812 end;
24813 if assigned(fRigidBodyNext) then begin
24814 fRigidBodyNext.fRigidBodyPrevious:=fRigidBodyPrevious;
24815 end else if fPhysics.fRigidBodyLast=self then begin
24816 fPhysics.fRigidBodyLast:=fRigidBodyPrevious;
24817 end;
24818 fRigidBodyPrevious:=nil;
24819 fRigidBodyNext:=nil;
24820
24821 if fStaticRigidBodyIsOnList then begin
24822 fStaticRigidBodyIsOnList:=false;
24823 if assigned(fStaticRigidBodyPrevious) then begin
24824 fStaticRigidBodyPrevious.fStaticRigidBodyNext:=fStaticRigidBodyNext;
24825 end else if fPhysics.fStaticRigidBodyFirst=self then begin
24826 fPhysics.fStaticRigidBodyFirst:=fStaticRigidBodyNext;
24827 end;
24828 if assigned(fStaticRigidBodyNext) then begin
24829 fStaticRigidBodyNext.fStaticRigidBodyPrevious:=fStaticRigidBodyPrevious;
24830 end else if fPhysics.fStaticRigidBodyLast=self then begin
24831 fPhysics.fStaticRigidBodyLast:=fStaticRigidBodyPrevious;
24832 end;
24833 fStaticRigidBodyPrevious:=nil;
24834 fStaticRigidBodyNext:=nil;
24835 end;
24836
24837 if fDynamicRigidBodyIsOnList then begin
24838 fDynamicRigidBodyIsOnList:=false;
24839 if assigned(fDynamicRigidBodyPrevious) then begin
24840 fDynamicRigidBodyPrevious.fDynamicRigidBodyNext:=fDynamicRigidBodyNext;
24841 end else if fPhysics.fDynamicRigidBodyFirst=self then begin
24842 fPhysics.fDynamicRigidBodyFirst:=fDynamicRigidBodyNext;
24843 end;
24844 if assigned(fDynamicRigidBodyNext) then begin
24845 fDynamicRigidBodyNext.fDynamicRigidBodyPrevious:=fDynamicRigidBodyPrevious;
24846 end else if fPhysics.fDynamicRigidBodyLast=self then begin
24847 fPhysics.fDynamicRigidBodyLast:=fDynamicRigidBodyPrevious;
24848 end;
24849 fDynamicRigidBodyPrevious:=nil;
24850 fDynamicRigidBodyNext:=nil;
24851 end;
24852
24853 if fKinematicRigidBodyIsOnList then begin
24854 fKinematicRigidBodyIsOnList:=false;
24855 if assigned(fKinematicRigidBodyPrevious) then begin
24856 fKinematicRigidBodyPrevious.fKinematicRigidBodyNext:=fKinematicRigidBodyNext;
24857 end else if fPhysics.fKinematicRigidBodyFirst=self then begin
24858 fPhysics.fKinematicRigidBodyFirst:=fKinematicRigidBodyNext;
24859 end;
24860 if assigned(fKinematicRigidBodyNext) then begin
24861 fKinematicRigidBodyNext.fKinematicRigidBodyPrevious:=fKinematicRigidBodyPrevious;
24862 end else if fPhysics.fKinematicRigidBodyLast=self then begin
24863 fPhysics.fKinematicRigidBodyLast:=fKinematicRigidBodyPrevious;
24864 end;
24865 fKinematicRigidBodyPrevious:=nil;
24866 fKinematicRigidBodyNext:=nil;
24867 end;
24868
24869 SetLength(fIslandIndices,0);
24870
24871 fRigidBodyType:=krbtUnknown;
24872
24873 fGravityProperty.Free;
24874
24875 inherited Destroy;
24876 end;
24877
24878 function TKraftRigidBody.SetRigidBodyType(ARigidBodyType:TKraftRigidBodyType):TKraftRigidBody;
24879 var Shape:TKraftShape;
24880 begin
24881
24882 if fRigidBodyType<>ARigidBodyType then begin
24883
24884 case fRigidBodyType of
24885 krbtStatic:begin
24886
24887 dec(fPhysics.fStaticRigidBodyCount);
24888
24889 if fStaticRigidBodyIsOnList then begin
24890 fStaticRigidBodyIsOnList:=false;
24891 if assigned(fStaticRigidBodyPrevious) then begin
24892 fStaticRigidBodyPrevious.fStaticRigidBodyNext:=fStaticRigidBodyNext;
24893 end else if fPhysics.fStaticRigidBodyFirst=self then begin
24894 fPhysics.fStaticRigidBodyFirst:=fStaticRigidBodyNext;
24895 end;
24896 if assigned(fStaticRigidBodyNext) then begin
24897 fStaticRigidBodyNext.fStaticRigidBodyPrevious:=fStaticRigidBodyPrevious;
24898 end else if fPhysics.fStaticRigidBodyLast=self then begin
24899 fPhysics.fStaticRigidBodyLast:=fStaticRigidBodyPrevious;
24900 end;
24901 fStaticRigidBodyPrevious:=nil;
24902 fStaticRigidBodyNext:=nil;
24903 end;
24904
24905 end;
24906 krbtDynamic:begin
24907
24908 dec(fPhysics.fDynamicRigidBodyCount);
24909
24910 if fDynamicRigidBodyIsOnList then begin
24911 fDynamicRigidBodyIsOnList:=false;
24912 if assigned(fDynamicRigidBodyPrevious) then begin
24913 fDynamicRigidBodyPrevious.fDynamicRigidBodyNext:=fDynamicRigidBodyNext;
24914 end else if fPhysics.fDynamicRigidBodyFirst=self then begin
24915 fPhysics.fDynamicRigidBodyFirst:=fDynamicRigidBodyNext;
24916 end;
24917 if assigned(fDynamicRigidBodyNext) then begin
24918 fDynamicRigidBodyNext.fDynamicRigidBodyPrevious:=fDynamicRigidBodyPrevious;
24919 end else if fPhysics.fDynamicRigidBodyLast=self then begin
24920 fPhysics.fDynamicRigidBodyLast:=fDynamicRigidBodyPrevious;
24921 end;
24922 fDynamicRigidBodyPrevious:=nil;
24923 fDynamicRigidBodyNext:=nil;
24924 end;
24925
24926 end;
24927 krbtKinematic:begin
24928
24929 dec(fPhysics.fKinematicRigidBodyCount);
24930
24931 if fKinematicRigidBodyIsOnList then begin
24932 fKinematicRigidBodyIsOnList:=false;
24933 if assigned(fKinematicRigidBodyPrevious) then begin
24934 fKinematicRigidBodyPrevious.fKinematicRigidBodyNext:=fKinematicRigidBodyNext;
24935 end else if fPhysics.fKinematicRigidBodyFirst=self then begin
24936 fPhysics.fKinematicRigidBodyFirst:=fKinematicRigidBodyNext;
24937 end;
24938 if assigned(fKinematicRigidBodyNext) then begin
24939 fKinematicRigidBodyNext.fKinematicRigidBodyPrevious:=fKinematicRigidBodyPrevious;
24940 end else if fPhysics.fKinematicRigidBodyLast=self then begin
24941 fPhysics.fKinematicRigidBodyLast:=fKinematicRigidBodyPrevious;
24942 end;
24943 fKinematicRigidBodyPrevious:=nil;
24944 fKinematicRigidBodyNext:=nil;
24945 end;
24946
24947 end;
24948 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
24949 end;
24950
24951 fRigidBodyType:=ARigidBodyType;
24952
24953 case fRigidBodyType of
24954 krbtStatic:begin
24955
24956 if assigned(fPhysics.fStaticRigidBodyLast) then begin
24957 fPhysics.fStaticRigidBodyLast.fStaticRigidBodyNext:=self;
24958 fStaticRigidBodyPrevious:=fPhysics.fStaticRigidBodyLast;
24959 end else begin
24960 fPhysics.fStaticRigidBodyFirst:=self;
24961 fStaticRigidBodyPrevious:=nil;
24962 end;
24963 fPhysics.fStaticRigidBodyLast:=self;
24964 fStaticRigidBodyNext:=nil;
24965 fStaticRigidBodyIsOnList:=true;
24966
24967 inc(fPhysics.fStaticRigidBodyCount);
24968
24969 end;
24970 krbtDynamic:begin
24971
24972 if assigned(fPhysics.fDynamicRigidBodyLast) then begin
24973 fPhysics.fDynamicRigidBodyLast.fDynamicRigidBodyNext:=self;
24974 fDynamicRigidBodyPrevious:=fPhysics.fDynamicRigidBodyLast;
24975 end else begin
24976 fPhysics.fDynamicRigidBodyFirst:=self;
24977 fDynamicRigidBodyPrevious:=nil;
24978 end;
24979 fPhysics.fDynamicRigidBodyLast:=self;
24980 fDynamicRigidBodyNext:=nil;
24981 fDynamicRigidBodyIsOnList:=true;
24982
24983 inc(fPhysics.fDynamicRigidBodyCount);
24984
24985 end;
24986 krbtKinematic:begin
24987
24988 if assigned(fPhysics.fKinematicRigidBodyLast) then begin
24989 fPhysics.fKinematicRigidBodyLast.fKinematicRigidBodyNext:=self;
24990 fKinematicRigidBodyPrevious:=fPhysics.fKinematicRigidBodyLast;
24991 end else begin
24992 fPhysics.fKinematicRigidBodyFirst:=self;
24993 fKinematicRigidBodyPrevious:=nil;
24994 end;
24995 fPhysics.fKinematicRigidBodyLast:=self;
24996 fKinematicRigidBodyNext:=nil;
24997 fKinematicRigidBodyIsOnList:=true;
24998
24999 inc(fPhysics.fKinematicRigidBodyCount);
25000
25001 end;
25002 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
25003 end;
25004
25005 Shape:=fShapeFirst;
25006 while assigned(Shape) do begin
25007 Shape.SynchronizeProxies;
25008 Shape:=Shape.fShapeNext;
25009 end;
25010
25011 end;
25012
25013 result:=self;
25014 end;
25015
25016 function TKraftRigidBody.IsStatic:boolean;
25017 begin
25018 result:=fRigidBodyType=krbtStatic;
25019 end;
25020
25021 function TKraftRigidBody.IsDynamic:boolean;
25022 begin
25023 result:=fRigidBodyType=krbtDynamic;
25024 end;
25025
25026 function TKraftRigidBody.IsKinematic:boolean;
25027 begin
25028 result:=fRigidBodyType=krbtKinematic;
25029 end;
25030
25031 procedure TKraftRigidBody.SynchronizeTransform;
25032 begin
25033 fWorldTransform:=QuaternionToMatrix4x4(fSweep.q);
25034 PKraftVector3(pointer(@fWorldTransform[3,0]))^.xyz:=Vector3Sub(fSweep.c,Vector3TermMatrixMulBasis(fSweep.LocalCenter,fWorldTransform)).xyz;
25035 end;
25036
25037 procedure TKraftRigidBody.SynchronizeTransformIncludingShapes;
25038 var Shape:TKraftShape;
25039 begin
25040 SynchronizeTransform;
25041 Shape:=fShapeFirst;
25042 while assigned(Shape) do begin
25043 Shape.SynchronizeTransform;
25044 Shape:=Shape.fShapeNext;
25045 end;
25046 end;
25047
25048 procedure TKraftRigidBody.StoreWorldTransform;
25049 var Shape:TKraftShape;
25050 begin
25051 Shape:=fShapeFirst;
25052 while assigned(Shape) do begin
25053 Shape.StoreWorldTransform;
25054 Shape:=Shape.fShapeNext;
25055 end;
25056 end;
25057
25058 procedure TKraftRigidBody.InterpolateWorldTransform(const Alpha:TKraftScalar);
25059 var Shape:TKraftShape;
25060 begin
25061 Shape:=fShapeFirst;
25062 while assigned(Shape) do begin
25063 Shape.InterpolateWorldTransform(Alpha);
25064 Shape:=Shape.fShapeNext;
25065 end;
25066 end;
25067
25068 procedure TKraftRigidBody.Advance(Alpha:TKraftScalar);
25069 begin
25070 SweepAdvance(fSweep,Alpha);
25071 fSweep.c:=fSweep.c0;
25072 fSweep.q:=fSweep.q0;
25073 SynchronizeTransformIncludingShapes;
25074 end;
25075
25076 procedure TKraftRigidBody.UpdateWorldInertiaTensor;
25077 var Orientation:TKraftMatrix3x3;
25078 begin
25079 if fRigidBodyType=krbtDynamic then begin
25080 Orientation:=QuaternionToMatrix3x3(fSweep.q0);
25081 fWorldInverseInertiaTensor:=Matrix3x3TermMulTranspose(Matrix3x3TermMul(Orientation,fBodyInverseInertiaTensor),Orientation);
25082 //fWorldInverseInertiaTensor:=Matrix3x3TermMul(Matrix3x3TermMul(Orientation,fBodyInverseInertiaTensor),Matrix3x3TermTranspose(Orientation));
25083 Matrix3x3Inverse(fWorldInertiaTensor,fWorldInverseInertiaTensor);
25084 end;
25085 end;
25086
25087 procedure TKraftRigidBody.Finish;
25088 procedure CalculateMassData; {$ifdef caninline}inline;{$endif}
25089 var Shape:TKraftShape;
25090 TempLocalCenter:TKraftVector3;
25091 begin
25092
25093 FillChar(fBodyInertiaTensor,SizeOf(TKraftMatrix3x3),AnsiChar(#0));
25094 FillChar(fBodyInverseInertiaTensor,SizeOf(TKraftMatrix3x3),AnsiChar(#0));
25095
25096 FillChar(fWorldInertiaTensor,SizeOf(TKraftMatrix3x3),AnsiChar(#0));
25097 FillChar(fWorldInverseInertiaTensor,SizeOf(TKraftMatrix3x3),AnsiChar(#0));
25098
25099 fMass:=0.0;
25100 fInverseMass:=0.0;
25101
25102 if fRigidBodyType<>krbtDynamic then begin
25103
25104 fSweep.LocalCenter:=Vector3Origin;
25105 fSweep.c0.x:=fWorldTransform[3,0];
25106 fSweep.c0.y:=fWorldTransform[3,1];
25107 fSweep.c0.z:=fWorldTransform[3,2];
25108 fSweep.c:=fSweep.c0;
25109
25110 end else begin
25111
25112 TempLocalCenter:=Vector3Origin;
25113
25114 Shape:=fShapeFirst;
25115 while assigned(Shape) do begin
25116 if Shape is TKraftShapePlane then begin
25117 raise EKraftShapeTypeOnlyForStaticRigidBody.Create('Plane shapes are allowed only at static rigidbodies');
25118 end else if Shape is TKraftShapeTriangle then begin
25119 raise EKraftShapeTypeOnlyForStaticRigidBody.Create('Triangle shapes are allowed only at static rigidbodies');
25120 end else if Shape is TKraftShapeMesh then begin
25121 raise EKraftShapeTypeOnlyForStaticRigidBody.Create('Mesh shapes are allowed only at static rigidbodies');
25122 end;
25123 if (ksfMass in Shape.fFlags) and (Shape.fDensity>EPSILON) then begin
25124 fMass:=fMass+Shape.fMassData.Mass;
25125 Matrix3x3Add(fBodyInertiaTensor,Shape.fMassData.Inertia);
25126 TempLocalCenter:=Vector3Add(TempLocalCenter,Vector3ScalarMul(Shape.fMassData.Center,Shape.fMassData.Mass));
25127 end;
25128 Shape:=Shape.fShapeNext;
25129 end;
25130
25131 if fMass>EPSILON then begin
25132
25133 TempLocalCenter.x:=TempLocalCenter.x/fMass;
25134 TempLocalCenter.y:=TempLocalCenter.y/fMass;
25135 TempLocalCenter.z:=TempLocalCenter.z/fMass;
25136
25137 Matrix3x3Sub(fBodyInertiaTensor,InertiaTensorParallelAxisTheorem(TempLocalCenter,fMass));
25138
25139 { fBodyInertiaTensor[1,0]:=fBodyInertiaTensor[0,1];
25140 fBodyInertiaTensor[2,0]:=fBodyInertiaTensor[0,2];
25141 fBodyInertiaTensor[2,1]:=fBodyInertiaTensor[1,2];{}
25142
25143 if fForcedMass>EPSILON then begin
25144 Matrix3x3ScalarMul(fBodyInertiaTensor,fForcedMass/fMass);
25145 fMass:=fForcedMass;
25146 end;
25147
25148 fInverseMass:=1.0/fMass;
25149
25150 if krbfLockTranslationAxisX in fFlags then begin
25151 fLinearFactor.x:=0.0;
25152 end else begin
25153 fLinearFactor.x:=1.0;
25154 end;
25155
25156 if krbfLockTranslationAxisY in fFlags then begin
25157 fLinearFactor.y:=0.0;
25158 end else begin
25159 fLinearFactor.y:=1.0;
25160 end;
25161
25162 if krbfLockTranslationAxisZ in fFlags then begin
25163 fLinearFactor.z:=0.0;
25164 end else begin
25165 fLinearFactor.z:=1.0;
25166 end;
25167
25168 Matrix3x3Inverse(fBodyInverseInertiaTensor,fBodyInertiaTensor);
25169
25170 if (fFlags*[krbfLockRotationAxisX,
25171 krbfLockRotationAxisY,
25172 krbfLockRotationAxisZ])<>[] then begin
25173
25174 if krbfLockRotationAxisX in fFlags then begin
25175 fBodyInverseInertiaTensor[0,0]:=0.0;
25176 fBodyInverseInertiaTensor[0,1]:=0.0;
25177 fBodyInverseInertiaTensor[0,2]:=0.0;
25178 end;
25179
25180 if krbfLockRotationAxisY in fFlags then begin
25181 fBodyInverseInertiaTensor[1,0]:=0.0;
25182 fBodyInverseInertiaTensor[1,1]:=0.0;
25183 fBodyInverseInertiaTensor[1,2]:=0.0;
25184 end;
25185
25186 if krbfLockRotationAxisZ in fFlags then begin
25187 fBodyInverseInertiaTensor[2,0]:=0.0;
25188 fBodyInverseInertiaTensor[2,1]:=0.0;
25189 fBodyInverseInertiaTensor[2,2]:=0.0;
25190 end;
25191
25192 Matrix3x3Inverse(fBodyInertiaTensor,fBodyInverseInertiaTensor);
25193
25194 end;
25195
25196 end else begin
25197
25198 fInverseMass:=1.0;
25199
25200 end;
25201
25202 fSweep.LocalCenter:=TempLocalCenter;
25203 fSweep.c0:=Vector3TermMatrixMul(TempLocalCenter,fWorldTransform);
25204 fSweep.c:=fSweep.c0;
25205
25206 end;
25207
25208 end;
25209 var Shape:TKraftShape;
25210 begin
25211
25212 Shape:=fShapeFirst;
25213 while assigned(Shape) do begin
25214 Shape.Finish;
25215 Shape:=Shape.fShapeNext;
25216 end;
25217
25218 CalculateMassData;
25219
25220 SynchronizeTransform;
25221
25222 SynchronizeProxies;
25223
25224 UpdateWorldInertiaTensor;
25225
25226 end;
25227
25228 procedure TKraftRigidBody.SynchronizeProxies;
25229 var Shape:TKraftShape;
25230 NewTransform:TKraftMatrix4x4;
25231 begin
25232 NewTransform:=QuaternionToMatrix4x4(fSweep.q0);
25233 PKraftVector3(pointer(@NewTransform[3,0]))^.xyz:=Vector3Sub(fSweep.c0,Vector3TermMatrixMulBasis(fSweep.LocalCenter,NewTransform)).xyz;
25234 fWorldDisplacement:=Vector3Sub(PKraftVector3(pointer(@NewTransform[3,0]))^,PKraftVector3(pointer(@fWorldTransform[3,0]))^);
25235 Shape:=fShapeFirst;
25236 while assigned(Shape) do begin
25237 Shape.SynchronizeProxies;
25238 Shape:=Shape.fShapeNext;
25239 end;
25240 end;
25241
25242 procedure TKraftRigidBody.Refilter;
25243 var ContactPairEdge:PKraftContactPairEdge;
25244 ContactPair:PKraftContactPair;
25245 begin
25246 ContactPairEdge:=fContactPairEdgeFirst;
25247 while assigned(ContactPairEdge) do begin
25248 ContactPair:=ContactPairEdge^.ContactPair;
25249 if assigned(ContactPair) then begin
25250 ContactPair^.Flags:=ContactPair^.Flags+[kcfFiltered];
25251 if assigned(ContactPair^.MeshContactPair) then begin
25252 ContactPair^.MeshContactPair.fFlags:=ContactPair^.MeshContactPair.fFlags+[kcfFiltered];
25253 end;
25254 end;
25255 ContactPairEdge:=ContactPairEdge^.Next;
25256 end;
25257 end;
25258
25259 function TKraftRigidBody.CanCollideWith(OtherRigidBody:TKraftRigidBody):boolean;
25260 var ConstraintEdge:PKraftConstraintEdge;
25261 Constraint:TKraftConstraint;
25262 begin
25263 if (assigned(OtherRigidBody) and
25264 (self<>OtherRigidBody)) and // Don't collide with itself
25265 (((fRigidBodyType=krbtDynamic) or // Every collision must have at least one dynamic body involved
25266 (OtherRigidBody.fRigidBodyType=krbtDynamic)) and
25267 (((fCollisionGroups*OtherRigidBody.fCollideWithCollisionGroups)<>[]) or
25268 ((OtherRigidBody.fCollisionGroups*fCollideWithCollisionGroups)<>[])
25269 )
25270 ) then begin
25271 ConstraintEdge:=fConstraintEdgeFirst;
25272 while assigned(ConstraintEdge) do begin
25273 Constraint:=ConstraintEdge^.Constraint;
25274 if (assigned(Constraint) and not (kcfCollideConnected in Constraint.fFlags)) and (ConstraintEdge^.OtherRigidBody=OtherRigidBody) then begin
25275 result:=false;
25276 exit;
25277 end;
25278 ConstraintEdge:=ConstraintEdge^.Next;
25279 end;
25280 result:=true;
25281 end else begin
25282 result:=false;
25283 end;
25284 end;
25285
25286 procedure TKraftRigidBody.SetToAwake;
25287 var ConstraintEdge:PKraftConstraintEdge;
25288 begin
25289 if not (krbfAwake in fFlags) then begin
25290 Include(fFlags,krbfAwake);
25291 fSleepTime:=0.0;
25292 fWorldDisplacement:=Vector3Origin;
25293 ConstraintEdge:=fConstraintEdgeFirst;
25294 while assigned(ConstraintEdge) do begin
25295 if assigned(ConstraintEdge^.OtherRigidBody) and (ConstraintEdge^.OtherRigidBody<>self) then begin
25296 ConstraintEdge^.OtherRigidBody.SetToAwake;
25297 end;
25298 ConstraintEdge:=ConstraintEdge^.Next;
25299 end;
25300 end;
25301 end;
25302
25303 procedure TKraftRigidBody.SetToSleep;
25304 begin
25305 Exclude(fFlags,krbfAwake);
25306 fSleepTime:=0.0;
25307 fLinearVelocity:=Vector3Origin;
25308 fAngularVelocity:=Vector3Origin;
25309 fForce:=Vector3Origin;
25310 fTorque:=Vector3Origin;
25311 fWorldDisplacement:=Vector3Origin;
25312 end;
25313
25314 procedure TKraftRigidBody.SetWorldTransformation(const AWorldTransformation:TKraftMatrix4x4);
25315 begin
25316 fWorldTransform:=AWorldTransformation;
25317 UpdateWorldInertiaTensor;
25318 fSweep.c0:=Vector3TermMatrixMul(fSweep.LocalCenter,fWorldTransform);
25319 fSweep.c:=fSweep.c0;
25320 fSweep.q0:=QuaternionFromMatrix4x4(fWorldTransform);
25321 fSweep.q:=fSweep.q0;
25322 SynchronizeProxies;
25323 SetToAwake;
25324 end;
25325
25326 procedure TKraftRigidBody.SetWorldPosition(const AWorldPosition:TKraftVector3);
25327 begin
25328 PKraftVector3(pointer(@fWorldTransform[3,0]))^.xyz:=AWorldPosition.xyz;
25329 fSweep.c0:=Vector3Add(AWorldPosition,Vector3TermMatrixMulBasis(fSweep.LocalCenter,fWorldTransform));
25330 fSweep.c:=fSweep.c0;
25331 SynchronizeProxies;
25332 SetToAwake;
25333 end;
25334
25335 procedure TKraftRigidBody.SetOrientation(const AOrientation:TKraftMatrix3x3);
25336 begin
25337 PKraftVector3(pointer(@fWorldTransform[0,0]))^.xyz:=PKraftVector3(pointer(@AOrientation[0,0]))^.xyz;
25338 PKraftVector3(pointer(@fWorldTransform[1,0]))^.xyz:=PKraftVector3(pointer(@AOrientation[1,0]))^.xyz;
25339 PKraftVector3(pointer(@fWorldTransform[2,0]))^.xyz:=PKraftVector3(pointer(@AOrientation[2,0]))^.xyz;
25340 UpdateWorldInertiaTensor;
25341 fSweep.q0:=QuaternionFromMatrix3x3(AOrientation);
25342 fSweep.q:=fSweep.q0;
25343 SynchronizeProxies;
25344 SetToAwake;
25345 end;
25346
25347 procedure TKraftRigidBody.SetOrientation(const x,y,z:TKraftScalar);
25348 var Orientation:TKraftMatrix3x3;
25349 begin
25350 Orientation:=Matrix3x3RotateZ(z);
25351 Matrix3x3Mul(Orientation,Matrix3x3RotateY(y));
25352 Matrix3x3Mul(Orientation,Matrix3x3RotateX(x));
25353 PKraftVector3(pointer(@fWorldTransform[0,0]))^.xyz:=PKraftVector3(pointer(@Orientation[0,0]))^.xyz;
25354 PKraftVector3(pointer(@fWorldTransform[1,0]))^.xyz:=PKraftVector3(pointer(@Orientation[1,0]))^.xyz;
25355 PKraftVector3(pointer(@fWorldTransform[2,0]))^.xyz:=PKraftVector3(pointer(@Orientation[2,0]))^.xyz;
25356 UpdateWorldInertiaTensor;
25357 fSweep.q0:=QuaternionFromMatrix3x3(Orientation);
25358 fSweep.q:=fSweep.q0;
25359 SynchronizeProxies;
25360 SetToAwake;
25361 end;
25362
25363 procedure TKraftRigidBody.AddOrientation(const x,y,z:TKraftScalar);
25364 var Orientation:TKraftMatrix3x3;
25365 begin
25366 Orientation:=Matrix3x3RotateZ(z);
25367 Matrix3x3Mul(Orientation,Matrix3x3RotateY(y));
25368 Matrix3x3Mul(Orientation,Matrix3x3RotateX(x));
25369 Orientation:=Matrix3x3TermMul(Orientation,QuaternionToMatrix3x3(fSweep.q));
25370 PKraftVector3(pointer(@fWorldTransform[0,0]))^.xyz:=PKraftVector3(pointer(@Orientation[0,0]))^.xyz;
25371 PKraftVector3(pointer(@fWorldTransform[1,0]))^.xyz:=PKraftVector3(pointer(@Orientation[1,0]))^.xyz;
25372 PKraftVector3(pointer(@fWorldTransform[2,0]))^.xyz:=PKraftVector3(pointer(@Orientation[2,0]))^.xyz;
25373 UpdateWorldInertiaTensor;
25374 fSweep.q0:=QuaternionFromMatrix3x3(Orientation);
25375 fSweep.q:=fSweep.q0;
25376 SynchronizeProxies;
25377 SetToAwake;
25378 end;
25379
25380 procedure TKraftRigidBody.LimitVelocities;
25381 var Velocity:TKraftScalar;
25382 begin
25383 if fMaximalLinearVelocity>EPSILON then begin
25384 Velocity:=Vector3Length(fLinearVelocity);
25385 if Velocity>fMaximalLinearVelocity then begin
25386 Vector3Scale(fLinearVelocity,fMaximalLinearVelocity/Velocity);
25387 end;
25388 end;
25389 if fMaximalAngularVelocity>EPSILON then begin
25390 Velocity:=Vector3Length(fAngularVelocity);
25391 if Velocity>fMaximalAngularVelocity then begin
25392 Vector3Scale(fAngularVelocity,fMaximalAngularVelocity/Velocity);
25393 end;
25394 end;
25395 if fPhysics.fMaximalLinearVelocity>EPSILON then begin
25396 Velocity:=Vector3Length(fLinearVelocity);
25397 if Velocity>fPhysics.fMaximalLinearVelocity then begin
25398 Vector3Scale(fLinearVelocity,fPhysics.fMaximalLinearVelocity/Velocity);
25399 end;
25400 end;
25401 if fPhysics.fMaximalAngularVelocity>EPSILON then begin
25402 Velocity:=Vector3Length(fAngularVelocity);
25403 if Velocity>fPhysics.fMaximalAngularVelocity then begin
25404 Vector3Scale(fAngularVelocity,fPhysics.fMaximalAngularVelocity/Velocity);
25405 end;
25406 end;
25407 end;
25408
25409 procedure TKraftRigidBody.ApplyImpulseAtPosition(const Point,Impulse:TKraftVector3);
25410 begin
25411 fLinearVelocity:=Vector3Add(fLinearVelocity,Vector3Mul(Impulse,Vector3ScalarMul(fLinearFactor,fInverseMass)));
25412 fAngularVelocity:=Vector3Add(fAngularVelocity,Vector3TermMatrixMul(Vector3Cross(Vector3Sub(Point,fSweep.c),Impulse),fWorldInverseInertiaTensor));
25413 end;
25414
25415 procedure TKraftRigidBody.ApplyImpulseAtRelativePosition(const RelativePosition,Impulse:TKraftVector3);
25416 begin
25417 fLinearVelocity:=Vector3Add(fLinearVelocity,Vector3Mul(Impulse,Vector3ScalarMul(fLinearFactor,fInverseMass)));
25418 fAngularVelocity:=Vector3Add(fAngularVelocity,Vector3TermMatrixMul(Vector3Cross(RelativePosition,Impulse),fWorldInverseInertiaTensor));
25419 end;
25420
25421 procedure TKraftRigidBody.SetForceAtPosition(const AForce,APosition:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25422 begin
25423 SetWorldForce(AForce,AForceMode);
25424 SetWorldTorque(Vector3TermMatrixMul(Vector3Cross(Vector3Sub(APosition,fSweep.c),AForce),fWorldInverseInertiaTensor),AForceMode);
25425 end;
25426
25427 procedure TKraftRigidBody.AddForceAtPosition(const AForce,APosition:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25428 begin
25429 AddWorldForce(AForce,AForceMode);
25430 AddWorldTorque(Vector3TermMatrixMul(Vector3Cross(Vector3Sub(APosition,fSweep.c),AForce),fWorldInverseInertiaTensor),AForceMode);
25431 end;
25432
25433 procedure TKraftRigidBody.SetWorldForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25434 begin
25435 fForce:=Vector3Origin;
25436 AddWorldForce(AForce,AForceMode);
25437 end;
25438
25439 procedure TKraftRigidBody.AddWorldForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25440 begin
25441 case AForceMode of
25442 kfmForce:begin
25443 // The unit of the Force parameter is applied to the rigidbody as mass*distance/time^2.
25444 fForce:=Vector3Add(fForce,AForce);
25445 end;
25446 kfmAcceleration:begin
25447 // The unit of the Force parameter is applied to the rigidbody as distance/time^2.
25448 fForce:=Vector3Add(fForce,Vector3ScalarMul(AForce,fMass));
25449 end;
25450 kfmImpulse:begin
25451 // The unit of the Force parameter is applied to the rigidbody as mass*distance/time.
25452 fForce:=Vector3Add(fForce,Vector3ScalarMul(AForce,fPhysics.fWorldInverseDeltaTime));
25453 end;
25454 kfmVelocity:begin
25455 // The unit of the Force parameter is applied to the rigidbody as distance/time.
25456 fForce:=Vector3Add(fForce,Vector3ScalarMul(AForce,fMass*fPhysics.fWorldInverseDeltaTime));
25457 end;
25458 end;
25459 end;
25460
25461 procedure TKraftRigidBody.SetBodyForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25462 begin
25463 SetWorldForce(Vector3TermMatrixMulBasis(AForce,fWorldTransform),AForceMode);
25464 end;
25465
25466 procedure TKraftRigidBody.AddBodyForce(const AForce:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25467 begin
25468 AddWorldForce(Vector3TermMatrixMulBasis(AForce,fWorldTransform),AForceMode);
25469 end;
25470
25471 procedure TKraftRigidBody.SetWorldTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25472 begin
25473 fTorque:=Vector3Origin;
25474 AddWorldTorque(ATorque,AForceMode);
25475 end;
25476
25477 procedure TKraftRigidBody.AddWorldTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25478 begin
25479 case AForceMode of
25480 kfmForce:begin
25481 // The unit of the Torque parameter is applied to the rigidbody as mass*distance/time^2.
25482 fTorque:=Vector3Add(fTorque,ATorque);
25483 end;
25484 kfmAcceleration:begin
25485 // The unit of the Torque parameter is applied to the rigidbody as distance/time^2.
25486 fTorque:=Vector3Add(fTorque,Vector3ScalarMul(ATorque,fMass));
25487 end;
25488 kfmImpulse:begin
25489 // The unit of the Torque parameter is applied to the rigidbody as mass*distance/time.
25490 fTorque:=Vector3Add(fTorque,Vector3ScalarMul(ATorque,fPhysics.fWorldInverseDeltaTime));
25491 end;
25492 kfmVelocity:begin
25493 // The unit of the Torque parameter is applied to the rigidbody as distance/time.
25494 fTorque:=Vector3Add(fTorque,Vector3ScalarMul(ATorque,fMass*fPhysics.fWorldInverseDeltaTime));
25495 end;
25496 end;
25497 end;
25498
25499 procedure TKraftRigidBody.SetBodyTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25500 begin
25501 SetWorldTorque(Vector3TermMatrixMulBasis(ATorque,fWorldTransform),AForceMode);
25502 end;
25503
25504 procedure TKraftRigidBody.AddBodyTorque(const ATorque:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25505 begin
25506 AddWorldTorque(Vector3TermMatrixMulBasis(ATorque,fWorldTransform),AForceMode);
25507 end;
25508
25509 procedure TKraftRigidBody.SetWorldAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25510 begin
25511 fAngularVelocity:=Vector3Origin;
25512 AddWorldAngularVelocity(AAngularVelocity,AForceMode);
25513 end;
25514
25515 procedure TKraftRigidBody.AddWorldAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25516 begin
25517 case AForceMode of
25518 kfmForce:begin
25519 // The unit of the Torque parameter is applied to the rigidbody as mass*distance/time^2.
25520 fAngularVelocity:=Vector3Add(fAngularVelocity,Vector3ScalarMul(AAngularVelocity,fInverseMass*fPhysics.fWorldDeltaTime));
25521 end;
25522 kfmAcceleration:begin
25523 // The unit of the Torque parameter is applied to the rigidbody as distance/time^2.
25524 fAngularVelocity:=Vector3Add(fAngularVelocity,Vector3ScalarMul(AAngularVelocity,fPhysics.fWorldDeltaTime));
25525 end;
25526 kfmImpulse:begin
25527 // The unit of the Torque parameter is applied to the rigidbody as mass*distance/time.
25528 fAngularVelocity:=Vector3Add(fAngularVelocity,Vector3ScalarMul(AAngularVelocity,fInverseMass));
25529 end;
25530 kfmVelocity:begin
25531 // The unit of the Torque parameter is applied to the rigidbody as distance/time.
25532 fAngularVelocity:=Vector3Add(fAngularVelocity,AAngularVelocity);
25533 end;
25534 end;
25535 end;
25536
25537 procedure TKraftRigidBody.SetBodyAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25538 begin
25539 SetWorldAngularVelocity(Vector3TermMatrixMulBasis(AAngularVelocity,fWorldTransform),AForceMode);
25540 end;
25541
25542 procedure TKraftRigidBody.AddBodyAngularVelocity(const AAngularVelocity:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25543 begin
25544 AddWorldAngularVelocity(Vector3TermMatrixMulBasis(AAngularVelocity,fWorldTransform),AForceMode);
25545 end;
25546
25547 procedure TKraftRigidBody.SetWorldAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25548 begin
25549 SetWorldAngularVelocity(Vector3TermMatrixMul(AAngularMomentum,fWorldInverseInertiaTensor),AForceMode);
25550 end;
25551
25552 procedure TKraftRigidBody.AddWorldAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25553 begin
25554 AddWorldAngularVelocity(Vector3TermMatrixMul(AAngularMomentum,fWorldInverseInertiaTensor),AForceMode);
25555 end;
25556
25557 procedure TKraftRigidBody.SetBodyAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25558 begin
25559 SetBodyAngularVelocity(Vector3TermMatrixMul(AAngularMomentum,fBodyInverseInertiaTensor),AForceMode);
25560 end;
25561
25562 procedure TKraftRigidBody.AddBodyAngularMomentum(const AAngularMomentum:TKraftVector3;const AForceMode:TKraftForceMode=kfmForce);
25563 begin
25564 AddBodyAngularVelocity(Vector3TermMatrixMul(AAngularMomentum,fBodyInverseInertiaTensor),AForceMode);
25565 end;
25566
25567 function TKraftRigidBody.GetAngularMomentum:TKraftVector3;
25568 begin
25569 result:=Vector3TermMatrixMul(fAngularVelocity,fWorldInertiaTensor);
25570 end;
25571
25572 procedure TKraftRigidBody.SetAngularMomentum(const NewAngularMomentum:TKraftVector3);
25573 begin
25574 fAngularVelocity:=Vector3TermMatrixMul(NewAngularMomentum,fWorldInverseInertiaTensor);
25575 end;
25576
25577 constructor TKraftConstraint.Create(const APhysics:TKraft);
25578 var RigidBodyIndex:longint;
25579 RigidBody:TKraftRigidBody;
25580 ConstraintEdge:PKraftConstraintEdge;
25581 ContactPairEdge:PKraftContactPairEdge;
25582 ContactPair:PKraftContactPair;
25583 begin
25584
25585 inherited Create;
25586
25587 fPhysics:=APhysics;
25588
25589 fParent:=nil;
25590
25591 fChildren:=nil;
25592 fCountChildren:=0;
25593
25594 fUserData:=nil;
25595
25596 fFlags:=(fFlags-[kcfVisited])+[kcfActive];
25597
25598 if assigned(fPhysics.fConstraintLast) then begin
25599 fPhysics.fConstraintLast.fNext:=self;
25600 fPrevious:=fPhysics.fConstraintLast;
25601 end else begin
25602 fPhysics.fConstraintFirst:=self;
25603 fPrevious:=nil;
25604 end;
25605 fPhysics.fConstraintLast:=self;
25606 fNext:=nil;
25607
25608 for RigidBodyIndex:=0 to 1 do begin
25609 ConstraintEdge:=@fConstraintEdges[RigidBodyIndex];
25610 RigidBody:=fRigidBodies[RigidBodyIndex];
25611 if assigned(RigidBody) then begin
25612 inc(RigidBody.fCountConstraints);
25613 if assigned(RigidBody.fConstraintEdgeLast) then begin
25614 RigidBody.fConstraintEdgeLast.Next:=ConstraintEdge;
25615 ConstraintEdge^.Previous:=RigidBody.fConstraintEdgeLast;
25616 end else begin
25617 RigidBody.fConstraintEdgeFirst:=ConstraintEdge;
25618 ConstraintEdge^.Previous:=nil;
25619 end;
25620 RigidBody.fConstraintEdgeLast:=ConstraintEdge;
25621 ConstraintEdge^.Next:=nil;
25622 ConstraintEdge^.Constraint:=self;
25623 ConstraintEdge^.OtherRigidBody:=fRigidBodies[(RigidBodyIndex+1) and 1];
25624 end else begin
25625 ConstraintEdge^.Previous:=nil;
25626 ConstraintEdge^.Next:=nil;
25627 ConstraintEdge^.Constraint:=nil;
25628 ConstraintEdge^.OtherRigidBody:=nil;
25629 end;
25630 end;
25631
25632 // If the constraint prevents collisions, then flag any contacts for filtering.
25633 if not (kcfCollideConnected in fFlags) then begin
25634 for RigidBodyIndex:=0 to 1 do begin
25635 ConstraintEdge:=@fConstraintEdges[RigidBodyIndex];
25636 RigidBody:=fRigidBodies[RigidBodyIndex];
25637 if assigned(RigidBody) then begin
25638 ContactPairEdge:=RigidBody.fContactPairEdgeFirst;
25639 while assigned(ContactPairEdge) do begin
25640 ContactPair:=ContactPairEdge^.ContactPair;
25641 if assigned(ContactPair) then begin
25642 if ContactPairEdge^.OtherRigidBody=ConstraintEdge^.OtherRigidBody then begin
25643 // Flag the contact for filtering at the next time step (where either rigid body is awake).
25644 ContactPair^.Flags:=ContactPair^.Flags+[kcfFiltered];
25645 if assigned(ContactPair^.MeshContactPair) then begin
25646 ContactPair^.MeshContactPair.fFlags:=ContactPair^.MeshContactPair.fFlags+[kcfFiltered];
25647 end;
25648 end;
25649 end;
25650 ContactPairEdge:=ContactPairEdge^.Next;
25651 end;
25652 end;
25653 end;
25654 end;
25655
25656 for RigidBodyIndex:=0 to 1 do begin
25657 RigidBody:=fRigidBodies[RigidBodyIndex];
25658 if assigned(RigidBody) then begin
25659 RigidBody.SetToAwake;
25660 end;
25661 end;
25662
25663 fBreakThresholdForce:=MAX_SCALAR;
25664
25665 fBreakThresholdTorque:=MAX_SCALAR;
25666
25667 fOnBreak:=nil;
25668
25669 end;
25670
25671 destructor TKraftConstraint.Destroy;
25672 var RigidBodyIndex,ConstraintIndex:longint;
25673 RigidBody:TKraftRigidBody;
25674 Constraint:TKraftConstraint;
25675 ConstraintEdge:PKraftConstraintEdge;
25676 ContactPairEdge:PKraftContactPairEdge;
25677 ContactPair:PKraftContactPair;
25678 begin
25679
25680 if assigned(fParent) then begin
25681 for ConstraintIndex:=0 to fParent.fCountChildren-1 do begin
25682 if fParent.fChildren[ConstraintIndex]=self then begin
25683 fParent.fChildren[ConstraintIndex]:=nil;
25684 end;
25685 end;
25686 end;
25687
25688 if fCountChildren>0 then begin
25689 for ConstraintIndex:=0 to fCountChildren-1 do begin
25690 Constraint:=fChildren[ConstraintIndex];
25691 if assigned(Constraint) then begin
25692 fChildren[ConstraintIndex]:=nil;
25693 Constraint.Free;
25694 end;
25695 end;
25696 SetLength(fChildren,0);
25697 end;
25698
25699 if assigned(fPrevious) then begin
25700 fPrevious.fNext:=fNext;
25701 end else if fPhysics.fConstraintFirst=self then begin
25702 fPhysics.fConstraintFirst:=fNext;
25703 end;
25704 if assigned(fNext) then begin
25705 fNext.fPrevious:=fPrevious;
25706 end else if fPhysics.fConstraintLast=self then begin
25707 fPhysics.fConstraintLast:=fPrevious;
25708 end;
25709 fPrevious:=nil;
25710 fNext:=nil;
25711
25712 for RigidBodyIndex:=0 to 1 do begin
25713 RigidBody:=fRigidBodies[RigidBodyIndex];
25714 if assigned(RigidBody) then begin
25715 RigidBody.SetToAwake;
25716 end;
25717 end;
25718
25719 for RigidBodyIndex:=0 to 1 do begin
25720 RigidBody:=fRigidBodies[RigidBodyIndex];
25721 if assigned(RigidBody) then begin
25722 dec(RigidBody.fCountConstraints);
25723 ConstraintEdge:=@fConstraintEdges[RigidBodyIndex];
25724 if assigned(ConstraintEdge^.Previous) then begin
25725 ConstraintEdge^.Previous.Next:=ConstraintEdge^.Next;
25726 end else if RigidBody.fConstraintEdgeFirst=ConstraintEdge then begin
25727 RigidBody.fConstraintEdgeFirst:=ConstraintEdge^.Next;
25728 end;
25729 if assigned(ConstraintEdge^.Next) then begin
25730 ConstraintEdge^.Next.Previous:=ConstraintEdge^.Previous;
25731 end else if RigidBody.fConstraintEdgeLast=ConstraintEdge then begin
25732 RigidBody.fConstraintEdgeLast:=ConstraintEdge^.Previous;
25733 end;
25734 ConstraintEdge^.Previous:=nil;
25735 ConstraintEdge^.Next:=nil;
25736 end;
25737 end;
25738
25739 // If the constraint prevents collisions, then flag any contacts for filtering.
25740 if not (kcfCollideConnected in fFlags) then begin
25741 for RigidBodyIndex:=0 to 1 do begin
25742 ConstraintEdge:=@fConstraintEdges[RigidBodyIndex];
25743 RigidBody:=fRigidBodies[RigidBodyIndex];
25744 if assigned(RigidBody) then begin
25745 ContactPairEdge:=RigidBody.fContactPairEdgeFirst;
25746 while assigned(ContactPairEdge) do begin
25747 ContactPair:=ContactPairEdge^.ContactPair;
25748 if assigned(ContactPair) then begin
25749 if ContactPairEdge^.OtherRigidBody=ConstraintEdge^.OtherRigidBody then begin
25750 // Flag the contact for filtering at the next time step (where either rigid body is awake).
25751 ContactPair^.Flags:=ContactPair^.Flags+[kcfFiltered];
25752 if assigned(ContactPair^.MeshContactPair) then begin
25753 ContactPair^.MeshContactPair.fFlags:=ContactPair^.MeshContactPair.fFlags+[kcfFiltered];
25754 end;
25755 end;
25756 end;
25757 ContactPairEdge:=ContactPairEdge^.Next;
25758 end;
25759 end;
25760 end;
25761 end;
25762
25763 inherited Destroy;
25764 end;
25765
25766 procedure TKraftConstraint.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
25767 begin
25768 end;
25769
25770 procedure TKraftConstraint.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
25771 begin
25772 end;
25773
25774 function TKraftConstraint.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
25775 begin
25776 result:=true;
25777 end;
25778
25779 function TKraftConstraint.GetAnchorA:TKraftVector3;
25780 begin
25781 result:=Vector3Origin;
25782 end;
25783
25784 function TKraftConstraint.GetAnchorB:TKraftVector3;
25785 begin
25786 result:=Vector3Origin;
25787 end;
25788
25789 function TKraftConstraint.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
25790 begin
25791 result:=Vector3Origin;
25792 end;
25793
25794 function TKraftConstraint.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
25795 begin
25796 result:=Vector3Origin;
25797 end;
25798
25799 constructor TKraftConstraintJointGrab.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const AWorldPoint:TKraftVector3;const AFrequencyHz:TKraftScalar=5.0;const ADampingRatio:TKraftScalar=0.7;const AMaximalForce:TKraftScalar=MAX_SCALAR;const ACollideConnected:boolean=false);
25800 begin
25801
25802 fWorldPoint:=AWorldPoint;
25803
25804 fLocalAnchor:=Vector3TermMatrixMulInverted(AWorldPoint,ARigidBody.fWorldTransform);
25805
25806 fFrequencyHz:=AFrequencyHz;
25807 fDampingRatio:=ADampingRatio;
25808 fAccumulatedImpulse:=Vector3Origin;
25809 fBeta:=0.0;
25810 fGamma:=0.0;
25811
25812 fMaximalForce:=AMaximalForce;
25813
25814 if ACollideConnected then begin
25815 Include(fFlags,kcfCollideConnected);
25816 end else begin
25817 Exclude(fFlags,kcfCollideConnected);
25818 end;
25819
25820 fRigidBodies[0]:=ARigidBody;
25821 fRigidBodies[1]:=nil;
25822
25823 inherited Create(APhysics);
25824
25825 end;
25826
25827 destructor TKraftConstraintJointGrab.Destroy;
25828 begin
25829 inherited Destroy;
25830 end;
25831
25832 procedure TKraftConstraintJointGrab.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
25833 {$define TKraftConstraintJointGrabMassMatrixCodeVariantA}
25834 var cA,vA,wA:PKraftVector3;
25835 qA:PKraftQuaternion;
25836 Omega,k,h,d:TKraftScalar;
25837 {$if defined(TKraftConstraintJointGrabMassMatrixCodeVariantC)}SkewSymmetricMatrix,{$ifend}MassMatrix:TKraftMatrix3x3;
25838 begin
25839
25840 fIslandIndex:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
25841
25842 fLocalCenter:=fRigidBodies[0].fSweep.LocalCenter;
25843
25844 fInverseMass:=fRigidBodies[0].fInverseMass;
25845
25846 fWorldInverseInertiaTensor:=fRigidBodies[0].fWorldInverseInertiaTensor;
25847
25848 fSolverVelocity:[email protected][fIslandIndex];
25849
25850 fSolverPosition:[email protected][fIslandIndex];
25851
25852 fSolverLinearFactor:[email protected][fIslandIndex];
25853
25854 cA:=@fSolverPosition^.Position;
25855 qA:=@fSolverPosition^.Orientation;
25856 vA:=@fSolverVelocity^.LinearVelocity;
25857 wA:=@fSolverVelocity^.AngularVelocity;
25858
25859 // Compute the effective mass matrix
25860 if fInverseMass<>0.0 then begin
25861 fMass:=1.0/fInverseMass;
25862 end else begin
25863 fMass:=0.0;
25864 end;
25865
25866 // fFrequency
25867 Omega:=pi2*fFrequencyHz;
25868
25869 // Damping coefficient
25870 d:=2.0*fMass*fDampingRatio*Omega;
25871
25872 // Spring stiffness
25873 k:=fMass*sqr(Omega);
25874
25875 // Magic formulas
25876 h:=TimeStep.DeltaTime;
25877 fGamma:=h*(d+(h*k));
25878 if fGamma<>0.0 then begin
25879 fGamma:=1.0/fGamma;
25880 end else begin
25881 fGamma:=0.0;
25882 end;
25883 fBeta:=h*k*fGamma;
25884
25885 fRelativePosition:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchor,fLocalCenter),qA^);
25886
25887 {$if defined(TKraftConstraintJointGrabMassMatrixCodeVariantA)}
25888
25889 MassMatrix[0,0]:=((fInverseMass+fGamma)-
25890 (fRelativePosition.z*((fWorldInverseInertiaTensor[1,2]*fRelativePosition.y)-(fWorldInverseInertiaTensor[1,1]*fRelativePosition.z))))+
25891 (fRelativePosition.y*((fWorldInverseInertiaTensor[2,2]*fRelativePosition.y)-(fWorldInverseInertiaTensor[2,1]*fRelativePosition.z)));
25892 MassMatrix[0,1]:=(fRelativePosition.z*((fWorldInverseInertiaTensor[0,2]*fRelativePosition.y)-(fWorldInverseInertiaTensor[0,1]*fRelativePosition.z)))-
25893 (fRelativePosition.x*((fWorldInverseInertiaTensor[2,2]*fRelativePosition.y)-(fWorldInverseInertiaTensor[2,1]*fRelativePosition.z)));
25894 MassMatrix[0,2]:=(fRelativePosition.x*((fWorldInverseInertiaTensor[1,2]*fRelativePosition.y)-(fWorldInverseInertiaTensor[1,1]*fRelativePosition.z)))-
25895 (fRelativePosition.y*((fWorldInverseInertiaTensor[0,2]*fRelativePosition.y)-(fWorldInverseInertiaTensor[0,1]*fRelativePosition.z)));
25896 MassMatrix[1,0]:=(fRelativePosition.z*((fWorldInverseInertiaTensor[1,2]*fRelativePosition.x)-(fWorldInverseInertiaTensor[1,0]*fRelativePosition.z)))-
25897 (fRelativePosition.y*((fWorldInverseInertiaTensor[2,2]*fRelativePosition.x)-(fWorldInverseInertiaTensor[2,0]*fRelativePosition.z)));
25898 MassMatrix[1,1]:=((fInverseMass+fGamma)-
25899 (fRelativePosition.z*((fWorldInverseInertiaTensor[0,2]*fRelativePosition.x)-(fWorldInverseInertiaTensor[0,0]*fRelativePosition.z))))+
25900 (fRelativePosition.x*((fWorldInverseInertiaTensor[2,2]*fRelativePosition.x)-(fWorldInverseInertiaTensor[2,0]*fRelativePosition.z)));
25901 MassMatrix[1,2]:=(fRelativePosition.y*((fWorldInverseInertiaTensor[0,2]*fRelativePosition.x)-(fWorldInverseInertiaTensor[0,0]*fRelativePosition.z)))-
25902 (fRelativePosition.x*((fWorldInverseInertiaTensor[1,2]*fRelativePosition.x)-(fWorldInverseInertiaTensor[1,0]*fRelativePosition.z)));
25903 MassMatrix[2,0]:=(fRelativePosition.y*((fWorldInverseInertiaTensor[2,1]*fRelativePosition.x)-(fWorldInverseInertiaTensor[2,0]*fRelativePosition.y)))-
25904 (fRelativePosition.z*((fWorldInverseInertiaTensor[1,1]*fRelativePosition.x)-(fWorldInverseInertiaTensor[1,0]*fRelativePosition.y)));
25905 MassMatrix[2,1]:=(fRelativePosition.z*((fWorldInverseInertiaTensor[0,1]*fRelativePosition.x)-(fWorldInverseInertiaTensor[0,0]*fRelativePosition.y)))-
25906 (fRelativePosition.x*((fWorldInverseInertiaTensor[2,1]*fRelativePosition.x)-(fWorldInverseInertiaTensor[2,0]*fRelativePosition.y)));
25907 MassMatrix[2,2]:=((fInverseMass+fGamma)-
25908 (fRelativePosition.y*((fWorldInverseInertiaTensor[0,1]*fRelativePosition.x)-(fWorldInverseInertiaTensor[0,0]*fRelativePosition.y))))+
25909 (fRelativePosition.x*((fWorldInverseInertiaTensor[1,1]*fRelativePosition.x)-(fWorldInverseInertiaTensor[1,0]*fRelativePosition.y)));
25910
25911 {$elseif defined(TKraftConstraintJointGrabMassMatrixCodeVariantB)}
25912
25913 MassMatrix[0,0]:=(((sqr(fRelativePosition.z)*fWorldInverseInertiaTensor[1,1])-
25914 ((fRelativePosition.y*fRelativePosition.z)*(fWorldInverseInertiaTensor[1,2]+fWorldInverseInertiaTensor[2,1])))+
25915 (sqr(fRelativePosition.y)*fWorldInverseInertiaTensor[2,2]))+
25916 (fInverseMass+fGamma);
25917 MassMatrix[0,1]:=(((-(sqr(fRelativePosition.z)*fWorldInverseInertiaTensor[1,0]))+
25918 ((fRelativePosition.x*fRelativePosition.z)*fWorldInverseInertiaTensor[1,2]))+
25919 ((fRelativePosition.y*fRelativePosition.z)*fWorldInverseInertiaTensor[2,0]))-
25920 ((fRelativePosition.x*fRelativePosition.y)*fWorldInverseInertiaTensor[2,2]);
25921 MassMatrix[0,2]:=((((fRelativePosition.y*fRelativePosition.z)*fWorldInverseInertiaTensor[1,0])-
25922 ((fRelativePosition.x*fRelativePosition.z)*fWorldInverseInertiaTensor[1,1]))-
25923 (sqr(fRelativePosition.y)*fWorldInverseInertiaTensor[2,0]))+
25924 ((fRelativePosition.x*fRelativePosition.y)*fWorldInverseInertiaTensor[2,1]);
25925 MassMatrix[1,0]:=(((-(sqr(fRelativePosition.z)*fWorldInverseInertiaTensor[0,1]))+
25926 ((fRelativePosition.y*fRelativePosition.z)*fWorldInverseInertiaTensor[0,2]))+
25927 ((fRelativePosition.x*fRelativePosition.z)*fWorldInverseInertiaTensor[2,1]))-
25928 ((fRelativePosition.x*fRelativePosition.y)*fWorldInverseInertiaTensor[2,2]);
25929 MassMatrix[1,1]:=(((sqr(fRelativePosition.z)*fWorldInverseInertiaTensor[0,0])-
25930 ((fRelativePosition.x*fRelativePosition.z)*(fWorldInverseInertiaTensor[0,2]+fWorldInverseInertiaTensor[2,0])))+
25931 (sqr(fRelativePosition.x)*fWorldInverseInertiaTensor[2,2]))+
25932 (fInverseMass+fGamma);
25933 MassMatrix[1,2]:=(((-((fRelativePosition.y*fRelativePosition.z)*fWorldInverseInertiaTensor[0,0]))+
25934 ((fRelativePosition.x*fRelativePosition.z)*fWorldInverseInertiaTensor[0,1]))+
25935 ((fRelativePosition.x*fRelativePosition.y)*fWorldInverseInertiaTensor[2,0]))-
25936 (sqr(fRelativePosition.x)*fWorldInverseInertiaTensor[2,1]);
25937 MassMatrix[2,0]:=((((fRelativePosition.y*fRelativePosition.z)*fWorldInverseInertiaTensor[0,1])-
25938 (sqr(fRelativePosition.y)*fWorldInverseInertiaTensor[0,2]))-
25939 ((fRelativePosition.x*fRelativePosition.z)*fWorldInverseInertiaTensor[1,1]))+
25940 ((fRelativePosition.x*fRelativePosition.y)*fWorldInverseInertiaTensor[1,2]);
25941 MassMatrix[2,1]:=(((-((fRelativePosition.y*fRelativePosition.z)*fWorldInverseInertiaTensor[0,0]))+
25942 ((fRelativePosition.x*fRelativePosition.y)*fWorldInverseInertiaTensor[0,2])+
25943 ((fRelativePosition.x*fRelativePosition.z)*fWorldInverseInertiaTensor[1,0])))-
25944 (sqr(fRelativePosition.x)*fWorldInverseInertiaTensor[1,2]);
25945 MassMatrix[2,2]:=(((sqr(fRelativePosition.y)*fWorldInverseInertiaTensor[0,0])-
25946 ((fRelativePosition.x*fRelativePosition.y)*(fWorldInverseInertiaTensor[0,1]+fWorldInverseInertiaTensor[1,0])))+
25947 (sqr(fRelativePosition.x)*fWorldInverseInertiaTensor[1,1]))+
25948 (fInverseMass+fGamma);
25949
25950 {$else}
25951
25952 MassMatrix[0,0]:=fInverseMass+fGamma;
25953 MassMatrix[0,1]:=0.0;
25954 MassMatrix[0,2]:=0.0;
25955 {$ifdef SIMD}
25956 MassMatrix[0,3]:=0.0;
25957 {$endif}
25958 MassMatrix[1,0]:=0.0;
25959 MassMatrix[1,1]:=MassMatrix[0,0];
25960 MassMatrix[1,2]:=0.0;
25961 {$ifdef SIMD}
25962 MassMatrix[1,3]:=0.0;
25963 {$endif}
25964 MassMatrix[2,0]:=0.0;
25965 MassMatrix[2,1]:=0.0;
25966 MassMatrix[2,2]:=MassMatrix[0,0];
25967 {$ifdef SIMD}
25968 MassMatrix[2,3]:=0.0;
25969 {$endif}
25970
25971 SkewSymmetricMatrix:=GetSkewSymmetricMatrixPlus(fRelativePosition);
25972
25973 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrix,fWorldInverseInertiaTensor),SkewSymmetricMatrix));
25974
25975 {$ifend}
25976
25977 Matrix3x3Inverse(fEffectiveMass,MassMatrix);
25978
25979 fmC:=Vector3ScalarMul(Vector3Sub(Vector3Add(cA^,fRelativePosition),fWorldPoint),fBeta);
25980
25981 Vector3Scale(wA^,0.98);
25982
25983 if fPhysics.fWarmStarting then begin
25984
25985 fAccumulatedImpulse:=Vector3ScalarMul(fAccumulatedImpulse,TimeStep.DeltaTimeRatio);
25986
25987 Vector3DirectAdd(vA^,Vector3Mul(fAccumulatedImpulse,Vector3ScalarMul(fSolverLinearFactor^,fInverseMass)));
25988 Vector3DirectAdd(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePosition,fAccumulatedImpulse),fWorldInverseInertiaTensor));
25989
25990 end else begin
25991
25992 fAccumulatedImpulse:=Vector3Origin;
25993
25994 end;
25995
25996 end;
25997
25998 procedure TKraftConstraintJointGrab.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
25999 var vA,wA:PKraftVector3;
26000 Cdot,Impulse,OldImpulse:TKraftVector3;
26001 MaximalImpulse:TKraftScalar;
26002 begin
26003
26004 vA:=@fSolverVelocity^.LinearVelocity;
26005 wA:=@fSolverVelocity^.AngularVelocity;
26006
26007 // Cdot = dot(u, v + cross(w, r))
26008 Cdot:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePosition));
26009
26010 Impulse:=Vector3TermMatrixMul(Vector3Neg(Vector3Add(Cdot,Vector3Add(fmC,Vector3ScalarMul(fAccumulatedImpulse,fGamma)))),fEffectiveMass);
26011
26012 OldImpulse:=fAccumulatedImpulse;
26013 Vector3DirectAdd(fAccumulatedImpulse,Impulse);
26014 MaximalImpulse:=fMaximalForce*TimeStep.DeltaTime;
26015 if Vector3Length(fAccumulatedImpulse)>MaximalImpulse then begin
26016 Vector3Scale(fAccumulatedImpulse,MaximalImpulse/Vector3Length(fAccumulatedImpulse));
26017 end;
26018 Impulse:=Vector3Sub(fAccumulatedImpulse,OldImpulse);
26019
26020 Vector3DirectAdd(vA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactor^,fInverseMass)));
26021 Vector3DirectAdd(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePosition,Impulse),fWorldInverseInertiaTensor));
26022
26023 end;
26024
26025 function TKraftConstraintJointGrab.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
26026 begin
26027 result:=true;
26028 end;
26029
26030 function TKraftConstraintJointGrab.GetAnchor:TKraftVector3;
26031 begin
26032 result:=Vector3TermMatrixMul(fLocalAnchor,fRigidBodies[0].fWorldTransform);
26033 end;
26034
26035 function TKraftConstraintJointGrab.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26036 begin
26037 result:=Vector3ScalarMul(fAccumulatedImpulse,InverseDeltaTime);
26038 end;
26039
26040 function TKraftConstraintJointGrab.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26041 begin
26042 result:=Vector3Origin;
26043 end;
26044
26045 function TKraftConstraintJointGrab.GetWorldPoint:TKraftVector3;
26046 begin
26047 result:=fWorldPoint;
26048 end;
26049
26050 function TKraftConstraintJointGrab.GetMaximalForce:TKraftScalar;
26051 begin
26052 result:=fMaximalForce;
26053 end;
26054
26055 procedure TKraftConstraintJointGrab.SetWorldPoint(AWorldPoint:TKraftVector3);
26056 begin
26057 fWorldPoint:=AWorldPoint;
26058 end;
26059
26060 procedure TKraftConstraintJointGrab.SetMaximalForce(AMaximalForce:TKraftScalar);
26061 begin
26062 fMaximalForce:=AMaximalForce;
26063 end;
26064
26065 constructor TKraftConstraintJointWorldPlaneDistance.Create(const APhysics:TKraft;const ARigidBody:TKraftRigidBody;const ALocalAnchorPoint:TKraftVector3;const AWorldPlane:TKraftPlane;const ADoubleSidedWorldPlane:boolean=true;const AWorldDistance:single=1.0;const ALimitBehavior:TKraftConstraintLimitBehavior=kclbLimitDistance;const AFrequencyHz:TKraftScalar=0.0;const ADampingRatio:TKraftScalar=0.0;const AInverseInertiaTensorRatio:TKraftScalar=1.0;const ACollideConnected:boolean=false);
26066 begin
26067
26068 fLocalAnchor:=ALocalAnchorPoint;
26069
26070 fWorldPlane:=AWorldPlane;
26071
26072 fWorldPoint:=Vector3ScalarMul(AWorldPlane.Normal,-AWorldPlane.Distance);
26073
26074 fDoubleSidedWorldPlane:=ADoubleSidedWorldPlane;
26075
26076 fWorldDistance:=AWorldDistance;
26077
26078 //fAnchorDistanceLength:=AWorldDistance;//Vector3Dist(fWorldPoint,Vector3TermMatrixMul(ALocalAnchorPoint,ARigidBody.fWorldTransform));
26079
26080 fLimitBehavior:=ALimitBehavior;
26081
26082 fFrequencyHz:=AFrequencyHz;
26083 fDampingRatio:=ADampingRatio;
26084 fInverseInertiaTensorRatio:=AInverseInertiaTensorRatio;
26085 fAccumulatedImpulse:=0.0;
26086 fGamma:=0.0;
26087 fBias:=0.0;
26088
26089 if ACollideConnected then begin
26090 Include(fFlags,kcfCollideConnected);
26091 end else begin
26092 Exclude(fFlags,kcfCollideConnected);
26093 end;
26094
26095 fRigidBodies[0]:=ARigidBody;
26096 fRigidBodies[1]:=nil;
26097
26098 inherited Create(APhysics);
26099
26100 end;
26101
26102 destructor TKraftConstraintJointWorldPlaneDistance.Destroy;
26103 begin
26104 inherited Destroy;
26105 end;
26106
26107 procedure TKraftConstraintJointWorldPlaneDistance.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26108 var cA,vA,wA:PKraftVector3;
26109 qA:PKraftQuaternion;
26110 crAu,P,AbsolutePosition,u:TKraftVector3;
26111 l,TotalInverseMass,C,Omega,k,h,d,BiasFactor:TKraftScalar;
26112 begin
26113
26114 fIslandIndex:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
26115
26116 fLocalCenter:=fRigidBodies[0].fSweep.LocalCenter;
26117
26118 fInverseMass:=fRigidBodies[0].fInverseMass;
26119
26120 fWorldInverseInertiaTensor:=Matrix3x3TermScalarMul(fRigidBodies[0].fWorldInverseInertiaTensor,fInverseInertiaTensorRatio);
26121
26122 fSolverVelocity:[email protected][fIslandIndex];
26123
26124 fSolverPosition:[email protected][fIslandIndex];
26125
26126 fSolverLinearFactor:[email protected][fIslandIndex];
26127
26128 cA:=@fSolverPosition^.Position;
26129 qA:=@fSolverPosition^.Orientation;
26130 vA:=@fSolverVelocity^.LinearVelocity;
26131 wA:=@fSolverVelocity^.AngularVelocity;
26132
26133 fRelativePosition:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchor,fLocalCenter),qA^);
26134 AbsolutePosition:=Vector3Add(cA^,fRelativePosition);
26135
26136 fWorldPoint:=Vector3Add(AbsolutePosition,Vector3ScalarMul(fWorldPlane.Normal,-PlaneVectorDistance(fWorldPlane,AbsolutePosition)));
26137
26138 if fDoubleSidedWorldPlane then begin
26139
26140 fmU:=Vector3Sub(fWorldPoint,AbsolutePosition);
26141
26142 // Handle singularity
26143 l:=Vector3Length(fmU);
26144 if l>fPhysics.fLinearSlop then begin
26145 Vector3Scale(fmU,1.0/l);
26146 end else begin
26147 fmU:=Vector3Origin;
26148 end;
26149
26150 end else begin
26151
26152 l:=PlaneVectorDistance(fWorldPlane,AbsolutePosition);
26153
26154 if abs(l)>fPhysics.fLinearSlop then begin
26155 fmU:=Vector3Neg(fWorldPlane.Normal);
26156 end else begin
26157 fmU:=Vector3Origin;
26158 end;
26159
26160 end;
26161
26162 fSoftConstraint:=fFrequencyHz>EPSILON;
26163
26164 if fSoftConstraint then begin
26165
26166 // No limit state skipping for soft contraints
26167 fSkip:=false;
26168
26169 end else begin
26170
26171 // Limit state skipping for non-soft contraints
26172 case fLimitBehavior of
26173 kclbLimitMinimumDistance:begin
26174 fSkip:=l>(fWorldDistance+fPhysics.fLinearSlop);
26175 end;
26176 kclbLimitMaximumDistance:begin
26177 fSkip:=l<(fWorldDistance-fPhysics.fLinearSlop);
26178 end;
26179 else begin
26180 fSkip:=false;
26181 end;
26182 end;
26183
26184 end;
26185
26186 if not fSkip then begin
26187
26188 crAu:=Vector3Cross(fRelativePosition,fmU);
26189
26190 TotalInverseMass:=fRigidBodies[0].fInverseMass+
26191 Vector3Dot(Vector3TermMatrixMul(crAu,fWorldInverseInertiaTensor),crAu);
26192
26193 // Compute the effective mass matrix
26194 if TotalInverseMass<>0.0 then begin
26195 fMass:=1.0/TotalInverseMass;
26196 end else begin
26197 fMass:=0.0;
26198 end;
26199
26200 if fSoftConstraint then begin
26201
26202 C:=l-fWorldDistance;
26203
26204 // fFrequency
26205 Omega:=pi2*fFrequencyHz;
26206
26207 // Damping coefficient
26208 d:=2.0*fMass*fDampingRatio*Omega;
26209
26210 // Spring stiffness
26211 k:=fMass*sqr(Omega);
26212
26213 // Magic formulas
26214 h:=TimeStep.DeltaTime;
26215 fGamma:=h*(d+(h*k));
26216 if fGamma<>0.0 then begin
26217 fGamma:=1.0/fGamma;
26218 end else begin
26219 fGamma:=0.0;
26220 end;
26221 fBias:=C*h*k*fGamma;
26222
26223 TotalInverseMass:=TotalInverseMass+fGamma;
26224
26225 if TotalInverseMass<>0.0 then begin
26226 fMass:=1.0/TotalInverseMass;
26227 end else begin
26228 fMass:=0.0;
26229 end;
26230
26231 end else begin
26232
26233 fGamma:=0.0;
26234 fBias:=0.0;
26235
26236 end;
26237
26238 if fPhysics.fConstraintPositionCorrectionMode=kpcmBaumgarte then begin
26239 AbsolutePosition:=Vector3Add(cA^,fRelativePosition);
26240 if fDoubleSidedWorldPlane then begin
26241 fWorldPoint:=Vector3Add(AbsolutePosition,Vector3ScalarMul(fWorldPlane.Normal,-PlaneVectorDistance(fWorldPlane,AbsolutePosition)));
26242 u:=Vector3Sub(fWorldPoint,AbsolutePosition);
26243 l:=Vector3LengthNormalize(u);
26244 C:=Min(Max(l-fWorldDistance,-fPhysics.fMaximalLinearCorrection),fPhysics.fMaximalLinearCorrection);
26245 end else begin
26246 C:=Min(Max(fWorldDistance-PlaneVectorDistance(fWorldPlane,AbsolutePosition),-fPhysics.fMaximalLinearCorrection),fPhysics.fMaximalLinearCorrection);
26247 end;
26248 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
26249 fBias:=fBias+(C*BiasFactor);
26250 end;
26251
26252 end;
26253
26254 if fPhysics.fWarmStarting and not fSkip then begin
26255
26256 fAccumulatedImpulse:=fAccumulatedImpulse*TimeStep.DeltaTimeRatio;
26257
26258 P:=Vector3ScalarMul(fmU,fAccumulatedImpulse);
26259
26260 Vector3DirectSub(vA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactor^,fInverseMass)));
26261 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePosition,P),fWorldInverseInertiaTensor));
26262
26263 end else begin
26264
26265 fAccumulatedImpulse:=0.0;
26266
26267 end;
26268
26269
26270 end;
26271
26272 procedure TKraftConstraintJointWorldPlaneDistance.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26273 var vA,wA:PKraftVector3;
26274 vpA,P:TKraftVector3;
26275 Cdot,Impulse,OldImpulse:TKraftScalar;
26276 begin
26277
26278 if not fSkip then begin
26279
26280 vA:=@fSolverVelocity^.LinearVelocity;
26281 wA:=@fSolverVelocity^.AngularVelocity;
26282
26283 // Cdot = dot(u, v + cross(w, r))
26284 vpA:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePosition));
26285 Cdot:=Vector3Dot(fmU,Vector3Neg(vpA));
26286
26287 Impulse:=-(fMass*((Cdot+fBias)+(fGamma*fAccumulatedImpulse)));
26288
26289 if fSoftConstraint then begin
26290 case fLimitBehavior of
26291 kclbLimitMinimumDistance:begin
26292 OldImpulse:=fAccumulatedImpulse;
26293 fAccumulatedImpulse:=Max(0.0,fAccumulatedImpulse+Impulse);
26294 Impulse:=fAccumulatedImpulse-OldImpulse;
26295 end;
26296 kclbLimitMaximumDistance:begin
26297 OldImpulse:=fAccumulatedImpulse;
26298 fAccumulatedImpulse:=Min(0.0,fAccumulatedImpulse+Impulse);
26299 Impulse:=fAccumulatedImpulse-OldImpulse;
26300 end;
26301 else begin
26302 fAccumulatedImpulse:=fAccumulatedImpulse+Impulse;
26303 end;
26304 end;
26305 end else begin
26306 fAccumulatedImpulse:=fAccumulatedImpulse+Impulse;
26307 end;
26308
26309 P:=Vector3ScalarMul(fmU,Impulse);
26310
26311 Vector3DirectSub(vA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactor^,fInverseMass)));
26312 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePosition,P),fWorldInverseInertiaTensor));
26313
26314 end;
26315
26316 end;
26317
26318 function TKraftConstraintJointWorldPlaneDistance.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
26319 var cA:PKraftVector3;
26320 qA:PKraftQuaternion;
26321 rA,AbsolutePosition,u,P:TKraftVector3;
26322 l,C,Impulse:TKraftScalar;
26323 begin
26324
26325 if (fPhysics.fConstraintPositionCorrectionMode<>kpcmNonLinearGaussSeidel) or fSoftConstraint or fSkip then begin
26326
26327 // There is no position correction for soft distance constraints or invalid limit states
26328 result:=true;
26329
26330 end else begin
26331
26332 cA:=@fSolverPosition^.Position;
26333 qA:=@fSolverPosition^.Orientation;
26334
26335 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchor,fLocalCenter),qA^);
26336
26337 AbsolutePosition:=Vector3Add(cA^,rA);
26338
26339 if fDoubleSidedWorldPlane then begin
26340
26341 fWorldPoint:=Vector3Add(AbsolutePosition,Vector3ScalarMul(fWorldPlane.Normal,-PlaneVectorDistance(fWorldPlane,AbsolutePosition)));
26342
26343 u:=Vector3Sub(fWorldPoint,AbsolutePosition);
26344
26345 l:=Vector3LengthNormalize(u);
26346
26347 C:=Min(Max(l-fWorldDistance,-fPhysics.fMaximalLinearCorrection),fPhysics.fMaximalLinearCorrection);
26348
26349 Impulse:=-(fMass*C);
26350
26351 P:=Vector3ScalarMul(u,Impulse);
26352
26353 end else begin
26354
26355 C:=Min(Max(fWorldDistance-PlaneVectorDistance(fWorldPlane,AbsolutePosition),-fPhysics.fMaximalLinearCorrection),fPhysics.fMaximalLinearCorrection);
26356
26357 Impulse:=-(fMass*C);
26358
26359 P:=Vector3ScalarMul(fWorldPlane.Normal,Impulse);
26360
26361 end;
26362
26363 Vector3DirectSub(cA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactor^,fInverseMass)));
26364 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(P)),fWorldInverseInertiaTensor),1.0);
26365
26366 result:=abs(C)<fPhysics.fLinearSlop;
26367
26368 end;
26369 end;
26370
26371 function TKraftConstraintJointWorldPlaneDistance.GetAnchor:TKraftVector3;
26372 begin
26373 result:=Vector3TermMatrixMul(fLocalAnchor,fRigidBodies[0].fWorldTransform);
26374 end;
26375
26376 function TKraftConstraintJointWorldPlaneDistance.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26377 begin
26378 result:=Vector3ScalarMul(fmU,fAccumulatedImpulse*InverseDeltaTime);
26379 end;
26380
26381 function TKraftConstraintJointWorldPlaneDistance.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26382 begin
26383 result:=Vector3Origin;
26384 end;
26385
26386 function TKraftConstraintJointWorldPlaneDistance.GetWorldPoint:TKraftVector3;
26387 begin
26388 result:=fWorldPoint;
26389 end;
26390
26391 function TKraftConstraintJointWorldPlaneDistance.GetWorldPlane:TKraftPlane;
26392 begin
26393 result:=fWorldPlane;
26394 end;
26395
26396 procedure TKraftConstraintJointWorldPlaneDistance.SetWorldPlane(const AWorldPlane:TKraftPlane);
26397 begin
26398 fWorldPlane:=AWorldPlane;
26399 end;
26400
26401 function TKraftConstraintJointWorldPlaneDistance.GetWorldDistance:TKraftScalar;
26402 begin
26403 result:=fWorldDistance;
26404 end;
26405
26406 procedure TKraftConstraintJointWorldPlaneDistance.SetWorldDistance(const AWorldDistance:TKraftScalar);
26407 begin
26408 fWorldDistance:=AWorldDistance;
26409 end;
26410
26411 constructor TKraftConstraintJointDistance.Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const ALocalAnchorPointA,ALocalAnchorPointB:TKraftVector3;const AFrequencyHz:TKraftScalar=0.0;const ADampingRatio:TKraftScalar=0.0;const ACollideConnected:boolean=false);
26412 begin
26413
26414 fLocalAnchors[0]:=ALocalAnchorPointA;
26415 fLocalAnchors[1]:=ALocalAnchorPointB;
26416
26417 fAnchorDistanceLength:=Vector3Dist(Vector3TermMatrixMul(ALocalAnchorPointB,ARigidBodyB.fWorldTransform),Vector3TermMatrixMul(ALocalAnchorPointA,ARigidBodyA.fWorldTransform));
26418 fFrequencyHz:=AFrequencyHz;
26419 fDampingRatio:=ADampingRatio;
26420 fAccumulatedImpulse:=0.0;
26421 fGamma:=0.0;
26422 fBias:=0.0;
26423
26424 if ACollideConnected then begin
26425 Include(fFlags,kcfCollideConnected);
26426 end else begin
26427 Exclude(fFlags,kcfCollideConnected);
26428 end;
26429
26430 fRigidBodies[0]:=ARigidBodyA;
26431 fRigidBodies[1]:=ARigidBodyB;
26432
26433 inherited Create(APhysics);
26434
26435 end;
26436
26437 destructor TKraftConstraintJointDistance.Destroy;
26438 begin
26439 inherited Destroy;
26440 end;
26441
26442 procedure TKraftConstraintJointDistance.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26443 var cA,vA,wA,cB,vB,wB:PKraftVector3;
26444 qA,qB:PKraftQuaternion;
26445 crAu,crBu,P,u:TKraftVector3;
26446 l,fInverseMass,C,Omega,k,h,d,BiasFactor:TKraftScalar;
26447 begin
26448
26449 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
26450 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
26451
26452 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
26453 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
26454
26455 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
26456 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
26457
26458 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
26459 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
26460
26461 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
26462 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
26463
26464 fSolverPositions[0]:[email protected][fIslandIndices[0]];
26465 fSolverPositions[1]:[email protected][fIslandIndices[1]];
26466
26467 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
26468 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
26469
26470 cA:=@fSolverPositions[0]^.Position;
26471 qA:=@fSolverPositions[0]^.Orientation;
26472 vA:=@fSolverVelocities[0]^.LinearVelocity;
26473 wA:=@fSolverVelocities[0]^.AngularVelocity;
26474
26475 cB:=@fSolverPositions[1]^.Position;
26476 qB:=@fSolverPositions[1]^.Orientation;
26477 vB:=@fSolverVelocities[1]^.LinearVelocity;
26478 wB:=@fSolverVelocities[1]^.AngularVelocity;
26479
26480 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
26481 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
26482 fmU:=Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0]));
26483
26484 // Handle singularity
26485 l:=Vector3Length(fmU);
26486 if l>fPhysics.fLinearSlop then begin
26487 Vector3Scale(fmU,1.0/l);
26488 end else begin
26489 fmU:=Vector3Origin;
26490 end;
26491
26492 crAu:=Vector3Cross(fRelativePositions[0],fmU);
26493 crBu:=Vector3Cross(fRelativePositions[1],fmU);
26494
26495 fInverseMass:=fRigidBodies[0].fInverseMass+
26496 fRigidBodies[1].fInverseMass+
26497 Vector3Dot(Vector3TermMatrixMul(crAu,fWorldInverseInertiaTensors[0]),crAu)+
26498 Vector3Dot(Vector3TermMatrixMul(crBu,fWorldInverseInertiaTensors[1]),crBu);
26499
26500 // Compute the effective mass matrix
26501 if fInverseMass<>0.0 then begin
26502 fMass:=1.0/fInverseMass;
26503 end else begin
26504 fMass:=0.0;
26505 end;
26506
26507 if fFrequencyHz>EPSILON then begin
26508
26509 C:=l-fAnchorDistanceLength;
26510
26511 // fFrequency
26512 Omega:=pi2*fFrequencyHz;
26513
26514 // Damping coefficient
26515 d:=2.0*fMass*fDampingRatio*Omega;
26516
26517 // Spring stiffness
26518 k:=fMass*sqr(Omega);
26519
26520 // Magic formulas
26521 h:=TimeStep.DeltaTime;
26522 fGamma:=h*(d+(h*k));
26523 if fGamma<>0.0 then begin
26524 fGamma:=1.0/fGamma;
26525 end else begin
26526 fGamma:=0.0;
26527 end;
26528 fBias:=C*h*k*fGamma;
26529
26530 fInverseMass:=fInverseMass+fGamma;
26531
26532 if fInverseMass<>0.0 then begin
26533 fMass:=1.0/fInverseMass;
26534 end else begin
26535 fMass:=0.0;
26536 end;
26537
26538 end else begin
26539
26540 fGamma:=0.0;
26541 fBias:=0.0;
26542
26543 end;
26544
26545 if fPhysics.fConstraintPositionCorrectionMode=kpcmBaumgarte then begin
26546 u:=Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0]));
26547 l:=Vector3LengthNormalize(u);
26548 C:=Min(Max(l-fAnchorDistanceLength,-fPhysics.fMaximalLinearCorrection),fPhysics.fMaximalLinearCorrection);
26549 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
26550 fBias:=fBias+(C*BiasFactor);
26551 end;
26552
26553 if fPhysics.fWarmStarting then begin
26554
26555 fAccumulatedImpulse:=fAccumulatedImpulse*TimeStep.DeltaTimeRatio;
26556
26557 P:=Vector3ScalarMul(fmU,fAccumulatedImpulse);
26558
26559 Vector3DirectSub(vA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
26560 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],P),fWorldInverseInertiaTensors[0]));
26561
26562 Vector3DirectAdd(vB^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
26563 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],P),fWorldInverseInertiaTensors[1]));
26564
26565 end else begin
26566
26567 fAccumulatedImpulse:=0.0;
26568
26569 end;
26570
26571 end;
26572
26573 procedure TKraftConstraintJointDistance.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26574 var vA,wA,vB,wB:PKraftVector3;
26575 vpA,vpB,P:TKraftVector3;
26576 Cdot,Impulse:TKraftScalar;
26577 begin
26578
26579 vA:=@fSolverVelocities[0]^.LinearVelocity;
26580 wA:=@fSolverVelocities[0]^.AngularVelocity;
26581
26582 vB:=@fSolverVelocities[1]^.LinearVelocity;
26583 wB:=@fSolverVelocities[1]^.AngularVelocity;
26584
26585 // Cdot = dot(u, v + cross(w, r))
26586 vpA:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePositions[0]));
26587 vpB:=Vector3Add(vB^,Vector3Cross(wB^,fRelativePositions[1]));
26588 Cdot:=Vector3Dot(fmU,Vector3Sub(vpB,vpA));
26589
26590 Impulse:=-(fMass*((Cdot+fBias)+(fGamma*fAccumulatedImpulse)));
26591 fAccumulatedImpulse:=fAccumulatedImpulse+Impulse;
26592
26593 P:=Vector3ScalarMul(fmU,Impulse);
26594
26595 Vector3DirectSub(vA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
26596 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],P),fWorldInverseInertiaTensors[0]));
26597
26598 Vector3DirectAdd(vB^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
26599 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],P),fWorldInverseInertiaTensors[1]));
26600
26601 end;
26602
26603 function TKraftConstraintJointDistance.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
26604 var cA,cB:PKraftVector3;
26605 qA,qB:PKraftQuaternion;
26606 rA,rB,u,P:TKraftVector3;
26607 l,C,Impulse:TKraftScalar;
26608 begin
26609
26610 if (fPhysics.fConstraintPositionCorrectionMode<>kpcmNonLinearGaussSeidel) or (fFrequencyHz>EPSILON) then begin
26611
26612 // There is no position correction for soft distance constraints
26613 result:=true;
26614
26615 end else begin
26616
26617 cA:=@fSolverPositions[0]^.Position;
26618 qA:=@fSolverPositions[0]^.Orientation;
26619
26620 cB:=@fSolverPositions[1]^.Position;
26621 qB:=@fSolverPositions[1]^.Orientation;
26622
26623 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
26624 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
26625 u:=Vector3Sub(Vector3Add(cB^,rB),Vector3Add(cA^,rA));
26626
26627 l:=Vector3LengthNormalize(u);
26628 C:=Min(Max(l-fAnchorDistanceLength,-fPhysics.fMaximalLinearCorrection),fPhysics.fMaximalLinearCorrection);
26629
26630 Impulse:=-(fMass*C);
26631
26632 P:=Vector3ScalarMul(u,Impulse);
26633
26634 Vector3DirectSub(cA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
26635 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(P)),fWorldInverseInertiaTensors[0]),1.0);
26636
26637 Vector3DirectAdd(cB^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
26638 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Vector3Cross(rB,P),fWorldInverseInertiaTensors[1]),1.0);
26639
26640 result:=abs(C)<fPhysics.fLinearSlop;
26641
26642 end;
26643
26644 end;
26645
26646 function TKraftConstraintJointDistance.GetAnchorA:TKraftVector3;
26647 begin
26648 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
26649 end;
26650
26651 function TKraftConstraintJointDistance.GetAnchorB:TKraftVector3;
26652 begin
26653 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
26654 end;
26655
26656 function TKraftConstraintJointDistance.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26657 begin
26658 result:=Vector3ScalarMul(fmU,fAccumulatedImpulse*InverseDeltaTime);
26659 end;
26660
26661 function TKraftConstraintJointDistance.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26662 begin
26663 result:=Vector3Origin;
26664 end;
26665
26666 constructor TKraftConstraintJointRope.Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const ALocalAnchorPointA,ALocalAnchorPointB:TKraftVector3;const AMaximalLength:TKraftScalar=1.0;const ACollideConnected:boolean=false);
26667 begin
26668
26669 fLocalAnchors[0]:=ALocalAnchorPointA;
26670 fLocalAnchors[1]:=ALocalAnchorPointB;
26671
26672 fMaximalLength:=AMaximalLength;
26673
26674 fAccumulatedImpulse:=0.0;
26675
26676 fLimitState:=kclsInactiveLimit;
26677
26678 if ACollideConnected then begin
26679 Include(fFlags,kcfCollideConnected);
26680 end else begin
26681 Exclude(fFlags,kcfCollideConnected);
26682 end;
26683
26684 fRigidBodies[0]:=ARigidBodyA;
26685 fRigidBodies[1]:=ARigidBodyB;
26686
26687 inherited Create(APhysics);
26688
26689 end;
26690
26691 destructor TKraftConstraintJointRope.Destroy;
26692 begin
26693 inherited Destroy;
26694 end;
26695
26696 procedure TKraftConstraintJointRope.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26697 var cA,vA,wA,cB,vB,wB:PKraftVector3;
26698 qA,qB:PKraftQuaternion;
26699 crAu,crBu,P,u:TKraftVector3;
26700 l,fInverseMass,C,BiasFactor:TKraftScalar;
26701 begin
26702
26703 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
26704 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
26705
26706 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
26707 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
26708
26709 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
26710 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
26711
26712 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
26713 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
26714
26715 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
26716 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
26717
26718 fSolverPositions[0]:[email protected][fIslandIndices[0]];
26719 fSolverPositions[1]:[email protected][fIslandIndices[1]];
26720
26721 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
26722 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
26723
26724 cA:=@fSolverPositions[0]^.Position;
26725 qA:=@fSolverPositions[0]^.Orientation;
26726 vA:=@fSolverVelocities[0]^.LinearVelocity;
26727 wA:=@fSolverVelocities[0]^.AngularVelocity;
26728
26729 cB:=@fSolverPositions[1]^.Position;
26730 qB:=@fSolverPositions[1]^.Orientation;
26731 vB:=@fSolverVelocities[1]^.LinearVelocity;
26732 wB:=@fSolverVelocities[1]^.AngularVelocity;
26733
26734 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
26735 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
26736 fmU:=Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0]));
26737
26738 fCurrentLength:=Vector3Length(fmU);
26739
26740 C:=fCurrentLength-fMaximalLength;
26741 if C>0.0 then begin
26742 fLimitState:=kclsAtUpperLimit;
26743 end else begin
26744 fLimitState:=kclsInactiveLimit;
26745 end;
26746
26747 // Handle singularity
26748 if fCurrentLength>fPhysics.fLinearSlop then begin
26749
26750 Vector3Scale(fmU,1.0/fCurrentLength);
26751
26752 crAu:=Vector3Cross(fRelativePositions[0],fmU);
26753 crBu:=Vector3Cross(fRelativePositions[1],fmU);
26754
26755 fInverseMass:=fRigidBodies[0].fInverseMass+
26756 fRigidBodies[1].fInverseMass+
26757 Vector3Dot(Vector3TermMatrixMul(crAu,fWorldInverseInertiaTensors[0]),crAu)+
26758 Vector3Dot(Vector3TermMatrixMul(crBu,fWorldInverseInertiaTensors[1]),crBu);
26759
26760 // Compute the effective mass matrix
26761 if fInverseMass<>0.0 then begin
26762 fMass:=1.0/fInverseMass;
26763 end else begin
26764 fMass:=0.0;
26765 end;
26766
26767 if fPhysics.fWarmStarting then begin
26768
26769 fAccumulatedImpulse:=fAccumulatedImpulse*TimeStep.DeltaTimeRatio;
26770
26771 P:=Vector3ScalarMul(fmU,fAccumulatedImpulse);
26772
26773 Vector3DirectSub(vA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
26774 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],P),fWorldInverseInertiaTensors[0]));
26775
26776 Vector3DirectAdd(vB^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
26777 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],P),fWorldInverseInertiaTensors[1]));
26778
26779 end else begin
26780
26781 fAccumulatedImpulse:=0.0;
26782
26783 end;
26784
26785 end else begin
26786
26787 fmU:=Vector3Origin;
26788 fMass:=0.0;
26789 fAccumulatedImpulse:=0.0;
26790
26791 end;
26792
26793 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
26794
26795 fBias:=0.0;
26796
26797 end else begin
26798
26799 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
26800
26801 u:=Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0]));
26802
26803 l:=Vector3LengthNormalize(u);
26804 C:=Min(Max(l-fMaximalLength,0.0),fPhysics.fMaximalLinearCorrection);
26805
26806 fBias:=C*BiasFactor;
26807
26808 end;
26809
26810 end;
26811
26812 procedure TKraftConstraintJointRope.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26813 var vA,wA,vB,wB:PKraftVector3;
26814 vpA,vpB,P:TKraftVector3;
26815 C,Cdot,Impulse,OldImpulse:TKraftScalar;
26816 begin
26817
26818 vA:=@fSolverVelocities[0]^.LinearVelocity;
26819 wA:=@fSolverVelocities[0]^.AngularVelocity;
26820
26821 vB:=@fSolverVelocities[1]^.LinearVelocity;
26822 wB:=@fSolverVelocities[1]^.AngularVelocity;
26823
26824 // Cdot = dot(u, v + cross(w, r))
26825 vpA:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePositions[0]));
26826 vpB:=Vector3Add(vB^,Vector3Cross(wB^,fRelativePositions[1]));
26827 C:=fCurrentLength-fMaximalLength;
26828 Cdot:=Vector3Dot(fmU,Vector3Sub(vpB,vpA));
26829
26830 // Predictive constraint
26831 if C<0.0 then begin
26832 Cdot:=Cdot+(C*TimeStep.InverseDeltaTime);
26833 end;
26834
26835 Impulse:=-(fMass*(Cdot+fBias));
26836 OldImpulse:=fAccumulatedImpulse;
26837 fAccumulatedImpulse:=Min(0.0,fAccumulatedImpulse+Impulse);
26838 Impulse:=fAccumulatedImpulse-OldImpulse;
26839
26840 P:=Vector3ScalarMul(fmU,Impulse);
26841
26842 Vector3DirectSub(vA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
26843 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],P),fWorldInverseInertiaTensors[0]));
26844
26845 Vector3DirectAdd(vB^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
26846 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],P),fWorldInverseInertiaTensors[1]));
26847
26848 end;
26849
26850 function TKraftConstraintJointRope.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
26851 var cA,cB:PKraftVector3;
26852 qA,qB:PKraftQuaternion;
26853 rA,rB,u,P:TKraftVector3;
26854 Len,C,Impulse:TKraftScalar;
26855 begin
26856
26857 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
26858
26859 cA:=@fSolverPositions[0]^.Position;
26860 qA:=@fSolverPositions[0]^.Orientation;
26861
26862 cB:=@fSolverPositions[1]^.Position;
26863 qB:=@fSolverPositions[1]^.Orientation;
26864
26865 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
26866 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
26867 u:=Vector3Sub(Vector3Add(cB^,rB),Vector3Add(cA^,rA));
26868
26869 Len:=Vector3LengthNormalize(u);
26870 C:=Min(Max(Len-fMaximalLength,0.0),fPhysics.fMaximalLinearCorrection);
26871
26872 Impulse:=-(fMass*C);
26873
26874 P:=Vector3ScalarMul(u,Impulse);
26875
26876 Vector3DirectSub(cA^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
26877 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(P)),fWorldInverseInertiaTensors[0]),1.0);
26878
26879 Vector3DirectAdd(cB^,Vector3Mul(P,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
26880 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Vector3Cross(rB,P),fWorldInverseInertiaTensors[1]),1.0);
26881
26882 result:=(Len-fMaximalLength)<fPhysics.fLinearSlop;
26883
26884 end else begin
26885
26886 result:=true;
26887
26888 end;
26889
26890 end;
26891
26892 function TKraftConstraintJointRope.GetAnchorA:TKraftVector3;
26893 begin
26894 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
26895 end;
26896
26897 function TKraftConstraintJointRope.GetAnchorB:TKraftVector3;
26898 begin
26899 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
26900 end;
26901
26902 function TKraftConstraintJointRope.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26903 begin
26904 result:=Vector3ScalarMul(fmU,fAccumulatedImpulse*InverseDeltaTime);
26905 end;
26906
26907 function TKraftConstraintJointRope.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
26908 begin
26909 result:=Vector3Origin;
26910 end;
26911
26912 constructor TKraftConstraintJointPulley.Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AWorldGroundAnchorA,AWorldGroundAnchorB,AWorldAnchorPointA,AWorldAnchorPointB:TKraftVector3;const ARatio:TKraftScalar=1.0;const ACollideConnected:boolean=false);
26913 begin
26914
26915 fGroundAnchors[0]:=AWorldGroundAnchorA;
26916 fGroundAnchors[1]:=AWorldGroundAnchorB;
26917
26918 fLocalAnchors[0]:=Vector3TermMatrixMulInverted(AWorldAnchorPointA,ARigidBodyA.fWorldTransform);
26919 fLocalAnchors[1]:=Vector3TermMatrixMulInverted(AWorldAnchorPointB,ARigidBodyB.fWorldTransform);
26920
26921 fLengths[0]:=Vector3Dist(AWorldAnchorPointA,AWorldGroundAnchorA);
26922 fLengths[1]:=Vector3Dist(AWorldAnchorPointB,AWorldGroundAnchorB);
26923
26924 fRatio:=ARatio;
26925
26926 fConstant:=fLengths[0]+(fLengths[1]*fRatio);
26927
26928 fAccumulatedImpulse:=0.0;
26929
26930 if ACollideConnected then begin
26931 Include(fFlags,kcfCollideConnected);
26932 end else begin
26933 Exclude(fFlags,kcfCollideConnected);
26934 end;
26935
26936 fRigidBodies[0]:=ARigidBodyA;
26937 fRigidBodies[1]:=ARigidBodyB;
26938
26939 inherited Create(APhysics);
26940
26941 end;
26942
26943 destructor TKraftConstraintJointPulley.Destroy;
26944 begin
26945 inherited Destroy;
26946 end;
26947
26948 procedure TKraftConstraintJointPulley.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
26949 var cA,vA,wA,cB,vB,wB:PKraftVector3;
26950 qA,qB:PKraftQuaternion;
26951 ruA,ruB,PA,PB:TKraftVector3;
26952 LengthA,LengthB,mA,mB,fInverseMass,BiasFactor,C:TKraftScalar;
26953 begin
26954
26955 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
26956 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
26957
26958 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
26959 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
26960
26961 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
26962 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
26963
26964 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
26965 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
26966
26967 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
26968 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
26969
26970 fSolverPositions[0]:[email protected][fIslandIndices[0]];
26971 fSolverPositions[1]:[email protected][fIslandIndices[1]];
26972
26973 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
26974 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
26975
26976 cA:=@fSolverPositions[0]^.Position;
26977 qA:=@fSolverPositions[0]^.Orientation;
26978 vA:=@fSolverVelocities[0]^.LinearVelocity;
26979 wA:=@fSolverVelocities[0]^.AngularVelocity;
26980
26981 cB:=@fSolverPositions[1]^.Position;
26982 qB:=@fSolverPositions[1]^.Orientation;
26983 vB:=@fSolverVelocities[1]^.LinearVelocity;
26984 wB:=@fSolverVelocities[1]^.AngularVelocity;
26985
26986 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
26987 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
26988
26989 fmU[0]:=Vector3Add(cA^,fRelativePositions[0]);
26990 fmU[1]:=Vector3Add(cB^,fRelativePositions[1]);
26991
26992 LengthA:=Vector3Length(fmU[0]);
26993 LengthB:=Vector3Length(fmU[1]);
26994
26995 if LengthA>(10.0*fPhysics.fLinearSlop) then begin
26996 Vector3Scale(fmU[0],1.0/LengthA);
26997 end else begin
26998 fmU[0]:=Vector3Origin;
26999 end;
27000
27001 if LengthB>(10.0*fPhysics.fLinearSlop) then begin
27002 Vector3Scale(fmU[1],1.0/LengthB);
27003 end else begin
27004 fmU[1]:=Vector3Origin;
27005 end;
27006
27007 ruA:=Vector3Cross(fRelativePositions[0],fmU[0]);
27008 ruB:=Vector3Cross(fRelativePositions[1],fmU[1]);
27009
27010 mA:=fRigidBodies[0].fInverseMass+Vector3Dot(Vector3TermMatrixMul(ruA,fWorldInverseInertiaTensors[0]),ruA);
27011 mB:=fRigidBodies[1].fInverseMass+Vector3Dot(Vector3TermMatrixMul(ruB,fWorldInverseInertiaTensors[1]),ruB);
27012
27013 fInverseMass:=mA+(mB*sqr(fRatio));
27014
27015 // Compute the effective mass matrix
27016 if fInverseMass<>0.0 then begin
27017 fMass:=1.0/fInverseMass;
27018 end else begin
27019 fMass:=0.0;
27020 end;
27021
27022 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27023
27024 fBias:=0.0;
27025
27026 end else begin
27027
27028 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
27029
27030 C:=fConstant-(LengthA+(LengthB*fRatio));
27031
27032 fBias:=C*BiasFactor;
27033
27034 end;
27035
27036 if fPhysics.fWarmStarting then begin
27037
27038 fAccumulatedImpulse:=fAccumulatedImpulse*TimeStep.DeltaTimeRatio;
27039
27040 PA:=Vector3ScalarMul(fmU[0],-fAccumulatedImpulse);
27041 PB:=Vector3ScalarMul(fmU[1],-(fAccumulatedImpulse*fRatio));
27042
27043 Vector3DirectAdd(vA^,Vector3Mul(PA,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27044 Vector3DirectAdd(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],PA),fWorldInverseInertiaTensors[0]));
27045
27046 Vector3DirectAdd(vB^,Vector3Mul(PB,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27047 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],PB),fWorldInverseInertiaTensors[1]));
27048
27049 end else begin
27050
27051 fAccumulatedImpulse:=0.0;
27052
27053 end;
27054
27055 end;
27056
27057 procedure TKraftConstraintJointPulley.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
27058 var vA,wA,vB,wB:PKraftVector3;
27059 vpA,vpB,PA,PB:TKraftVector3;
27060 Cdot,Impulse:TKraftScalar;
27061 begin
27062
27063 vA:=@fSolverVelocities[0]^.LinearVelocity;
27064 wA:=@fSolverVelocities[0]^.AngularVelocity;
27065
27066 vB:=@fSolverVelocities[1]^.LinearVelocity;
27067 wB:=@fSolverVelocities[1]^.AngularVelocity;
27068
27069 vpA:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePositions[0]));
27070 vpB:=Vector3Add(vB^,Vector3Cross(wB^,fRelativePositions[1]));
27071
27072 Cdot:=(-(Vector3Dot(fmU[0],vpA)))-(Vector3Dot(fmU[1],vpB)*fRatio);
27073 Impulse:=-(fMass*(Cdot+fBias));
27074 fAccumulatedImpulse:=fAccumulatedImpulse+Impulse;
27075
27076 PA:=Vector3ScalarMul(fmU[0],-Impulse);
27077 PB:=Vector3ScalarMul(fmU[1],-(Impulse*fRatio));
27078
27079 Vector3DirectAdd(vA^,Vector3Mul(PA,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27080 Vector3DirectAdd(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],PA),fWorldInverseInertiaTensors[0]));
27081
27082 Vector3DirectAdd(vB^,Vector3Mul(PB,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27083 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],PB),fWorldInverseInertiaTensors[1]));
27084
27085 end;
27086
27087 function TKraftConstraintJointPulley.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
27088 var cA,cB:PKraftVector3;
27089 qA,qB:PKraftQuaternion;
27090 rA,rB,uA,uB,ruA,ruB,PA,PB:TKraftVector3;
27091 LengthA,LengthB,mA,mB,fInverseMass,Mass,C,LinearError,Impulse:TKraftScalar;
27092 begin
27093
27094 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27095
27096 cA:=@fSolverPositions[0]^.Position;
27097 qA:=@fSolverPositions[0]^.Orientation;
27098
27099 cB:=@fSolverPositions[1]^.Position;
27100 qB:=@fSolverPositions[1]^.Orientation;
27101
27102 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
27103 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
27104
27105 // Get the pulley axes
27106 uA:=Vector3Add(cA^,rA);
27107 uB:=Vector3Add(cB^,rB);
27108
27109 LengthA:=Vector3Length(uA);
27110 LengthB:=Vector3Length(uB);
27111
27112 if LengthA>(10.0*fPhysics.fLinearSlop) then begin
27113 Vector3Scale(uA,1.0/LengthA);
27114 end else begin
27115 uA:=Vector3Origin;
27116 end;
27117
27118 if LengthB>(10.0*fPhysics.fLinearSlop) then begin
27119 Vector3Scale(uB,1.0/LengthB);
27120 end else begin
27121 uB:=Vector3Origin;
27122 end;
27123
27124 ruA:=Vector3Cross(fRelativePositions[0],fmU[0]);
27125 ruB:=Vector3Cross(fRelativePositions[1],fmU[1]);
27126
27127 mA:=fRigidBodies[0].fInverseMass+Vector3Dot(Vector3TermMatrixMul(ruA,fWorldInverseInertiaTensors[0]),ruA);
27128 mB:=fRigidBodies[1].fInverseMass+Vector3Dot(Vector3TermMatrixMul(ruB,fWorldInverseInertiaTensors[1]),ruB);
27129
27130 fInverseMass:=mA+(mB*sqr(fRatio));
27131
27132 // Compute the effective mass matrix
27133 if fInverseMass<>0.0 then begin
27134 Mass:=1.0/fInverseMass;
27135 end else begin
27136 Mass:=0.0;
27137 end;
27138
27139 C:=fConstant-(LengthA+(LengthB*fRatio));
27140
27141 LinearError:=abs(c);
27142
27143 Impulse:=-(Mass*C);
27144
27145 PA:=Vector3ScalarMul(uA,-Impulse);
27146 PB:=Vector3ScalarMul(uB,-(Impulse*fRatio));
27147
27148 Vector3DirectAdd(cA^,Vector3Mul(PA,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27149 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,PA),fWorldInverseInertiaTensors[0]),1.0);
27150
27151 Vector3DirectAdd(cB^,Vector3Mul(PB,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27152 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Vector3Cross(rB,PB),fWorldInverseInertiaTensors[1]),1.0);
27153
27154 result:=LinearError<fPhysics.fLinearSlop;
27155
27156 end else begin
27157
27158 result:=true;
27159
27160 end;
27161 end;
27162
27163 function TKraftConstraintJointPulley.GetAnchorA:TKraftVector3;
27164 begin
27165 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
27166 end;
27167
27168 function TKraftConstraintJointPulley.GetAnchorB:TKraftVector3;
27169 begin
27170 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
27171 end;
27172
27173 function TKraftConstraintJointPulley.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
27174 begin
27175 result:=Vector3ScalarMul(fmU[1],fAccumulatedImpulse*InverseDeltaTime);
27176 end;
27177
27178 function TKraftConstraintJointPulley.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
27179 begin
27180 result:=Vector3Origin;
27181 end;
27182
27183 function TKraftConstraintJointPulley.GetCurrentLengthA:TKraftScalar;
27184 begin
27185 result:=Vector3Dist(Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform),fGroundAnchors[0]);
27186 end;
27187
27188 function TKraftConstraintJointPulley.GetCurrentLengthB:TKraftScalar;
27189 begin
27190 result:=Vector3Dist(Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform),fGroundAnchors[1]);
27191 end;
27192
27193 constructor TKraftConstraintJointBallSocket.Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AWorldAnchorPoint:TKraftVector3;const ACollideConnected:boolean=false);
27194 begin
27195
27196 fLocalAnchors[0]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyA.fWorldTransform);
27197 fLocalAnchors[1]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyB.fWorldTransform);
27198
27199 fAccumulatedImpulse:=Vector3Origin;
27200
27201 if ACollideConnected then begin
27202 Include(fFlags,kcfCollideConnected);
27203 end else begin
27204 Exclude(fFlags,kcfCollideConnected);
27205 end;
27206
27207 fRigidBodies[0]:=ARigidBodyA;
27208 fRigidBodies[1]:=ARigidBodyB;
27209
27210 inherited Create(APhysics);
27211
27212 end;
27213
27214 constructor TKraftConstraintJointBallSocket.Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const ALocalAnchorPointA,ALocalAnchorPointB:TKraftVector3;const ACollideConnected:boolean=false);
27215 begin
27216
27217 fLocalAnchors[0]:=ALocalAnchorPointA;
27218 fLocalAnchors[1]:=ALocalAnchorPointB;
27219
27220 fAccumulatedImpulse:=Vector3Origin;
27221
27222 if ACollideConnected then begin
27223 Include(fFlags,kcfCollideConnected);
27224 end else begin
27225 Exclude(fFlags,kcfCollideConnected);
27226 end;
27227
27228 fRigidBodies[0]:=ARigidBodyA;
27229 fRigidBodies[1]:=ARigidBodyB;
27230
27231 inherited Create(APhysics);
27232
27233 end;
27234
27235
27236 destructor TKraftConstraintJointBallSocket.Destroy;
27237 begin
27238 inherited Destroy;
27239 end;
27240
27241 procedure TKraftConstraintJointBallSocket.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
27242 var cA,vA,wA,cB,vB,wB:PKraftVector3;
27243 qA,qB:PKraftQuaternion;
27244 InverseMassOfBodies,BiasFactor:TKraftScalar;
27245 SkewSymmetricMatrices:array[0..1] of TKraftMatrix3x3;
27246 MassMatrix:TKraftMatrix3x3;
27247 begin
27248
27249 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
27250 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
27251
27252 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
27253 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
27254
27255 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
27256 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
27257
27258 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
27259 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
27260
27261 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
27262 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
27263
27264 fSolverPositions[0]:[email protected][fIslandIndices[0]];
27265 fSolverPositions[1]:[email protected][fIslandIndices[1]];
27266
27267 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
27268 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
27269
27270 cA:=@fSolverPositions[0]^.Position;
27271 qA:=@fSolverPositions[0]^.Orientation;
27272 vA:=@fSolverVelocities[0]^.LinearVelocity;
27273 wA:=@fSolverVelocities[0]^.AngularVelocity;
27274
27275 cB:=@fSolverPositions[1]^.Position;
27276 qB:=@fSolverPositions[1]^.Orientation;
27277 vB:=@fSolverVelocities[1]^.LinearVelocity;
27278 wB:=@fSolverVelocities[1]^.AngularVelocity;
27279
27280 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
27281 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
27282
27283 SkewSymmetricMatrices[0]:=GetSkewSymmetricMatrixPlus(fRelativePositions[0]);
27284 SkewSymmetricMatrices[1]:=GetSkewSymmetricMatrixPlus(fRelativePositions[1]);
27285
27286 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
27287
27288 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27289 MassMatrix[0,0]:=InverseMassOfBodies;
27290 MassMatrix[0,1]:=0.0;
27291 MassMatrix[0,2]:=0.0;
27292 {$ifdef SIMD}
27293 MassMatrix[0,3]:=0.0;
27294 {$endif}
27295 MassMatrix[1,0]:=0.0;
27296 MassMatrix[1,1]:=InverseMassOfBodies;
27297 MassMatrix[1,2]:=0.0;
27298 {$ifdef SIMD}
27299 MassMatrix[1,3]:=0.0;
27300 {$endif}
27301 MassMatrix[2,0]:=0.0;
27302 MassMatrix[2,1]:=0.0;
27303 MassMatrix[2,2]:=InverseMassOfBodies;
27304 {$ifdef SIMD}
27305 MassMatrix[2,3]:=0.0;
27306 {$endif}
27307 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[0],fWorldInverseInertiaTensors[0]),SkewSymmetricMatrices[0]));
27308 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[1],fWorldInverseInertiaTensors[1]),SkewSymmetricMatrices[1]));
27309 fInverseMassMatrix:=Matrix3x3TermInverse(MassMatrix);
27310 end else begin
27311 fInverseMassMatrix:=Matrix3x3Null;
27312 end;
27313
27314 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27315 fBiasVector:=Vector3Origin;
27316 end else begin
27317 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
27318 fBiasVector:=Vector3ScalarMul(Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0])),BiasFactor);
27319 end;
27320
27321 if fPhysics.fWarmStarting then begin
27322
27323 fAccumulatedImpulse:=Vector3ScalarMul(fAccumulatedImpulse,TimeStep.DeltaTimeRatio);
27324
27325 //writeln('BallWarm ',Vector3Length(fAccumulatedImpulse):1:8);
27326
27327 Vector3DirectSub(vA^,Vector3Mul(fAccumulatedImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27328 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],fAccumulatedImpulse),fWorldInverseInertiaTensors[0]));
27329
27330 Vector3DirectAdd(vB^,Vector3Mul(fAccumulatedImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27331 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],fAccumulatedImpulse),fWorldInverseInertiaTensors[1]));
27332
27333 end else begin
27334
27335 fAccumulatedImpulse:=Vector3Origin;
27336
27337 end;
27338
27339 end;
27340
27341 procedure TKraftConstraintJointBallSocket.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
27342 var vA,wA,vB,wB:PKraftVector3;
27343 vpA,vpB,Jv,Impulse:TKraftVector3;
27344 begin
27345
27346 vA:=@fSolverVelocities[0]^.LinearVelocity;
27347 wA:=@fSolverVelocities[0]^.AngularVelocity;
27348
27349 vB:=@fSolverVelocities[1]^.LinearVelocity;
27350 wB:=@fSolverVelocities[1]^.AngularVelocity;
27351
27352 // Cdot = dot(u, v + cross(w, r))
27353 vpA:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePositions[0]));
27354 vpB:=Vector3Add(vB^,Vector3Cross(wB^,fRelativePositions[1]));
27355 Jv:=Vector3Sub(vpB,vpA);
27356
27357 Impulse:=Vector3TermMatrixMul(Vector3Sub(Vector3Neg(Jv),fBiasVector),fInverseMassMatrix);
27358
27359 fAccumulatedImpulse:=Vector3Add(fAccumulatedImpulse,Impulse);
27360
27361 //writeln('BallVelo ',Vector3Length(Impulse):1:8);
27362
27363 Vector3DirectSub(vA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27364 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],Impulse),fWorldInverseInertiaTensors[0]));
27365
27366 Vector3DirectAdd(vB^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27367 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],Impulse),fWorldInverseInertiaTensors[1]));
27368
27369 end;
27370
27371 function TKraftConstraintJointBallSocket.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
27372 var cA,cB:PKraftVector3;
27373 qA,qB:PKraftQuaternion;
27374 rA,rB,TranslationError,Impulse:TKraftVector3;
27375 InverseMassOfBodies:TKraftScalar;
27376 SkewSymmetricMatrices:array[0..1] of TKraftMatrix3x3;
27377 MassMatrix:TKraftMatrix3x3;
27378 begin
27379
27380 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27381
27382 cA:=@fSolverPositions[0]^.Position;
27383 qA:=@fSolverPositions[0]^.Orientation;
27384
27385 cB:=@fSolverPositions[1]^.Position;
27386 qB:=@fSolverPositions[1]^.Orientation;
27387
27388 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
27389 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
27390
27391 SkewSymmetricMatrices[0]:=GetSkewSymmetricMatrixPlus(rA);
27392 SkewSymmetricMatrices[1]:=GetSkewSymmetricMatrixPlus(rB);
27393
27394 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
27395
27396 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27397 MassMatrix[0,0]:=InverseMassOfBodies;
27398 MassMatrix[0,1]:=0.0;
27399 MassMatrix[0,2]:=0.0;
27400 {$ifdef SIMD}
27401 MassMatrix[0,3]:=0.0;
27402 {$endif}
27403 MassMatrix[1,0]:=0.0;
27404 MassMatrix[1,1]:=InverseMassOfBodies;
27405 MassMatrix[1,2]:=0.0;
27406 {$ifdef SIMD}
27407 MassMatrix[1,3]:=0.0;
27408 {$endif}
27409 MassMatrix[2,0]:=0.0;
27410 MassMatrix[2,1]:=0.0;
27411 MassMatrix[2,2]:=InverseMassOfBodies;
27412 {$ifdef SIMD}
27413 MassMatrix[2,3]:=0.0;
27414 {$endif}
27415 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[0],fWorldInverseInertiaTensors[0]),SkewSymmetricMatrices[0]));
27416 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[1],fWorldInverseInertiaTensors[1]),SkewSymmetricMatrices[1]));
27417 fInverseMassMatrix:=Matrix3x3TermInverse(MassMatrix);
27418 end else begin
27419 fInverseMassMatrix:=Matrix3x3Null;
27420 end;
27421
27422 TranslationError:=Vector3Sub(Vector3Add(cB^,rB),Vector3Add(cA^,rA));
27423
27424 Impulse:=Vector3TermMatrixMul(Vector3Neg(TranslationError),fInverseMassMatrix);
27425
27426 // writeln('BallPos ',Vector3Length(fAccumulatedImpulse):1:8,' ',TranslationError.x:1:8,' ',TranslationError.y:1:8,' ',TranslationError.z:1:8);
27427
27428 Vector3DirectSub(cA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27429 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(Impulse)),fWorldInverseInertiaTensors[0]),1.0);
27430
27431 Vector3DirectAdd(cB^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27432 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Vector3Cross(rB,Impulse),fWorldInverseInertiaTensors[1]),1.0);
27433
27434 result:=Vector3Length(TranslationError)<fPhysics.fLinearSlop;
27435
27436 end else begin
27437
27438 result:=true;
27439
27440 end;
27441 end;
27442
27443 function TKraftConstraintJointBallSocket.GetAnchorA:TKraftVector3;
27444 begin
27445 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
27446 end;
27447
27448 function TKraftConstraintJointBallSocket.GetAnchorB:TKraftVector3;
27449 begin
27450 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
27451 end;
27452
27453 function TKraftConstraintJointBallSocket.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
27454 begin
27455 result:=Vector3ScalarMul(fAccumulatedImpulse,InverseDeltaTime);
27456 end;
27457
27458 function TKraftConstraintJointBallSocket.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
27459 begin
27460 result:=Vector3Origin;
27461 end;
27462
27463 constructor TKraftConstraintJointFixed.Create(const APhysics:TKraft;const ARigidBodyA,ARigidBodyB:TKraftRigidBody;const AWorldAnchorPoint:TKraftVector3;const ACollideConnected:boolean=false);
27464 begin
27465
27466 fLocalAnchors[0]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyA.fWorldTransform);
27467 fLocalAnchors[1]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyB.fWorldTransform);
27468
27469 fAccumulatedImpulseTranslation:=Vector3Origin;
27470 fAccumulatedImpulseRotation:=Vector3Origin;
27471
27472 fInverseInitialOrientationDifference:=QuaternionInverse(QuaternionTermNormalize(QuaternionMul(ARigidBodyB.fSweep.q0,QuaternionInverse(ARigidBodyA.fSweep.q0))));
27473
27474 if ACollideConnected then begin
27475 Include(fFlags,kcfCollideConnected);
27476 end else begin
27477 Exclude(fFlags,kcfCollideConnected);
27478 end;
27479
27480 fRigidBodies[0]:=ARigidBodyA;
27481 fRigidBodies[1]:=ARigidBodyB;
27482
27483 inherited Create(APhysics);
27484
27485 end;
27486
27487 destructor TKraftConstraintJointFixed.Destroy;
27488 begin
27489 inherited Destroy;
27490 end;
27491
27492 procedure TKraftConstraintJointFixed.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
27493 var cA,vA,wA,cB,vB,wB:PKraftVector3;
27494 qA,qB:PKraftQuaternion;
27495 InverseMassOfBodies,BiasFactor:TKraftScalar;
27496 SkewSymmetricMatrices:array[0..1] of TKraftMatrix3x3;
27497 MassMatrix:TKraftMatrix3x3;
27498 CurrentOrientationDifference,qError:TKraftQuaternion;
27499 begin
27500
27501 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
27502 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
27503
27504 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
27505 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
27506
27507 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
27508 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
27509
27510 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
27511 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
27512
27513 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
27514 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
27515
27516 fSolverPositions[0]:[email protected][fIslandIndices[0]];
27517 fSolverPositions[1]:[email protected][fIslandIndices[1]];
27518
27519 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
27520 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
27521
27522 cA:=@fSolverPositions[0]^.Position;
27523 qA:=@fSolverPositions[0]^.Orientation;
27524 vA:=@fSolverVelocities[0]^.LinearVelocity;
27525 wA:=@fSolverVelocities[0]^.AngularVelocity;
27526
27527 cB:=@fSolverPositions[1]^.Position;
27528 qB:=@fSolverPositions[1]^.Orientation;
27529 vB:=@fSolverVelocities[1]^.LinearVelocity;
27530 wB:=@fSolverVelocities[1]^.AngularVelocity;
27531
27532 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
27533 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
27534
27535 SkewSymmetricMatrices[0]:=GetSkewSymmetricMatrixPlus(fRelativePositions[0]);
27536 SkewSymmetricMatrices[1]:=GetSkewSymmetricMatrixPlus(fRelativePositions[1]);
27537
27538 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
27539
27540 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27541 MassMatrix[0,0]:=InverseMassOfBodies;
27542 MassMatrix[0,1]:=0.0;
27543 MassMatrix[0,2]:=0.0;
27544 {$ifdef SIMD}
27545 MassMatrix[0,3]:=0.0;
27546 {$endif}
27547 MassMatrix[1,0]:=0.0;
27548 MassMatrix[1,1]:=InverseMassOfBodies;
27549 MassMatrix[1,2]:=0.0;
27550 {$ifdef SIMD}
27551 MassMatrix[1,3]:=0.0;
27552 {$endif}
27553 MassMatrix[2,0]:=0.0;
27554 MassMatrix[2,1]:=0.0;
27555 MassMatrix[2,2]:=InverseMassOfBodies;
27556 {$ifdef SIMD}
27557 MassMatrix[2,3]:=0.0;
27558 {$endif}
27559 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[0],fWorldInverseInertiaTensors[0]),SkewSymmetricMatrices[0]));
27560 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[1],fWorldInverseInertiaTensors[1]),SkewSymmetricMatrices[1]));
27561 fInverseMassMatrixTranslation:=Matrix3x3TermInverse(MassMatrix);
27562 fInverseMassMatrixRotation:=Matrix3x3TermInverse(Matrix3x3TermAdd(fWorldInverseInertiaTensors[0],fWorldInverseInertiaTensors[1]));
27563 end else begin
27564 fInverseMassMatrixTranslation:=Matrix3x3Null;
27565 fInverseMassMatrixRotation:=Matrix3x3Null;
27566 end;
27567
27568 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27569
27570 fBiasTranslation:=Vector3Origin;
27571 fBiasRotation:=Vector3Origin;
27572
27573 end else begin
27574
27575 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
27576
27577 fBiasTranslation:=Vector3ScalarMul(Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0])),BiasFactor);
27578
27579 CurrentOrientationDifference:=QuaternionTermNormalize(QuaternionMul(qB^,QuaternionInverse(qA^)));
27580 qError:=QuaternionMul(CurrentOrientationDifference,fInverseInitialOrientationDifference);
27581 fBiasRotation:=Vector3ScalarMul(Vector3(qError.x,qError.y,qError.z),BiasFactor*2.0);
27582
27583 end;
27584
27585 if fPhysics.fWarmStarting then begin
27586
27587 fAccumulatedImpulseTranslation:=Vector3ScalarMul(fAccumulatedImpulseTranslation,TimeStep.DeltaTimeRatio);
27588 fAccumulatedImpulseRotation:=Vector3ScalarMul(fAccumulatedImpulseRotation,TimeStep.DeltaTimeRatio);
27589
27590 Vector3DirectSub(vA^,Vector3Mul(fAccumulatedImpulseTranslation,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27591 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Add(Vector3Cross(fRelativePositions[0],fAccumulatedImpulseTranslation),fAccumulatedImpulseRotation),fWorldInverseInertiaTensors[0]));
27592
27593 Vector3DirectAdd(vB^,Vector3Mul(fAccumulatedImpulseTranslation,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27594 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Add(Vector3Cross(fRelativePositions[1],fAccumulatedImpulseTranslation),fAccumulatedImpulseRotation),fWorldInverseInertiaTensors[1]));
27595
27596 end else begin
27597
27598 fAccumulatedImpulseTranslation:=Vector3Origin;
27599 fAccumulatedImpulseRotation:=Vector3Origin;
27600
27601 end;
27602
27603 end;
27604
27605 procedure TKraftConstraintJointFixed.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
27606 var vA,wA,vB,wB:PKraftVector3;
27607 Jv,Impulse:TKraftVector3;
27608 begin
27609
27610 vA:=@fSolverVelocities[0]^.LinearVelocity;
27611 wA:=@fSolverVelocities[0]^.AngularVelocity;
27612
27613 vB:=@fSolverVelocities[1]^.LinearVelocity;
27614 wB:=@fSolverVelocities[1]^.AngularVelocity;
27615
27616 (**** Translation ****)
27617
27618 // Cdot = dot(u, v + cross(w, r))
27619 Jv:=Vector3Sub(Vector3Add(vB^,Vector3Cross(wB^,fRelativePositions[1])),
27620 Vector3Add(vA^,Vector3Cross(wA^,fRelativePositions[0])));
27621
27622 Impulse:=Vector3TermMatrixMul(Vector3Sub(Vector3Neg(Jv),fBiasTranslation),fInverseMassMatrixTranslation);
27623
27624 fAccumulatedImpulseTranslation:=Vector3Add(fAccumulatedImpulseTranslation,Impulse);
27625
27626 Vector3DirectSub(vA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27627 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],Impulse),fWorldInverseInertiaTensors[0]));
27628
27629 Vector3DirectAdd(vB^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27630 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],Impulse),fWorldInverseInertiaTensors[1]));
27631
27632 (**** Rotation ****)
27633
27634 Jv:=Vector3Sub(wB^,wA^);
27635
27636 Impulse:=Vector3TermMatrixMul(Vector3Sub(Vector3Neg(Jv),fBiasRotation),fInverseMassMatrixRotation);
27637
27638 fAccumulatedImpulseRotation:=Vector3Add(fAccumulatedImpulseRotation,Impulse);
27639
27640 Vector3DirectSub(wA^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[0]));
27641
27642 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]));
27643
27644 end;
27645
27646 function TKraftConstraintJointFixed.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
27647 var cA,cB:PKraftVector3;
27648 qA,qB:PKraftQuaternion;
27649 rA,rB,TranslationError,RotationError,Impulse:TKraftVector3;
27650 InverseMassOfBodies:TKraftScalar;
27651 SkewSymmetricMatrices:array[0..1] of TKraftMatrix3x3;
27652 MassMatrix:TKraftMatrix3x3;
27653 CurrentOrientationDifference,qError:TKraftQuaternion;
27654 begin
27655
27656 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27657
27658 cA:=@fSolverPositions[0]^.Position;
27659 qA:=@fSolverPositions[0]^.Orientation;
27660
27661 cB:=@fSolverPositions[1]^.Position;
27662 qB:=@fSolverPositions[1]^.Orientation;
27663
27664 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
27665 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
27666
27667 SkewSymmetricMatrices[0]:=GetSkewSymmetricMatrixPlus(rA);
27668 SkewSymmetricMatrices[1]:=GetSkewSymmetricMatrixPlus(rB);
27669
27670 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
27671
27672 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27673 MassMatrix[0,0]:=InverseMassOfBodies;
27674 MassMatrix[0,1]:=0.0;
27675 MassMatrix[0,2]:=0.0;
27676 {$ifdef SIMD}
27677 MassMatrix[0,3]:=0.0;
27678 {$endif}
27679 MassMatrix[1,0]:=0.0;
27680 MassMatrix[1,1]:=InverseMassOfBodies;
27681 MassMatrix[1,2]:=0.0;
27682 {$ifdef SIMD}
27683 MassMatrix[1,3]:=0.0;
27684 {$endif}
27685 MassMatrix[2,0]:=0.0;
27686 MassMatrix[2,1]:=0.0;
27687 MassMatrix[2,2]:=InverseMassOfBodies;
27688 {$ifdef SIMD}
27689 MassMatrix[2,3]:=0.0;
27690 {$endif}
27691 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[0],fWorldInverseInertiaTensors[0]),SkewSymmetricMatrices[0]));
27692 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[1],fWorldInverseInertiaTensors[1]),SkewSymmetricMatrices[1]));
27693 fInverseMassMatrixTranslation:=Matrix3x3TermInverse(MassMatrix);
27694 end else begin
27695 fInverseMassMatrixTranslation:=Matrix3x3Null;
27696 end;
27697
27698 (**** Translation ****)
27699
27700 TranslationError:=Vector3Sub(Vector3Add(cB^,rB),Vector3Add(cA^,rA));
27701
27702 result:=Vector3Length(TranslationError)<fPhysics.fLinearSlop;
27703
27704 Impulse:=Vector3TermMatrixMul(Vector3Neg(TranslationError),fInverseMassMatrixTranslation);
27705
27706 Vector3DirectSub(cA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
27707 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(Impulse)),fWorldInverseInertiaTensors[0]),1.0);
27708
27709 Vector3DirectAdd(cB^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
27710 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Vector3Cross(rB,Impulse),fWorldInverseInertiaTensors[1]),1.0);
27711
27712 (**** Rotation ****)
27713
27714 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27715 fInverseMassMatrixRotation:=Matrix3x3TermInverse(Matrix3x3TermAdd(fWorldInverseInertiaTensors[0],fWorldInverseInertiaTensors[1]));
27716 end else begin
27717 fInverseMassMatrixRotation:=Matrix3x3Null;
27718 end;
27719
27720 CurrentOrientationDifference:=QuaternionTermNormalize(QuaternionMul(qB^,QuaternionInverse(qA^)));
27721 qError:=QuaternionMul(CurrentOrientationDifference,fInverseInitialOrientationDifference);
27722 RotationError.x:=qError.x*2.0;
27723 RotationError.y:=qError.y*2.0;
27724 RotationError.z:=qError.z*2.0;
27725
27726 result:=result and (Vector3Length(RotationError)<fPhysics.fAngularSlop);
27727
27728 Impulse:=Vector3TermMatrixMul(Vector3Neg(RotationError),fInverseMassMatrixRotation);
27729
27730 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(Impulse),fWorldInverseInertiaTensors[0]),1.0);
27731
27732 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]),1.0);
27733
27734 end else begin
27735
27736 result:=true;
27737
27738 end;
27739
27740 end;
27741
27742 function TKraftConstraintJointFixed.GetAnchorA:TKraftVector3;
27743 begin
27744 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
27745 end;
27746
27747 function TKraftConstraintJointFixed.GetAnchorB:TKraftVector3;
27748 begin
27749 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
27750 end;
27751
27752 function TKraftConstraintJointFixed.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
27753 begin
27754 result:=Vector3ScalarMul(fAccumulatedImpulseTranslation,InverseDeltaTime);
27755 end;
27756
27757 function TKraftConstraintJointFixed.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
27758 begin
27759 result:=Vector3ScalarMul(fAccumulatedImpulseRotation,InverseDeltaTime);
27760 end;
27761
27762 constructor TKraftConstraintJointHinge.Create(const APhysics:TKraft;
27763 const ARigidBodyA,ARigidBodyB:TKraftRigidBody;
27764 const AWorldAnchorPoint:TKraftVector3;
27765 const AWorldRotationAxis:TKraftVector3;
27766 const ALimitEnabled:boolean=false;
27767 const AMotorEnabled:boolean=false;
27768 const AMinimumAngleLimit:TKraftScalar=-1.0;
27769 const AMaximumAngleLimit:TKraftScalar=1.0;
27770 const AMotorSpeed:TKraftScalar=0.0;
27771 const AMaximalMotorTorque:TKraftScalar=0.0;
27772 const ACollideConnected:boolean=false);
27773 begin
27774
27775 fLimitState:=ALimitEnabled;
27776
27777 fMotorState:=AMotorEnabled;
27778
27779 fLowerLimit:=AMinimumAngleLimit;
27780
27781 fUpperLimit:=AMaximumAngleLimit;
27782
27783 Assert((fLowerLimit<=EPSILON) and (fLowerLimit>=(-(pi2+EPSILON))));
27784
27785 Assert((fUpperLimit>=(-EPSILON)) and (fUpperLimit<=(pi2+EPSILON)));
27786
27787 fMotorSpeed:=AMotorSpeed;
27788
27789 fMaximalMotorTorque:=AMaximalMotorTorque;
27790
27791 fLocalAnchors[0]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyA.fWorldTransform);
27792 fLocalAnchors[1]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyB.fWorldTransform);
27793
27794 fLocalAxes[0]:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(AWorldRotationAxis,ARigidBodyA.fWorldTransform));
27795 fLocalAxes[1]:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(AWorldRotationAxis,ARigidBodyB.fWorldTransform));
27796
27797 fAccumulatedImpulseLowerLimit:=0.0;
27798 fAccumulatedImpulseUpperLimit:=0.0;
27799 fAccumulatedImpulseMotor:=0.0;
27800 fAccumulatedImpulseTranslation:=Vector3Origin;
27801 fAccumulatedImpulseRotation:=Vector2Origin;
27802
27803 fBiasLowerLimit:=0.0;
27804 fBiasUpperLimit:=0.0;
27805
27806 fInverseInitialOrientationDifference:=QuaternionInverse(QuaternionTermNormalize(QuaternionMul(ARigidBodyB.fSweep.q0,QuaternionInverse(ARigidBodyA.fSweep.q0))));
27807
27808 if ACollideConnected then begin
27809 Include(fFlags,kcfCollideConnected);
27810 end else begin
27811 Exclude(fFlags,kcfCollideConnected);
27812 end;
27813
27814 fRigidBodies[0]:=ARigidBodyA;
27815 fRigidBodies[1]:=ARigidBodyB;
27816
27817 inherited Create(APhysics);
27818
27819 end;
27820
27821 destructor TKraftConstraintJointHinge.Destroy;
27822 begin
27823 inherited Destroy;
27824 end;
27825
27826 function TKraftConstraintJointHinge.ComputeCurrentHingeAngle(const OrientationA,OrientationB:TKraftQuaternion):TKraftScalar;
27827 function ComputeNormalizedAngle(a:TKraftScalar):TKraftScalar;
27828 begin
27829 result:=a-(floor(a/pi2)*pi2); // ModuloPos(ModuloPos(a+pi,pi2)+pi2,pi2)-pi;
27830 while result<-pi do begin
27831 result:=result+pi2;
27832 end;
27833 while result>pi do begin
27834 result:=result-pi2;
27835 end;
27836 end;
27837 var CurrentOrientationDifference,RelativeRotation:TKraftQuaternion;
27838 CosHalfAngle,SinHalfAngleAbs,DotProduct:TKraftScalar;
27839 begin
27840 // Compute the current orientation difference between the two bodies
27841 CurrentOrientationDifference:=QuaternionTermNormalize(QuaternionMul(OrientationB,QuaternionInverse(OrientationA)));
27842
27843 // Compute the relative rotation considering the initial orientation difference
27844 RelativeRotation:=QuaternionTermNormalize(QuaternionMul(CurrentOrientationDifference,fInverseInitialOrientationDifference));
27845
27846 // Extract cos(theta/2) and |sin(theta/2)|
27847 CosHalfAngle:=RelativeRotation.w;
27848 SinHalfAngleAbs:=Vector3Length(PKraftVector3(pointer(@RelativeRotation))^);
27849
27850 // Compute the dot product of the relative rotation axis and the hinge axis
27851 DotProduct:=Vector3Dot(PKraftVector3(pointer(@RelativeRotation))^,PKraftVector3(pointer(@fA1))^);
27852
27853 // If the relative rotation axis and the hinge axis are pointing the same direction
27854 if DotProduct>=0.0 then begin
27855 result:=2.0*ArcTan2(SinHalfAngleAbs,CosHalfAngle);
27856 end else begin
27857 result:=2.0*ArcTan2(SinHalfAngleAbs,-CosHalfAngle);
27858 end;
27859
27860 // Convert the angle from range [-2*pi; 2*pi] into the range [-pi; pi]
27861 result:=ComputeNormalizedAngle(result);
27862
27863 // Compute and return the corresponding angle near one the two limits
27864 if fLowerLimit<fUpperLimit then begin
27865 if result>fUpperLimit then begin
27866 if abs(ComputeNormalizedAngle(result-fUpperLimit))>abs(ComputeNormalizedAngle(result-fLowerLimit)) then begin
27867 result:=result-pi2;
27868 end;
27869 end else if result<fLowerLimit then begin
27870 if abs(ComputeNormalizedAngle(fUpperLimit-result))<=abs(ComputeNormalizedAngle(fLowerLimit-result)) then begin
27871 result:=result+pi2;
27872 end;
27873 end;
27874 end;
27875
27876 end;
27877
27878 procedure TKraftConstraintJointHinge.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
27879 var cA,vA,wA,cB,vB,wB:PKraftVector3;
27880 qA,qB:PKraftQuaternion;
27881 HingeAngle,LowerLimitError,UpperLimitError,InverseMassOfBodies,BiasFactor:TKraftScalar;
27882 SkewSymmetricMatrices:array[0..1] of TKraftMatrix3x3;
27883 MassMatrix:TKraftMatrix3x3;
27884 RotationKMatrix:TKraftMatrix2x2;
27885 OldIsLowerLimitViolated,OldIsUpperLimitViolated:boolean;
27886 a2,b2,c2,I1B2CrossA1,I1C2CrossA1,I2B2CrossA1,I2C2CrossA1,RotationImpulse,LimitsImpulse,MotorImpulse,AngularImpulse:TKraftVector3;
27887 begin
27888
27889 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
27890 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
27891
27892 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
27893 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
27894
27895 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
27896 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
27897
27898 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
27899 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
27900
27901 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
27902 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
27903
27904 fSolverPositions[0]:[email protected][fIslandIndices[0]];
27905 fSolverPositions[1]:[email protected][fIslandIndices[1]];
27906
27907 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
27908 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
27909
27910 cA:=@fSolverPositions[0]^.Position;
27911 qA:=@fSolverPositions[0]^.Orientation;
27912 vA:=@fSolverVelocities[0]^.LinearVelocity;
27913 wA:=@fSolverVelocities[0]^.AngularVelocity;
27914
27915 cB:=@fSolverPositions[1]^.Position;
27916 qB:=@fSolverPositions[1]^.Orientation;
27917 vB:=@fSolverVelocities[1]^.LinearVelocity;
27918 wB:=@fSolverVelocities[1]^.AngularVelocity;
27919
27920 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
27921 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
27922
27923 HingeAngle:=ComputeCurrentHingeAngle(qA^,qB^);
27924
27925 LowerLimitError:=HingeAngle-fLowerLimit;
27926 UpperLimitError:=fUpperLimit-HingeAngle;
27927 OldIsLowerLimitViolated:=fIsLowerLimitViolated;
27928 fIsLowerLimitViolated:=LowerLimitError<=0.0;
27929 if fIsLowerLimitViolated<>OldIsLowerLimitViolated then begin
27930 fAccumulatedImpulseLowerLimit:=0.0;
27931 end;
27932 OldIsUpperLimitViolated:=fIsUpperLimitViolated;
27933 fIsUpperLimitViolated:=UpperLimitError<=0.0;
27934 if fIsUpperLimitViolated<>OldIsUpperLimitViolated then begin
27935 fAccumulatedImpulseUpperLimit:=0.0;
27936 end;
27937
27938 fA1:=Vector3NormEx(Vector3TermQuaternionRotate(fLocalAxes[0],qA^));
27939 a2:=Vector3NormEx(Vector3TermQuaternionRotate(fLocalAxes[1],qB^));
27940 b2:=Vector3GetOneUnitOrthogonalVector(a2);
27941 c2:=Vector3Cross(a2,b2);
27942 fB2CrossA1:=Vector3Cross(b2,fA1);
27943 fC2CrossA1:=Vector3Cross(c2,fA1);
27944
27945 SkewSymmetricMatrices[0]:=GetSkewSymmetricMatrixPlus(fRelativePositions[0]);
27946 SkewSymmetricMatrices[1]:=GetSkewSymmetricMatrixPlus(fRelativePositions[1]);
27947
27948 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
27949
27950 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27951 MassMatrix[0,0]:=InverseMassOfBodies;
27952 MassMatrix[0,1]:=0.0;
27953 MassMatrix[0,2]:=0.0;
27954 {$ifdef SIMD}
27955 MassMatrix[0,3]:=0.0;
27956 {$endif}
27957 MassMatrix[1,0]:=0.0;
27958 MassMatrix[1,1]:=InverseMassOfBodies;
27959 MassMatrix[1,2]:=0.0;
27960 {$ifdef SIMD}
27961 MassMatrix[1,3]:=0.0;
27962 {$endif}
27963 MassMatrix[2,0]:=0.0;
27964 MassMatrix[2,1]:=0.0;
27965 MassMatrix[2,2]:=InverseMassOfBodies;
27966 {$ifdef SIMD}
27967 MassMatrix[2,3]:=0.0;
27968 {$endif}
27969 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[0],fWorldInverseInertiaTensors[0]),SkewSymmetricMatrices[0]));
27970 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[1],fWorldInverseInertiaTensors[1]),SkewSymmetricMatrices[1]));
27971 fInverseMassMatrixTranslation:=Matrix3x3TermInverse(MassMatrix);
27972 end else begin
27973 fInverseMassMatrixTranslation:=Matrix3x3Null;
27974 end;
27975
27976 I1B2CrossA1:=Vector3TermMatrixMul(fB2CrossA1,fWorldInverseInertiaTensors[0]);
27977 I1C2CrossA1:=Vector3TermMatrixMul(fC2CrossA1,fWorldInverseInertiaTensors[0]);
27978 I2B2CrossA1:=Vector3TermMatrixMul(fB2CrossA1,fWorldInverseInertiaTensors[1]);
27979 I2C2CrossA1:=Vector3TermMatrixMul(fC2CrossA1,fWorldInverseInertiaTensors[1]);
27980 RotationKMatrix[0,0]:=Vector3Dot(fB2CrossA1,I1B2CrossA1)+Vector3Dot(fB2CrossA1,I2B2CrossA1);
27981 RotationKMatrix[0,1]:=Vector3Dot(fB2CrossA1,I1C2CrossA1)+Vector3Dot(fB2CrossA1,I2C2CrossA1);
27982 RotationKMatrix[1,0]:=Vector3Dot(fC2CrossA1,I1B2CrossA1)+Vector3Dot(fC2CrossA1,I2B2CrossA1);
27983 RotationKMatrix[1,1]:=Vector3Dot(fC2CrossA1,I1C2CrossA1)+Vector3Dot(fC2CrossA1,I2C2CrossA1);
27984 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
27985 Matrix2x2Inverse(fInverseMassMatrixRotation,RotationKMatrix);
27986 end else begin
27987 fInverseMassMatrixRotation:=Matrix2x2Null;
27988 end;
27989
27990 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
27991 BiasFactor:=0.0;
27992 fBiasTranslation:=Vector3Origin;
27993 fBiasRotation:=Vector2Origin;
27994 end else begin
27995 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
27996 fBiasTranslation:=Vector3ScalarMul(Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0])),BiasFactor);
27997 fBiasRotation:=Vector2ScalarMul(Vector2(Vector3Dot(fA1,b2),Vector3Dot(fA1,c2)),BiasFactor);
27998 end;
27999
28000 if fMotorState or (fLimitState and (fIsLowerLimitViolated or fIsUpperLimitViolated)) then begin
28001 // Compute the inverse of the mass matrix K=JM^-1J^t for the limits and motor (1x1 matrix)
28002 fInverseMassMatrixLimitMotor:=Vector3Dot(fA1,Vector3TermMatrixMul(fA1,fWorldInverseInertiaTensors[0]))+
28003 Vector3Dot(fA1,Vector3TermMatrixMul(fA1,fWorldInverseInertiaTensors[1]));
28004 if fInverseMassMatrixLimitMotor>0.0 then begin
28005 fInverseMassMatrixLimitMotor:=1.0/fInverseMassMatrixLimitMotor;
28006 end else begin
28007 fInverseMassMatrixLimitMotor:=0.0;
28008 end;
28009 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
28010 fBiasLowerLimit:=0.0;
28011 fBiasUpperLimit:=0.0;
28012 end else begin
28013 fBiasLowerLimit:=LowerLimitError*BiasFactor;
28014 fBiasUpperLimit:=UpperLimitError*BiasFactor;
28015 end;
28016 end;
28017
28018 if fPhysics.fWarmStarting then begin
28019
28020 // Compute the impulse P=J^T * lambda for the 2 rotation constraints
28021 RotationImpulse:=Vector3Add(Vector3ScalarMul(fB2CrossA1,fAccumulatedImpulseRotation.x),
28022 Vector3ScalarMul(fC2CrossA1,fAccumulatedImpulseRotation.y));
28023
28024 // Compute the impulse P=J^T * lambda for the lower and upper limits constraints
28025 LimitsImpulse:=Vector3ScalarMul(fA1,fAccumulatedImpulseLowerLimit-fAccumulatedImpulseUpperLimit);
28026
28027 // Compute the impulse P=J^T * lambda for the motor constraint
28028 MotorImpulse:=Vector3ScalarMul(fA1,fAccumulatedImpulseMotor);
28029
28030 fAccumulatedImpulseTranslation:=Vector3ScalarMul(fAccumulatedImpulseTranslation,TimeStep.DeltaTimeRatio);
28031
28032 AngularImpulse:=Vector3ScalarMul(Vector3Add(Vector3Add(RotationImpulse,LimitsImpulse),MotorImpulse),TimeStep.DeltaTimeRatio);
28033
28034 Vector3DirectSub(vA^,Vector3Mul(fAccumulatedImpulseTranslation,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28035 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Add(Vector3Cross(fRelativePositions[0],fAccumulatedImpulseTranslation),AngularImpulse),fWorldInverseInertiaTensors[0]));
28036
28037 Vector3DirectAdd(vB^,Vector3Mul(fAccumulatedImpulseTranslation,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28038 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Add(Vector3Cross(fRelativePositions[1],fAccumulatedImpulseTranslation),AngularImpulse),fWorldInverseInertiaTensors[1]));
28039
28040 end else begin
28041
28042 fAccumulatedImpulseTranslation:=Vector3Origin;
28043 fAccumulatedImpulseRotation:=Vector2Origin;
28044 fAccumulatedImpulseLowerLimit:=0.0;
28045 fAccumulatedImpulseUpperLimit:=0.0;
28046 fAccumulatedImpulseMotor:=0.0;
28047
28048 end;
28049
28050 end;
28051
28052 procedure TKraftConstraintJointHinge.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
28053 var vA,wA,vB,wB:PKraftVector3;
28054 vpA,vpB,Jv,Impulse:TKraftVector3;
28055 JvRotation,RotationImpulse:TKraftVector2;
28056 JvLowerLimit,ImpulseLower,JvUpperLimit,ImpulseUpper,JvMotor,ImpulseMotor,LambdaTemp,MaximalMotorImpulse:TKraftScalar;
28057 begin
28058
28059 vA:=@fSolverVelocities[0]^.LinearVelocity;
28060 wA:=@fSolverVelocities[0]^.AngularVelocity;
28061
28062 vB:=@fSolverVelocities[1]^.LinearVelocity;
28063 wB:=@fSolverVelocities[1]^.AngularVelocity;
28064
28065 (**** Translation ****)
28066
28067 // Cdot = dot(u, v + cross(w, r))
28068 vpA:=Vector3Add(vA^,Vector3Cross(wA^,fRelativePositions[0]));
28069 vpB:=Vector3Add(vB^,Vector3Cross(wB^,fRelativePositions[1]));
28070 Jv:=Vector3Sub(vpB,vpA);
28071
28072 Impulse:=Vector3TermMatrixMul(Vector3Sub(Vector3Neg(Jv),fBiasTranslation),fInverseMassMatrixTranslation);
28073
28074 fAccumulatedImpulseTranslation:=Vector3Add(fAccumulatedImpulseTranslation,Impulse);
28075
28076 Vector3DirectSub(vA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28077 Vector3DirectSub(wA^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[0],Impulse),fWorldInverseInertiaTensors[0]));
28078
28079 Vector3DirectAdd(vB^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28080 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Vector3Cross(fRelativePositions[1],Impulse),fWorldInverseInertiaTensors[1]));
28081
28082 (**** Rotation ****)
28083
28084 JvRotation.x:=(Vector3Dot(fB2CrossA1,wB^)-Vector3Dot(fB2CrossA1,wA^))+fBiasRotation.x;
28085 JvRotation.y:=(Vector3Dot(fC2CrossA1,wB^)-Vector3Dot(fC2CrossA1,wA^))+fBiasRotation.y;
28086
28087 RotationImpulse.x:=-((JvRotation.x*fInverseMassMatrixRotation[0,0])+(JvRotation.y*fInverseMassMatrixRotation[0,1]));
28088 RotationImpulse.y:=-((JvRotation.x*fInverseMassMatrixRotation[1,0])+(JvRotation.y*fInverseMassMatrixRotation[1,1]));
28089
28090 fAccumulatedImpulseRotation.x:=fAccumulatedImpulseRotation.x+RotationImpulse.x;
28091 fAccumulatedImpulseRotation.y:=fAccumulatedImpulseRotation.y+RotationImpulse.y;
28092
28093 Impulse:=Vector3Add(Vector3ScalarMul(fB2CrossA1,RotationImpulse.x),
28094 Vector3ScalarMul(fC2CrossA1,RotationImpulse.y));
28095
28096 Vector3DirectSub(wA^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[0]));
28097
28098 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]));
28099
28100 (**** Limits ****)
28101
28102 if fLimitState then begin
28103 if fIsLowerLimitViolated then begin
28104 JvLowerLimit:=Vector3Dot(Vector3Sub(wB^,wA^),fA1);
28105 ImpulseLower:=fInverseMassMatrixLimitMotor*(-(JvLowerLimit+fBiasLowerLimit));
28106 LambdaTemp:=fAccumulatedImpulseLowerLimit;
28107 fAccumulatedImpulseLowerLimit:=Max(0.0,fAccumulatedImpulseLowerLimit+ImpulseLower);
28108 ImpulseLower:=fAccumulatedImpulseLowerLimit-LambdaTemp;
28109 Impulse:=Vector3ScalarMul(fA1,ImpulseLower);
28110 Vector3DirectSub(wA^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[0]));
28111 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]));
28112 end;
28113 if fIsUpperLimitViolated then begin
28114 JvUpperLimit:=-Vector3Dot(Vector3Sub(wB^,wA^),fA1);
28115 ImpulseUpper:=fInverseMassMatrixLimitMotor*(-(JvUpperLimit++fBiasUpperLimit));
28116 LambdaTemp:=fAccumulatedImpulseUpperLimit;
28117 fAccumulatedImpulseUpperLimit:=Max(0.0,fAccumulatedImpulseUpperLimit+ImpulseUpper);
28118 ImpulseUpper:=-(fAccumulatedImpulseUpperLimit-LambdaTemp);
28119 Impulse:=Vector3ScalarMul(fA1,ImpulseUpper);
28120 Vector3DirectSub(wA^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[0]));
28121 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]));
28122 end;
28123 end;
28124
28125 (**** Motor ****)
28126
28127 if fMotorState then begin
28128 JvMotor:=Vector3Dot(Vector3Sub(wB^,wA^),fA1);
28129 ImpulseMotor:=fInverseMassMatrixLimitMotor*(-JvMotor);
28130 LambdaTemp:=fAccumulatedImpulseMotor;
28131 MaximalMotorImpulse:=fMaximalMotorTorque*TimeStep.DeltaTime;
28132 fAccumulatedImpulseMotor:=Min(Max(fAccumulatedImpulseMotor+ImpulseMotor,-MaximalMotorImpulse),MaximalMotorImpulse);
28133 ImpulseMotor:=fAccumulatedImpulseMotor-LambdaTemp;
28134 Impulse:=Vector3ScalarMul(fA1,ImpulseMotor);
28135 Vector3DirectSub(wA^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[0]));
28136 Vector3DirectAdd(wB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]));
28137 end;
28138
28139 end;
28140
28141 function TKraftConstraintJointHinge.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
28142 var cA,cB:PKraftVector3;
28143 qA,qB:PKraftQuaternion;
28144 rA,rB,TranslationError,Impulse,a2,b2,c2,I1B2CrossA1,I1C2CrossA1,I2B2CrossA1,I2C2CrossA1:TKraftVector3;
28145 RotationError,RotationImpulse:TKraftVector2;
28146 InverseMassOfBodies,HingeAngle,LowerLimitError,UpperLimitError,ImpulseLower,ImpulseUpper:TKraftScalar;
28147 SkewSymmetricMatrices:array[0..1] of TKraftMatrix3x3;
28148 MassMatrix:TKraftMatrix3x3;
28149 RotationKMatrix:TKraftMatrix2x2;
28150 begin
28151
28152 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
28153
28154 cA:=@fSolverPositions[0]^.Position;
28155 qA:=@fSolverPositions[0]^.Orientation;
28156
28157 cB:=@fSolverPositions[1]^.Position;
28158 qB:=@fSolverPositions[1]^.Orientation;
28159
28160 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
28161 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
28162
28163 HingeAngle:=ComputeCurrentHingeAngle(qA^,qB^);
28164
28165 LowerLimitError:=HingeAngle-fLowerLimit;
28166 UpperLimitError:=fUpperLimit-HingeAngle;
28167 fIsLowerLimitViolated:=LowerLimitError<=0.0;
28168 fIsUpperLimitViolated:=UpperLimitError<=0.0;
28169
28170 fA1:=Vector3NormEx(Vector3TermQuaternionRotate(fLocalAxes[0],qA^));
28171 a2:=Vector3NormEx(Vector3TermQuaternionRotate(fLocalAxes[1],qB^));
28172 b2:=Vector3GetOneUnitOrthogonalVector(a2);
28173 c2:=Vector3Cross(a2,b2);
28174 fB2CrossA1:=Vector3Cross(b2,fA1);
28175 fC2CrossA1:=Vector3Cross(c2,fA1);
28176
28177 SkewSymmetricMatrices[0]:=GetSkewSymmetricMatrixPlus(rA);
28178 SkewSymmetricMatrices[1]:=GetSkewSymmetricMatrixPlus(rB);
28179
28180 (**** Translation ****)
28181
28182 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
28183
28184 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
28185 MassMatrix[0,0]:=InverseMassOfBodies;
28186 MassMatrix[0,1]:=0.0;
28187 MassMatrix[0,2]:=0.0;
28188 {$ifdef SIMD}
28189 MassMatrix[0,3]:=0.0;
28190 {$endif}
28191 MassMatrix[1,0]:=0.0;
28192 MassMatrix[1,1]:=InverseMassOfBodies;
28193 MassMatrix[1,2]:=0.0;
28194 {$ifdef SIMD}
28195 MassMatrix[1,3]:=0.0;
28196 {$endif}
28197 MassMatrix[2,0]:=0.0;
28198 MassMatrix[2,1]:=0.0;
28199 MassMatrix[2,2]:=InverseMassOfBodies;
28200 {$ifdef SIMD}
28201 MassMatrix[2,3]:=0.0;
28202 {$endif}
28203 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[0],fWorldInverseInertiaTensors[0]),SkewSymmetricMatrices[0]));
28204 Matrix3x3Add(MassMatrix,Matrix3x3TermMulTranspose(Matrix3x3TermMul(SkewSymmetricMatrices[1],fWorldInverseInertiaTensors[1]),SkewSymmetricMatrices[1]));
28205 fInverseMassMatrixTranslation:=Matrix3x3TermInverse(MassMatrix);
28206 end else begin
28207 fInverseMassMatrixTranslation:=Matrix3x3Null;
28208 end;
28209
28210 TranslationError:=Vector3Sub(Vector3Add(cB^,rB),Vector3Add(cA^,rA));
28211
28212 result:=Vector3Length(TranslationError)<fPhysics.fLinearSlop;
28213
28214 Impulse:=Vector3TermMatrixMul(Vector3Neg(TranslationError),fInverseMassMatrixTranslation);
28215
28216 Vector3DirectSub(cA^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28217 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(Impulse)),fWorldInverseInertiaTensors[0]),1.0);
28218
28219 Vector3DirectAdd(cB^,Vector3Mul(Impulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28220 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Vector3Cross(rB,Impulse),fWorldInverseInertiaTensors[1]),1.0);
28221
28222 (**** Rotation ****)
28223
28224 I1B2CrossA1:=Vector3TermMatrixMul(fB2CrossA1,fWorldInverseInertiaTensors[0]);
28225 I1C2CrossA1:=Vector3TermMatrixMul(fC2CrossA1,fWorldInverseInertiaTensors[0]);
28226 I2B2CrossA1:=Vector3TermMatrixMul(fB2CrossA1,fWorldInverseInertiaTensors[1]);
28227 I2C2CrossA1:=Vector3TermMatrixMul(fC2CrossA1,fWorldInverseInertiaTensors[1]);
28228 RotationKMatrix[0,0]:=Vector3Dot(fB2CrossA1,I1B2CrossA1)+Vector3Dot(fB2CrossA1,I2B2CrossA1);
28229 RotationKMatrix[0,1]:=Vector3Dot(fB2CrossA1,I1C2CrossA1)+Vector3Dot(fB2CrossA1,I2C2CrossA1);
28230 RotationKMatrix[1,0]:=Vector3Dot(fC2CrossA1,I1B2CrossA1)+Vector3Dot(fC2CrossA1,I2B2CrossA1);
28231 RotationKMatrix[1,1]:=Vector3Dot(fC2CrossA1,I1C2CrossA1)+Vector3Dot(fC2CrossA1,I2C2CrossA1);
28232 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
28233 Matrix2x2Inverse(fInverseMassMatrixRotation,RotationKMatrix);
28234 end else begin
28235 fInverseMassMatrixRotation:=Matrix2x2Null;
28236 end;
28237
28238 RotationError.x:=Vector3Dot(fA1,b2);
28239 RotationError.y:=Vector3Dot(fA1,c2);
28240
28241 result:=result and (Vector2Length(RotationError)<fPhysics.fAngularSlop);
28242
28243 RotationImpulse.x:=-((RotationError.x*fInverseMassMatrixRotation[0,0])+(RotationError.y*fInverseMassMatrixRotation[0,1]));
28244 RotationImpulse.y:=-((RotationError.x*fInverseMassMatrixRotation[1,0])+(RotationError.y*fInverseMassMatrixRotation[1,1]));
28245
28246 Impulse:=Vector3Add(Vector3ScalarMul(fB2CrossA1,RotationImpulse.x),Vector3ScalarMul(fC2CrossA1,RotationImpulse.y));
28247
28248 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(Impulse),fWorldInverseInertiaTensors[0]),1.0);
28249
28250 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]),1.0);
28251
28252 (**** Limits ****)
28253
28254 if fLimitState then begin
28255 if fIsLowerLimitViolated then begin
28256 ImpulseLower:=fInverseMassMatrixLimitMotor*(-LowerLimitError);
28257 result:=result and (ImpulseLower<fPhysics.fAngularSlop);
28258 Impulse:=Vector3ScalarMul(fA1,ImpulseLower);
28259 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(Impulse),fWorldInverseInertiaTensors[0]),1.0);
28260 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]),1.0);
28261 end;
28262 if fIsUpperLimitViolated then begin
28263 ImpulseUpper:=fInverseMassMatrixLimitMotor*(-UpperLimitError);
28264 result:=result and (ImpulseUpper<fPhysics.fAngularSlop);
28265 Impulse:=Vector3ScalarMul(fA1,-ImpulseUpper);
28266 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(Impulse),fWorldInverseInertiaTensors[0]),1.0);
28267 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(Impulse,fWorldInverseInertiaTensors[1]),1.0);
28268 end;
28269 end;
28270
28271 end else begin
28272
28273 result:=true;
28274
28275 end;
28276
28277 end;
28278
28279 function TKraftConstraintJointHinge.GetAnchorA:TKraftVector3;
28280 begin
28281 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
28282 end;
28283
28284 function TKraftConstraintJointHinge.GetAnchorB:TKraftVector3;
28285 begin
28286 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
28287 end;
28288
28289 function TKraftConstraintJointHinge.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
28290 begin
28291 result:=Vector3ScalarMul(fAccumulatedImpulseTranslation,InverseDeltaTime);
28292 end;
28293
28294 function TKraftConstraintJointHinge.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
28295 var RotationImpulse,LimitsImpulse,MotorImpulse:TKraftVector3;
28296 begin
28297 RotationImpulse:=Vector3Sub(Vector3ScalarMul(fC2CrossA1,fAccumulatedImpulseRotation.y),
28298 Vector3ScalarMul(fB2CrossA1,-fAccumulatedImpulseRotation.x));
28299 LimitsImpulse:=Vector3ScalarMul(fA1,fAccumulatedImpulseLowerLimit-fAccumulatedImpulseUpperLimit);
28300 MotorImpulse:=Vector3ScalarMul(fA1,fAccumulatedImpulseMotor);
28301 result:=Vector3ScalarMul(Vector3Add(Vector3Add(RotationImpulse,LimitsImpulse),MotorImpulse),InverseDeltaTime);
28302 end;
28303
28304 function TKraftConstraintJointHinge.GetWorldRotationAxis:TKraftVector3;
28305 begin
28306 result:=Vector3TermMatrixMulBasis(fLocalAxes[0],fRigidBodies[0].fWorldTransform);
28307 end;
28308
28309 procedure TKraftConstraintJointHinge.SetWorldRotationAxis(AWorldRotationAxis:TKraftVector3);
28310 begin
28311 fLocalAxes[0]:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(AWorldRotationAxis,fRigidBodies[0].fWorldTransform));
28312 fLocalAxes[1]:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(AWorldRotationAxis,fRigidBodies[1].fWorldTransform));
28313 end;
28314
28315 function TKraftConstraintJointHinge.IsLimitEnabled:boolean;
28316 begin
28317 result:=fLimitState;
28318 end;
28319
28320 function TKraftConstraintJointHinge.IsMotorEnabled:boolean;
28321 begin
28322 result:=fMotorState;
28323 end;
28324
28325 function TKraftConstraintJointHinge.GetMinimumAngleLimit:TKraftScalar;
28326 begin
28327 result:=fLowerLimit;
28328 end;
28329
28330 function TKraftConstraintJointHinge.GetMaximumAngleLimit:TKraftScalar;
28331 begin
28332 result:=fUpperLimit;
28333 end;
28334
28335 function TKraftConstraintJointHinge.GetMotorSpeed:TKraftScalar;
28336 begin
28337 result:=fMotorSpeed;
28338 end;
28339
28340 function TKraftConstraintJointHinge.GetMaximalMotorTorque:TKraftScalar;
28341 begin
28342 result:=fMaximalMotorTorque;
28343 end;
28344
28345 function TKraftConstraintJointHinge.GetMotorTorque(const DeltaTime:TKraftScalar):TKraftScalar;
28346 begin
28347 result:=fAccumulatedImpulseMotor/DeltaTime;
28348 end;
28349
28350 procedure TKraftConstraintJointHinge.ResetLimits;
28351 begin
28352 fAccumulatedImpulseLowerLimit:=0.0;
28353 fAccumulatedImpulseUpperLimit:=0.0;
28354 fRigidBodies[0].SetToAwake;
28355 fRigidBodies[1].SetToAwake;
28356 end;
28357
28358 procedure TKraftConstraintJointHinge.EnableLimit(const ALimitEnabled:boolean);
28359 begin
28360 if fLimitState<>ALimitEnabled then begin
28361 fLimitState:=ALimitEnabled;
28362 ResetLimits;
28363 end;
28364 end;
28365
28366 procedure TKraftConstraintJointHinge.EnableMotor(const AMotorEnabled:boolean);
28367 begin
28368 if fMotorState<>AMotorEnabled then begin
28369 fMotorState:=AMotorEnabled;
28370 fAccumulatedImpulseMotor:=0.0;
28371 fRigidBodies[0].SetToAwake;
28372 fRigidBodies[1].SetToAwake;
28373 end;
28374 end;
28375
28376 procedure TKraftConstraintJointHinge.SetMinimumAngleLimit(const AMinimumAngleLimit:TKraftScalar);
28377 begin
28378 if fLowerLimit<>AMinimumAngleLimit then begin
28379 fLowerLimit:=AMinimumAngleLimit;
28380 Assert((fLowerLimit<=EPSILON) and (fLowerLimit>=(-(pi2+EPSILON))));
28381 ResetLimits;
28382 end;
28383 end;
28384
28385 procedure TKraftConstraintJointHinge.SetMaximumAngleLimit(const AMaximumAngleLimit:TKraftScalar);
28386 begin
28387 if fUpperLimit<>AMaximumAngleLimit then begin
28388 fUpperLimit:=AMaximumAngleLimit;
28389 Assert((fUpperLimit>=(-EPSILON)) and (fUpperLimit<=(pi2+EPSILON)));
28390 ResetLimits;
28391 end;
28392 end;
28393
28394 procedure TKraftConstraintJointHinge.SetMotorSpeed(const AMotorSpeed:TKraftScalar);
28395 begin
28396 if fMotorSpeed<>AMotorSpeed then begin
28397 fMotorSpeed:=AMotorSpeed;
28398 fRigidBodies[0].SetToAwake;
28399 fRigidBodies[1].SetToAwake;
28400 end;
28401 end;
28402
28403 procedure TKraftConstraintJointHinge.SetMaximalMotorTorque(const AMaximalMotorTorque:TKraftScalar);
28404 begin
28405 if fMaximalMotorTorque<>AMaximalMotorTorque then begin
28406 fMaximalMotorTorque:=AMaximalMotorTorque;
28407 Assert(fMaximalMotorTorque>=(-EPSILON));
28408 fRigidBodies[0].SetToAwake;
28409 fRigidBodies[1].SetToAwake;
28410 end;
28411 end;
28412
28413 constructor TKraftConstraintJointSlider.Create(const APhysics:TKraft;
28414 const ARigidBodyA,ARigidBodyB:TKraftRigidBody;
28415 const AWorldAnchorPoint:TKraftVector3;
28416 const AWorldSliderAxis:TKraftVector3;
28417 const ALimitEnabled:boolean=false;
28418 const AMotorEnabled:boolean=false;
28419 const AMinimumTranslationLimit:TKraftScalar=-1.0;
28420 const AMaximumTranslationLimit:TKraftScalar=1.0;
28421 const AMotorSpeed:TKraftScalar=0.0;
28422 const AMaximalMotorForce:TKraftScalar=0.0;
28423 const ACollideConnected:boolean=false);
28424 begin
28425
28426 fLimitState:=ALimitEnabled;
28427
28428 fMotorState:=AMotorEnabled;
28429
28430 fLowerLimit:=AMinimumTranslationLimit;
28431
28432 fUpperLimit:=AMaximumTranslationLimit;
28433
28434 fMotorSpeed:=AMotorSpeed;
28435
28436 fMaximalMotorForce:=AMaximalMotorForce;
28437
28438 fLocalAnchors[0]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyA.fWorldTransform);
28439 fLocalAnchors[1]:=Vector3TermMatrixMulInverted(AWorldAnchorPoint,ARigidBodyB.fWorldTransform);
28440
28441 fSliderAxisBodyA:=Vector3NormEx(Vector3TermMatrixMulTransposedBasis(AWorldSliderAxis,ARigidBodyA.fWorldTransform));
28442
28443 fAccumulatedImpulseLowerLimit:=0.0;
28444 fAccumulatedImpulseUpperLimit:=0.0;
28445 fAccumulatedImpulseMotor:=0.0;
28446 fAccumulatedImpulseTranslation:=Vector2Origin;
28447 fAccumulatedImpulseRotation:=Vector3Origin;
28448
28449 fBiasLowerLimit:=0.0;
28450 fBiasUpperLimit:=0.0;
28451
28452 fInverseInitialOrientationDifference:=QuaternionInverse(QuaternionTermNormalize(QuaternionMul(ARigidBodyB.fSweep.q0,QuaternionInverse(ARigidBodyA.fSweep.q0))));
28453
28454 if ACollideConnected then begin
28455 Include(fFlags,kcfCollideConnected);
28456 end else begin
28457 Exclude(fFlags,kcfCollideConnected);
28458 end;
28459
28460 fRigidBodies[0]:=ARigidBodyA;
28461 fRigidBodies[1]:=ARigidBodyB;
28462
28463 inherited Create(APhysics);
28464
28465 end;
28466
28467 destructor TKraftConstraintJointSlider.Destroy;
28468 begin
28469 inherited Destroy;
28470 end;
28471
28472 procedure TKraftConstraintJointSlider.InitializeConstraintsAndWarmStart(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
28473 var cA,vA,wA,cB,vB,wB:PKraftVector3;
28474 qA,qB:PKraftQuaternion;
28475 uDotSliderAxis,LowerLimitError,UpperLimitError,InverseMassOfBodies,ImpulseLimits,BiasFactor:TKraftScalar;
28476 TranslationKMatrix:TKraftMatrix2x2;
28477 OldIsLowerLimitViolated,OldIsUpperLimitViolated:boolean;
28478 u,R1PlusU,I1R1PlusUCrossN1,I1R1PlusUCrossN2,I2R2CrossN1,I2R2CrossN2,
28479 LinearImpulseLimits,ImpulseMotor,LinearImpulse,AngularImpulseA,AngularImpulseB:TKraftVector3;
28480 CurrentOrientationDifference,qError:TKraftQuaternion;
28481 begin
28482
28483 fIslandIndices[0]:=fRigidBodies[0].fIslandIndices[Island.fIslandIndex];
28484 fIslandIndices[1]:=fRigidBodies[1].fIslandIndices[Island.fIslandIndex];
28485
28486 fLocalCenters[0]:=fRigidBodies[0].fSweep.LocalCenter;
28487 fLocalCenters[1]:=fRigidBodies[1].fSweep.LocalCenter;
28488
28489 fInverseMasses[0]:=fRigidBodies[0].fInverseMass;
28490 fInverseMasses[1]:=fRigidBodies[1].fInverseMass;
28491
28492 fWorldInverseInertiaTensors[0]:=fRigidBodies[0].fWorldInverseInertiaTensor;
28493 fWorldInverseInertiaTensors[1]:=fRigidBodies[1].fWorldInverseInertiaTensor;
28494
28495 fSolverVelocities[0]:[email protected][fIslandIndices[0]];
28496 fSolverVelocities[1]:[email protected][fIslandIndices[1]];
28497
28498 fSolverPositions[0]:[email protected][fIslandIndices[0]];
28499 fSolverPositions[1]:[email protected][fIslandIndices[1]];
28500
28501 fSolverLinearFactors[0]:[email protected][fIslandIndices[0]];
28502 fSolverLinearFactors[1]:[email protected][fIslandIndices[1]];
28503
28504 cA:=@fSolverPositions[0]^.Position;
28505 qA:=@fSolverPositions[0]^.Orientation;
28506 vA:=@fSolverVelocities[0]^.LinearVelocity;
28507 wA:=@fSolverVelocities[0]^.AngularVelocity;
28508
28509 cB:=@fSolverPositions[1]^.Position;
28510 qB:=@fSolverPositions[1]^.Orientation;
28511 vB:=@fSolverVelocities[1]^.LinearVelocity;
28512 wB:=@fSolverVelocities[1]^.AngularVelocity;
28513
28514 fRelativePositions[0]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
28515 fRelativePositions[1]:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
28516 u:=Vector3Sub(Vector3Add(cB^,fRelativePositions[1]),Vector3Add(cA^,fRelativePositions[0]));
28517
28518 fSliderAxisWorld:=Vector3NormEx(Vector3TermQuaternionRotate(fSliderAxisBodyA,qA^));
28519
28520 fN1:=Vector3GetOneUnitOrthogonalVector(fSliderAxisWorld);
28521 fN2:=Vector3Cross(fSliderAxisWorld,fN1);
28522
28523 uDotSliderAxis:=Vector3Dot(u,fSliderAxisWorld);
28524
28525 LowerLimitError:=uDotSliderAxis-fLowerLimit;
28526 UpperLimitError:=fUpperLimit-uDotSliderAxis;
28527 OldIsLowerLimitViolated:=fIsLowerLimitViolated;
28528 fIsLowerLimitViolated:=LowerLimitError<=0.0;
28529 if fIsLowerLimitViolated<>OldIsLowerLimitViolated then begin
28530 fAccumulatedImpulseLowerLimit:=0.0;
28531 end;
28532 OldIsUpperLimitViolated:=fIsUpperLimitViolated;
28533 fIsUpperLimitViolated:=UpperLimitError<=0.0;
28534 if fIsUpperLimitViolated<>OldIsUpperLimitViolated then begin
28535 fAccumulatedImpulseUpperLimit:=0.0;
28536 end;
28537
28538 fR2CrossN1:=Vector3Cross(fRelativePositions[1],fN1);
28539 fR2CrossN2:=Vector3Cross(fRelativePositions[1],fN2);
28540 fR2CrossSliderAxis:=Vector3Cross(fRelativePositions[1],fSliderAxisWorld);
28541 R1PlusU:=Vector3Cross(fRelativePositions[0],u);
28542 fR1PlusUCrossN1:=Vector3Cross(R1PlusU,fN1);
28543 fR1PlusUCrossN2:=Vector3Cross(R1PlusU,fN2);
28544 fR1PlusUCrossSliderAxis:=Vector3Cross(R1PlusU,fSliderAxisWorld);
28545
28546 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
28547
28548 I1R1PlusUCrossN1:=Vector3TermMatrixMul(fR1PlusUCrossN1,fWorldInverseInertiaTensors[0]);
28549 I1R1PlusUCrossN2:=Vector3TermMatrixMul(fR1PlusUCrossN2,fWorldInverseInertiaTensors[0]);
28550 I2R2CrossN1:=Vector3TermMatrixMul(fR2CrossN1,fWorldInverseInertiaTensors[1]);
28551 I2R2CrossN2:=Vector3TermMatrixMul(fR2CrossN2,fWorldInverseInertiaTensors[1]);
28552 TranslationKMatrix[0,0]:=InverseMassOfBodies+Vector3Dot(fR1PlusUCrossN1,I1R1PlusUCrossN1)+Vector3Dot(fR2CrossN1,I2R2CrossN1);
28553 TranslationKMatrix[0,1]:=Vector3Dot(fR1PlusUCrossN1,I1R1PlusUCrossN2)+Vector3Dot(fR2CrossN1,I2R2CrossN2);
28554 TranslationKMatrix[1,0]:=Vector3Dot(fR1PlusUCrossN2,I1R1PlusUCrossN1)+Vector3Dot(fR2CrossN2,I2R2CrossN1);
28555 TranslationKMatrix[1,1]:=InverseMassOfBodies+Vector3Dot(fR1PlusUCrossN2,I1R1PlusUCrossN2)+Vector3Dot(fR2CrossN2,I2R2CrossN2);
28556 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
28557 Matrix2x2Inverse(fInverseMassMatrixTranslationConstraint,TranslationKMatrix);
28558 fInverseMassMatrixRotationConstraint:=Matrix3x3TermInverse(Matrix3x3TermAdd(fWorldInverseInertiaTensors[0],fWorldInverseInertiaTensors[1]));
28559 end else begin
28560 fInverseMassMatrixTranslationConstraint:=Matrix2x2Null;
28561 fInverseMassMatrixRotationConstraint:=Matrix3x3Null;
28562 end;
28563
28564 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
28565
28566 BiasFactor:=0.0;
28567
28568 fBiasTranslation:=Vector2Origin;
28569
28570 fBiasRotation:=Vector3Origin;
28571
28572 end else begin
28573
28574 BiasFactor:=fPhysics.fConstraintBaumgarte/TimeStep.DeltaTime;
28575
28576 fBiasTranslation:=Vector2ScalarMul(Vector2(Vector3Dot(u,fN1),Vector3Dot(u,fN2)),BiasFactor);
28577
28578 CurrentOrientationDifference:=QuaternionTermNormalize(QuaternionMul(qB^,QuaternionInverse(qA^)));
28579 qError:=QuaternionMul(CurrentOrientationDifference,fInverseInitialOrientationDifference);
28580 fBiasRotation:=Vector3ScalarMul(Vector3(qError.x,qError.y,qError.z),BiasFactor*2.0);
28581
28582 end;
28583
28584 if fLimitState and (fIsLowerLimitViolated or fIsUpperLimitViolated) then begin
28585 // Compute the inverse of the mass matrix K=JM^-1J^t for the limits (1x1 matrix)
28586 fInverseMassMatrixLimit:=InverseMassOfBodies+
28587 Vector3Dot(fR1PlusUCrossSliderAxis,Vector3TermMatrixMul(fR1PlusUCrossSliderAxis,fWorldInverseInertiaTensors[0]))+
28588 Vector3Dot(fR2CrossSliderAxis,Vector3TermMatrixMul(fR2CrossSliderAxis,fWorldInverseInertiaTensors[1]));
28589 if fInverseMassMatrixLimit>0.0 then begin
28590 fInverseMassMatrixLimit:=1.0/fInverseMassMatrixLimit;
28591 end else begin
28592 fInverseMassMatrixLimit:=0.0;
28593 end;
28594 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
28595 fBiasLowerLimit:=0.0;
28596 fBiasUpperLimit:=0.0;
28597 end else begin
28598 fBiasLowerLimit:=LowerLimitError*BiasFactor;
28599 fBiasUpperLimit:=UpperLimitError*BiasFactor;
28600 end;
28601 end;
28602
28603 if fMotorState then begin
28604 // Compute the inverse of the mass matrix K=JM^-1J^t for the motor (1x1 matrix)
28605 fInverseMassMatrixMotor:=InverseMassOfBodies;
28606 if fInverseMassMatrixMotor>0.0 then begin
28607 fInverseMassMatrixMotor:=1.0/fInverseMassMatrixMotor;
28608 end else begin
28609 fInverseMassMatrixMotor:=0.0;
28610 end;
28611 end;
28612
28613 if fPhysics.fWarmStarting then begin
28614
28615 // Compute the impulse P=J^T * lambda for the lower and upper limits constraints of body A
28616 ImpulseLimits:=fAccumulatedImpulseLowerLimit-fAccumulatedImpulseUpperLimit;
28617 LinearImpulseLimits:=Vector3ScalarMul(fSliderAxisWorld,ImpulseLimits);
28618
28619 // Compute the impulse P=J^T * lambda for the motor constraint of body 1
28620 ImpulseMotor:=Vector3ScalarMul(fSliderAxisWorld,-fAccumulatedImpulseMotor);
28621
28622 // Compute the linear impulse P=J^T * lambda for the 2 translation constraints for bodies A and B
28623 LinearImpulse:=Vector3ScalarMul(Vector3Add(Vector3Add(Vector3ScalarMul(fN1,fAccumulatedImpulseTranslation.x),
28624 Vector3ScalarMul(fN2,fAccumulatedImpulseTranslation.y)),
28625 Vector3Add(LinearImpulseLimits,ImpulseMotor)),TimeStep.DeltaTimeRatio);
28626
28627 // Compute the angular impulse P=J^T * lambda for the 2 translation constraints for body A
28628 AngularImpulseA:=Vector3ScalarMul(Vector3Add(Vector3Add(Vector3ScalarMul(fR1PlusUCrossN1,fAccumulatedImpulseTranslation.x),
28629 Vector3ScalarMul(fR1PlusUCrossN2,fAccumulatedImpulseTranslation.y)),
28630 Vector3Add(Vector3ScalarMul(fR1PlusUCrossSliderAxis,ImpulseLimits),
28631 fAccumulatedImpulseRotation)),TimeStep.DeltaTimeRatio);
28632
28633 // Compute the angular impulse P=J^T * lambda for the 2 translation constraints for body B
28634 AngularImpulseB:=Vector3ScalarMul(Vector3Add(Vector3Add(Vector3ScalarMul(fR2CrossN1,fAccumulatedImpulseTranslation.x),
28635 Vector3ScalarMul(fR2CrossN2,fAccumulatedImpulseTranslation.y)),
28636 Vector3Add(Vector3ScalarMul(fR2CrossSliderAxis,ImpulseLimits),
28637 fAccumulatedImpulseRotation)),TimeStep.DeltaTimeRatio);
28638
28639 // Apply impulses
28640 Vector3DirectSub(vA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28641 Vector3DirectSub(wA^,Vector3TermMatrixMul(AngularImpulseA,fWorldInverseInertiaTensors[0]));
28642
28643 Vector3DirectAdd(vB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28644 Vector3DirectAdd(wB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]));
28645
28646 end else begin
28647
28648 fAccumulatedImpulseTranslation:=Vector2Origin;
28649 fAccumulatedImpulseRotation:=Vector3Origin;
28650 fAccumulatedImpulseLowerLimit:=0.0;
28651 fAccumulatedImpulseUpperLimit:=0.0;
28652 fAccumulatedImpulseMotor:=0.0;
28653
28654 end;
28655
28656 end;
28657
28658 procedure TKraftConstraintJointSlider.SolveVelocityConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep);
28659 var vA,wA,vB,wB:PKraftVector3;
28660 LinearImpulse,AngularImpulseA,AngularImpulseB,JvRotation,RotationImpulse:TKraftVector3;
28661 JvTranslation,TranslationImpulse:TKraftVector2;
28662 JvLowerLimit,ImpulseLower,JvUpperLimit,ImpulseUpper,JvMotor,ImpulseMotor,LambdaTemp,MaximalMotorImpulse:TKraftScalar;
28663 begin
28664
28665 vA:=@fSolverVelocities[0]^.LinearVelocity;
28666 wA:=@fSolverVelocities[0]^.AngularVelocity;
28667
28668 vB:=@fSolverVelocities[1]^.LinearVelocity;
28669 wB:=@fSolverVelocities[1]^.AngularVelocity;
28670
28671 (**** Translation ****)
28672
28673 // Compute J*v for the 2 translation constraints
28674 JvTranslation.x:=((Vector3Dot(fN1,vB^)+Vector3Dot(wB^,fR2CrossN1))-(Vector3Dot(fN1,vA^)+Vector3Dot(wA^,fR1PlusUCrossN1)))+fBiasTranslation.x;
28675 JvTranslation.y:=((Vector3Dot(fN2,vB^)+Vector3Dot(wB^,fR2CrossN2))-(Vector3Dot(fN2,vA^)+Vector3Dot(wA^,fR1PlusUCrossN2)))+fBiasTranslation.y;
28676
28677 TranslationImpulse.x:=-((JvTranslation.x*fInverseMassMatrixTranslationConstraint[0,0])+(JvTranslation.y*fInverseMassMatrixTranslationConstraint[0,1]));
28678 TranslationImpulse.y:=-((JvTranslation.x*fInverseMassMatrixTranslationConstraint[1,0])+(JvTranslation.y*fInverseMassMatrixTranslationConstraint[1,1]));
28679
28680 fAccumulatedImpulseTranslation.x:=fAccumulatedImpulseTranslation.x+TranslationImpulse.x;
28681 fAccumulatedImpulseTranslation.y:=fAccumulatedImpulseTranslation.y+TranslationImpulse.y;
28682
28683 LinearImpulse:=Vector3Add(Vector3ScalarMul(fN1,TranslationImpulse.x),
28684 Vector3ScalarMul(fN2,TranslationImpulse.y));
28685
28686 AngularImpulseA:=Vector3Add(Vector3ScalarMul(fR1PlusUCrossN1,TranslationImpulse.x),
28687 Vector3ScalarMul(fR1PlusUCrossN2,TranslationImpulse.y));
28688
28689 AngularImpulseB:=Vector3Add(Vector3ScalarMul(fR2CrossN1,TranslationImpulse.x),
28690 Vector3ScalarMul(fR2CrossN2,TranslationImpulse.y));
28691
28692 Vector3DirectSub(vA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28693 Vector3DirectSub(wA^,Vector3TermMatrixMul(AngularImpulseA,fWorldInverseInertiaTensors[0]));
28694
28695 Vector3DirectAdd(vB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28696 Vector3DirectAdd(wB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]));
28697
28698 (**** Rotation ****)
28699
28700 JvRotation:=Vector3Sub(wB^,wA^);
28701
28702 RotationImpulse:=Vector3TermMatrixMul(Vector3Sub(Vector3Neg(JvRotation),fBiasRotation),fInverseMassMatrixRotationConstraint);
28703
28704 Vector3DirectAdd(fAccumulatedImpulseRotation,RotationImpulse);
28705
28706 Vector3DirectSub(wA^,Vector3TermMatrixMul(RotationImpulse,fWorldInverseInertiaTensors[0]));
28707
28708 Vector3DirectAdd(wB^,Vector3TermMatrixMul(RotationImpulse,fWorldInverseInertiaTensors[1]));
28709
28710 (**** Limits ****)
28711
28712 if fLimitState then begin
28713 if fIsLowerLimitViolated then begin
28714 JvLowerLimit:=(Vector3Dot(fSliderAxisWorld,vB^)+Vector3Dot(fR2CrossSliderAxis,wB^))-(Vector3Dot(fSliderAxisWorld,vA^)+Vector3Dot(fR1PlusUCrossSliderAxis,wA^));
28715 ImpulseLower:=fInverseMassMatrixLimit*(-(JvLowerLimit+fBiasLowerLimit));
28716 LambdaTemp:=fAccumulatedImpulseLowerLimit;
28717 fAccumulatedImpulseLowerLimit:=Max(0.0,fAccumulatedImpulseLowerLimit+ImpulseLower);
28718 ImpulseLower:=fAccumulatedImpulseLowerLimit-LambdaTemp;
28719 LinearImpulse:=Vector3ScalarMul(fSliderAxisWorld,ImpulseLower);
28720 AngularImpulseA:=Vector3ScalarMul(fR1PlusUCrossSliderAxis,ImpulseLower);
28721 AngularImpulseB:=Vector3ScalarMul(fR2CrossSliderAxis,ImpulseLower);
28722 Vector3DirectSub(vA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28723 Vector3DirectSub(wA^,Vector3TermMatrixMul(AngularImpulseA,fWorldInverseInertiaTensors[0]));
28724 Vector3DirectAdd(vB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28725 Vector3DirectAdd(wB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]));
28726 end;
28727 if fIsUpperLimitViolated then begin
28728 JvUpperLimit:=(Vector3Dot(fSliderAxisWorld,vA^)+Vector3Dot(fR1PlusUCrossSliderAxis,wA^))-(Vector3Dot(fSliderAxisWorld,vB^)+Vector3Dot(fR2CrossSliderAxis,wB^));
28729 ImpulseUpper:=fInverseMassMatrixLimit*(-(JvUpperLimit+fBiasUpperLimit));
28730 LambdaTemp:=fAccumulatedImpulseUpperLimit;
28731 fAccumulatedImpulseUpperLimit:=Max(0.0,fAccumulatedImpulseUpperLimit+ImpulseUpper);
28732 ImpulseUpper:=-(fAccumulatedImpulseUpperLimit-LambdaTemp);
28733 LinearImpulse:=Vector3ScalarMul(fSliderAxisWorld,ImpulseUpper);
28734 AngularImpulseA:=Vector3ScalarMul(fR1PlusUCrossSliderAxis,ImpulseUpper);
28735 AngularImpulseB:=Vector3ScalarMul(fR2CrossSliderAxis,ImpulseUpper);
28736 Vector3DirectSub(vA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28737 Vector3DirectSub(wA^,Vector3TermMatrixMul(AngularImpulseA,fWorldInverseInertiaTensors[0]));
28738 Vector3DirectAdd(vB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28739 Vector3DirectAdd(wB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]));
28740 end;
28741 end;
28742
28743 (**** Motor ****)
28744
28745 if fMotorState then begin
28746 JvMotor:=Vector3Dot(fSliderAxisWorld,vA^)-Vector3Dot(fSliderAxisWorld,vB^);
28747 ImpulseMotor:=fInverseMassMatrixMotor*(-JvMotor);
28748 LambdaTemp:=fAccumulatedImpulseMotor;
28749 MaximalMotorImpulse:=fMaximalMotorForce*TimeStep.DeltaTime;
28750 fAccumulatedImpulseMotor:=Min(Max(fAccumulatedImpulseMotor+ImpulseMotor,-MaximalMotorImpulse),MaximalMotorImpulse);
28751 ImpulseMotor:=-(fAccumulatedImpulseMotor-LambdaTemp);
28752 LinearImpulse:=Vector3ScalarMul(fSliderAxisWorld,ImpulseMotor);
28753 Vector3DirectSub(wA^,Vector3TermMatrixMul(LinearImpulse,fWorldInverseInertiaTensors[0]));
28754 Vector3DirectAdd(wB^,Vector3TermMatrixMul(LinearImpulse,fWorldInverseInertiaTensors[1]));
28755 end;
28756
28757 end;
28758
28759 function TKraftConstraintJointSlider.SolvePositionConstraint(const Island:TKraftIsland;const TimeStep:TKraftTimeStep):boolean;
28760 var cA,cB:PKraftVector3;
28761 qA,qB:PKraftQuaternion;
28762 rA,rB,u,R1PlusU,I1R1PlusUCrossN1,I1R1PlusUCrossN2,I2R2CrossN1,I2R2CrossN2,
28763 LinearImpulse,AngularImpulseA,AngularImpulseB,RotationError,RotationImpulse:TKraftVector3;
28764 TranslationError,TranslationImpulse:TKraftVector2;
28765 uDotSliderAxis,InverseMassOfBodies,LowerLimitError,UpperLimitError,ImpulseLower,ImpulseUpper:TKraftScalar;
28766 TranslationKMatrix:TKraftMatrix2x2;
28767 CurrentOrientationDifference,qError:TKraftQuaternion;
28768 begin
28769
28770 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
28771
28772 cA:=@fSolverPositions[0]^.Position;
28773 qA:=@fSolverPositions[0]^.Orientation;
28774
28775 cB:=@fSolverPositions[1]^.Position;
28776 qB:=@fSolverPositions[1]^.Orientation;
28777
28778 rA:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),qA^);
28779 rB:=Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),qB^);
28780
28781 u:=Vector3Sub(Vector3Add(cB^,rB),Vector3Add(cA^,rA));
28782
28783 fSliderAxisWorld:=Vector3NormEx(Vector3TermQuaternionRotate(fSliderAxisBodyA,qA^));
28784
28785 fN1:=Vector3GetOneUnitOrthogonalVector(fSliderAxisWorld);
28786 fN2:=Vector3Cross(fSliderAxisWorld,fN1);
28787
28788 uDotSliderAxis:=Vector3Dot(u,fSliderAxisWorld);
28789
28790 LowerLimitError:=uDotSliderAxis-fLowerLimit;
28791 UpperLimitError:=fUpperLimit-uDotSliderAxis;
28792 fIsLowerLimitViolated:=LowerLimitError<=0.0;
28793 fIsUpperLimitViolated:=UpperLimitError<=0.0;
28794
28795 fR2CrossN1:=Vector3Cross(fRelativePositions[1],fN1);
28796 fR2CrossN2:=Vector3Cross(fRelativePositions[1],fN2);
28797 fR2CrossSliderAxis:=Vector3Cross(fRelativePositions[1],fSliderAxisWorld);
28798 R1PlusU:=Vector3Cross(fRelativePositions[0],u);
28799 fR1PlusUCrossN1:=Vector3Cross(R1PlusU,fN1);
28800 fR1PlusUCrossN2:=Vector3Cross(R1PlusU,fN2);
28801 fR1PlusUCrossSliderAxis:=Vector3Cross(R1PlusU,fSliderAxisWorld);
28802
28803 (**** Translation ****)
28804
28805 InverseMassOfBodies:=fRigidBodies[0].fInverseMass+fRigidBodies[1].fInverseMass;
28806
28807 I1R1PlusUCrossN1:=Vector3TermMatrixMul(fR1PlusUCrossN1,fWorldInverseInertiaTensors[0]);
28808 I1R1PlusUCrossN2:=Vector3TermMatrixMul(fR1PlusUCrossN2,fWorldInverseInertiaTensors[0]);
28809 I2R2CrossN1:=Vector3TermMatrixMul(fR2CrossN1,fWorldInverseInertiaTensors[1]);
28810 I2R2CrossN2:=Vector3TermMatrixMul(fR2CrossN2,fWorldInverseInertiaTensors[1]);
28811 TranslationKMatrix[0,0]:=InverseMassOfBodies+Vector3Dot(fR1PlusUCrossN1,I1R1PlusUCrossN1)+Vector3Dot(fR2CrossN1,I2R2CrossN1);
28812 TranslationKMatrix[0,1]:=Vector3Dot(fR1PlusUCrossN1,I1R1PlusUCrossN2)+Vector3Dot(fR2CrossN1,I2R2CrossN2);
28813 TranslationKMatrix[1,0]:=Vector3Dot(fR1PlusUCrossN2,I1R1PlusUCrossN1)+Vector3Dot(fR2CrossN2,I2R2CrossN1);
28814 TranslationKMatrix[1,1]:=InverseMassOfBodies+Vector3Dot(fR1PlusUCrossN2,I1R1PlusUCrossN2)+Vector3Dot(fR2CrossN2,I2R2CrossN2);
28815 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
28816 Matrix2x2Inverse(fInverseMassMatrixTranslationConstraint,TranslationKMatrix);
28817 end else begin
28818 fInverseMassMatrixRotationConstraint:=Matrix3x3Null;
28819 end;
28820
28821 TranslationError.x:=Vector3Dot(u,fN1);
28822 TranslationError.y:=Vector3Dot(u,fN2);
28823
28824 TranslationImpulse.x:=-((TranslationError.x*fInverseMassMatrixTranslationConstraint[0,0])+(TranslationError.y*fInverseMassMatrixTranslationConstraint[0,1]));
28825 TranslationImpulse.y:=-((TranslationError.x*fInverseMassMatrixTranslationConstraint[1,0])+(TranslationError.y*fInverseMassMatrixTranslationConstraint[1,1]));
28826
28827 LinearImpulse:=Vector3Add(Vector3ScalarMul(fN1,TranslationImpulse.x),
28828 Vector3ScalarMul(fN2,TranslationImpulse.y));
28829
28830 AngularImpulseA:=Vector3Add(Vector3ScalarMul(fR1PlusUCrossN1,TranslationImpulse.x),
28831 Vector3ScalarMul(fR1PlusUCrossN2,TranslationImpulse.y));
28832
28833 AngularImpulseB:=Vector3Add(Vector3ScalarMul(fR2CrossN1,TranslationImpulse.x),
28834 Vector3ScalarMul(fR2CrossN2,TranslationImpulse.y));
28835
28836 result:=Vector2Length(TranslationError)<fPhysics.fLinearSlop;
28837
28838 Vector3DirectSub(cA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28839 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(AngularImpulseA),fWorldInverseInertiaTensors[0]),1.0);
28840
28841 Vector3DirectAdd(cB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28842 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]),1.0);
28843
28844 (**** Rotation ****)
28845
28846 if (fRigidBodies[0].fRigidBodyType=krbtDynamic) or (fRigidBodies[1].fRigidBodyType=krbtDynamic) then begin
28847 fInverseMassMatrixRotationConstraint:=Matrix3x3TermInverse(Matrix3x3TermAdd(fWorldInverseInertiaTensors[0],fWorldInverseInertiaTensors[1]));
28848 end else begin
28849 fInverseMassMatrixRotationConstraint:=Matrix3x3Null;
28850 end;
28851
28852 CurrentOrientationDifference:=QuaternionTermNormalize(QuaternionMul(qB^,QuaternionInverse(qA^)));
28853 qError:=QuaternionMul(CurrentOrientationDifference,fInverseInitialOrientationDifference);
28854 RotationError.x:=qError.x*2.0;
28855 RotationError.y:=qError.y*2.0;
28856 RotationError.z:=qError.z*2.0;
28857
28858 RotationImpulse:=Vector3TermMatrixMul(Vector3Neg(RotationError),fInverseMassMatrixRotationConstraint);
28859
28860 result:=result and (Vector3Length(RotationError)<fPhysics.fAngularSlop);
28861
28862 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(RotationImpulse),fWorldInverseInertiaTensors[0]),1.0);
28863
28864 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(RotationImpulse,fWorldInverseInertiaTensors[1]),1.0);
28865
28866 (**** Limits ****)
28867
28868 if fLimitState then begin
28869 if fIsLowerLimitViolated or fIsUpperLimitViolated then begin
28870 fInverseMassMatrixLimit:=InverseMassOfBodies+
28871 Vector3Dot(fR1PlusUCrossSliderAxis,Vector3TermMatrixMul(fR1PlusUCrossSliderAxis,fWorldInverseInertiaTensors[0]))+
28872 Vector3Dot(fR2CrossSliderAxis,Vector3TermMatrixMul(fR2CrossSliderAxis,fWorldInverseInertiaTensors[1]));
28873 if fInverseMassMatrixLimit>0.0 then begin
28874 fInverseMassMatrixLimit:=1.0/fInverseMassMatrixLimit;
28875 end else begin
28876 fInverseMassMatrixLimit:=0.0;
28877 end;
28878 end;
28879 if fIsLowerLimitViolated then begin
28880 ImpulseLower:=fInverseMassMatrixLimit*(-LowerLimitError);
28881 LinearImpulse:=Vector3ScalarMul(fSliderAxisWorld,ImpulseLower);
28882 AngularImpulseA:=Vector3ScalarMul(fR1PlusUCrossSliderAxis,ImpulseLower);
28883 AngularImpulseB:=Vector3ScalarMul(fR2CrossSliderAxis,ImpulseLower);
28884 result:=result and (LowerLimitError<fPhysics.fLinearSlop);
28885 Vector3DirectSub(cA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28886 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(AngularImpulseA),fWorldInverseInertiaTensors[0]),1.0);
28887 Vector3DirectAdd(cB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28888 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]),1.0);
28889 end;
28890 if fIsUpperLimitViolated then begin
28891 ImpulseUpper:=-(fInverseMassMatrixLimit*(-UpperLimitError));
28892 LinearImpulse:=Vector3ScalarMul(fSliderAxisWorld,ImpulseUpper);
28893 AngularImpulseA:=Vector3ScalarMul(fR1PlusUCrossSliderAxis,ImpulseUpper);
28894 AngularImpulseB:=Vector3ScalarMul(fR2CrossSliderAxis,ImpulseUpper);
28895 result:=result and (UpperLimitError<fPhysics.fLinearSlop);
28896 Vector3DirectSub(cA^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[0]^,fInverseMasses[0])));
28897 QuaternionDirectSpin(qA^,Vector3TermMatrixMul(Vector3Neg(AngularImpulseA),fWorldInverseInertiaTensors[0]),1.0);
28898 Vector3DirectAdd(cB^,Vector3Mul(LinearImpulse,Vector3ScalarMul(fSolverLinearFactors[1]^,fInverseMasses[1])));
28899 QuaternionDirectSpin(qB^,Vector3TermMatrixMul(AngularImpulseB,fWorldInverseInertiaTensors[1]),1.0);
28900 end;
28901 end;
28902
28903 end else begin
28904
28905 result:=true;
28906
28907 end;
28908
28909 end;
28910
28911 function TKraftConstraintJointSlider.GetAnchorA:TKraftVector3;
28912 begin
28913 result:=Vector3TermMatrixMul(fLocalAnchors[0],fRigidBodies[0].fWorldTransform);
28914 end;
28915
28916 function TKraftConstraintJointSlider.GetAnchorB:TKraftVector3;
28917 begin
28918 result:=Vector3TermMatrixMul(fLocalAnchors[1],fRigidBodies[1].fWorldTransform);
28919 end;
28920
28921 function TKraftConstraintJointSlider.GetReactionForce(const InverseDeltaTime:TKraftScalar):TKraftVector3;
28922 begin
28923 result:=Vector3ScalarMul(Vector3Add(Vector3ScalarMul(fN1,fAccumulatedImpulseTranslation.x),
28924 Vector3ScalarMul(fN2,fAccumulatedImpulseTranslation.y)),InverseDeltaTime);
28925 end;
28926
28927 function TKraftConstraintJointSlider.GetReactionTorque(const InverseDeltaTime:TKraftScalar):TKraftVector3;
28928 begin
28929 result:=Vector3ScalarMul(fAccumulatedImpulseRotation,InverseDeltaTime);
28930 end;
28931
28932 function TKraftConstraintJointSlider.IsLimitEnabled:boolean;
28933 begin
28934 result:=fLimitState;
28935 end;
28936
28937 function TKraftConstraintJointSlider.IsMotorEnabled:boolean;
28938 begin
28939 result:=fMotorState;
28940 end;
28941
28942 function TKraftConstraintJointSlider.GetMinimumTranslationLimit:TKraftScalar;
28943 begin
28944 result:=fLowerLimit;
28945 end;
28946
28947 function TKraftConstraintJointSlider.GetMaximumTranslationLimit:TKraftScalar;
28948 begin
28949 result:=fUpperLimit;
28950 end;
28951
28952 function TKraftConstraintJointSlider.GetMotorSpeed:TKraftScalar;
28953 begin
28954 result:=fMotorSpeed;
28955 end;
28956
28957 function TKraftConstraintJointSlider.GetMaximalMotorForce:TKraftScalar;
28958 begin
28959 result:=fMaximalMotorForce;
28960 end;
28961
28962 function TKraftConstraintJointSlider.GetMotorForce(const DeltaTime:TKraftScalar):TKraftScalar;
28963 begin
28964 result:=fAccumulatedImpulseMotor/DeltaTime;
28965 end;
28966
28967 function TKraftConstraintJointSlider.GetTranslation:TKraftScalar;
28968 begin
28969 result:=Vector3Dot(Vector3Sub(Vector3Add(fSolverPositions[1]^.Position,Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[1],fLocalCenters[1]),fSolverPositions[1]^.Orientation)),
28970 Vector3Add(fSolverPositions[0]^.Position,Vector3TermQuaternionRotate(Vector3Sub(fLocalAnchors[0],fLocalCenters[0]),fSolverPositions[0]^.Orientation))),
28971 Vector3TermQuaternionRotate(fSliderAxisBodyA,fSolverPositions[0]^.Orientation));
28972 end;
28973
28974 procedure TKraftConstraintJointSlider.ResetLimits;
28975 begin
28976 fAccumulatedImpulseLowerLimit:=0.0;
28977 fAccumulatedImpulseUpperLimit:=0.0;
28978 fRigidBodies[0].SetToAwake;
28979 fRigidBodies[1].SetToAwake;
28980 end;
28981
28982 procedure TKraftConstraintJointSlider.EnableLimit(const ALimitEnabled:boolean);
28983 begin
28984 if fLimitState<>ALimitEnabled then begin
28985 fLimitState:=ALimitEnabled;
28986 ResetLimits;
28987 end;
28988 end;
28989
28990 procedure TKraftConstraintJointSlider.EnableMotor(const AMotorEnabled:boolean);
28991 begin
28992 if fMotorState<>AMotorEnabled then begin
28993 fMotorState:=AMotorEnabled;
28994 fAccumulatedImpulseMotor:=0.0;
28995 fRigidBodies[0].SetToAwake;
28996 fRigidBodies[1].SetToAwake;
28997 end;
28998 end;
28999
29000 procedure TKraftConstraintJointSlider.SetMinimumTranslationLimit(const AMinimumTranslationLimit:TKraftScalar);
29001 begin
29002 if fLowerLimit<>AMinimumTranslationLimit then begin
29003 fLowerLimit:=AMinimumTranslationLimit;
29004 ResetLimits;
29005 end;
29006 end;
29007
29008 procedure TKraftConstraintJointSlider.SetMaximumTranslationLimit(const AMaximumTranslationLimit:TKraftScalar);
29009 begin
29010 if fUpperLimit<>AMaximumTranslationLimit then begin
29011 fUpperLimit:=AMaximumTranslationLimit;
29012 ResetLimits;
29013 end;
29014 end;
29015
29016 procedure TKraftConstraintJointSlider.SetMotorSpeed(const AMotorSpeed:TKraftScalar);
29017 begin
29018 if fMotorSpeed<>AMotorSpeed then begin
29019 fMotorSpeed:=AMotorSpeed;
29020 fRigidBodies[0].SetToAwake;
29021 fRigidBodies[1].SetToAwake;
29022 end;
29023 end;
29024
29025 procedure TKraftConstraintJointSlider.SetMaximalMotorForce(const AMaximalMotorForce:TKraftScalar);
29026 begin
29027 if fMaximalMotorForce<>AMaximalMotorForce then begin
29028 fMaximalMotorForce:=AMaximalMotorForce;
29029 fRigidBodies[0].SetToAwake;
29030 fRigidBodies[1].SetToAwake;
29031 end;
29032 end;
29033
29034 constructor TKraftSolver.Create(const APhysics:TKraft;const AIsland:TKraftIsland);
29035 begin
29036 inherited Create;
29037
29038 fPhysics:=APhysics;
29039
29040 fIsland:=AIsland;
29041
29042 fVelocities:=nil;
29043 SetLength(fVelocities,64);
29044 fCountVelocities:=0;
29045
29046 fPositions:=nil;
29047 SetLength(fPositions,64);
29048 fCountPositions:=0;
29049
29050 fLinearFactors:=nil;
29051 SetLength(fLinearFactors,64);
29052 fCountLinearFactors:=0;
29053
29054 fVelocityStates:=nil;
29055 SetLength(fVelocityStates,64);
29056 fCountVelocityStates:=0;
29057
29058 fPositionStates:=nil;
29059 SetLength(fPositionStates,64);
29060 fCountPositionStates:=0;
29061
29062 fSpeculativeContactStates:=nil;
29063 SetLength(fSpeculativeContactStates,64);
29064 fCountSpeculativeContactStates:=0;
29065
29066 fCountContacts:=0;
29067
29068 end;
29069
29070 destructor TKraftSolver.Destroy;
29071 begin
29072 SetLength(fVelocities,0);
29073 SetLength(fPositions,0);
29074 SetLength(fLinearFactors,0);
29075 SetLength(fVelocityStates,0);
29076 SetLength(fPositionStates,0);
29077 SetLength(fSpeculativeContactStates,0);
29078 inherited Destroy;
29079 end;
29080
29081 procedure TKraftSolver.Initialize(const TimeStep:TKraftTimeStep);
29082 begin
29083 fDeltaTime:=TimeStep.DeltaTime;
29084 fDeltaTimeRatio:=TimeStep.DeltaTimeRatio;
29085 fEnableFriction:=fPhysics.fEnableFriction;
29086 fPositionCorrectionMode:=fPhysics.fContactPositionCorrectionMode;
29087 end;
29088
29089 procedure TKraftSolver.Store;
29090 var ContactPairIndex,ContactIndex:longint;
29091 VelocityState:PKraftSolverVelocityState;
29092 PositionState:PKraftSolverPositionState;
29093 ContactPair:PKraftContactPair;
29094 Contact:PKraftContact;
29095 ContactPoint:PKraftSolverVelocityStateContactPoint;
29096 SpeculativeContactState:PKraftSolverSpeculativeContactState;
29097 begin
29098
29099 if fIsland.fCountRigidBodies>length(fVelocities) then begin
29100 SetLength(fVelocities,fIsland.fCountRigidBodies*2);
29101 end;
29102 fCountVelocities:=fIsland.fCountRigidBodies;
29103
29104 if fIsland.fCountRigidBodies>length(fPositions) then begin
29105 SetLength(fPositions,fIsland.fCountRigidBodies*2);
29106 end;
29107 fCountPositions:=fIsland.fCountRigidBodies;
29108
29109 if fIsland.fCountRigidBodies>length(fLinearFactors) then begin
29110 SetLength(fLinearFactors,fIsland.fCountRigidBodies*2);
29111 end;
29112 fCountLinearFactors:=fIsland.fCountRigidBodies;
29113
29114 fCountContacts:=fIsland.fCountContactPairs;
29115
29116 if fCountContacts>length(fVelocityStates) then begin
29117 SetLength(fVelocityStates,fCountContacts*2);
29118 end;
29119 fCountVelocityStates:=fCountContacts;
29120
29121 if fCountContacts>length(fPositionStates) then begin
29122 SetLength(fPositionStates,fCountContacts*2);
29123 end;
29124 fCountPositionStates:=fCountContacts;
29125
29126 fCountSpeculativeContacts:=fIsland.fCountSpeculativeContactPairs;
29127
29128 if fCountSpeculativeContacts>length(fSpeculativeContactStates) then begin
29129 SetLength(fSpeculativeContactStates,fCountSpeculativeContacts*2);
29130 end;
29131 fCountSpeculativeContactStates:=fCountSpeculativeContacts;
29132
29133 for ContactPairIndex:=0 to fCountContacts-1 do begin
29134
29135 ContactPair:=fIsland.fContactPairs[ContactPairIndex];
29136
29137 VelocityState:=@fVelocityStates[ContactPairIndex];
29138 VelocityState^.Centers[0]:=ContactPair^.RigidBodies[0].fSweep.c0;
29139 VelocityState^.Centers[1]:=ContactPair^.RigidBodies[1].fSweep.c0;
29140 VelocityState^.WorldInverseInertiaTensors[0]:=ContactPair^.RigidBodies[0].fWorldInverseInertiaTensor;
29141 VelocityState^.WorldInverseInertiaTensors[1]:=ContactPair^.RigidBodies[1].fWorldInverseInertiaTensor;
29142 VelocityState^.NormalMass:=0.0;
29143 VelocityState^.TangentMass[0]:=0.0;
29144 VelocityState^.TangentMass[1]:=0.0;
29145 VelocityState^.InverseMasses[0]:=ContactPair^.RigidBodies[0].fInverseMass;
29146 VelocityState^.InverseMasses[1]:=ContactPair^.RigidBodies[1].fInverseMass;
29147 VelocityState^.Restitution:=ContactPair^.Restitution;
29148 VelocityState^.Friction:=ContactPair^.Friction;
29149 VelocityState^.Indices[0]:=ContactPair^.RigidBodies[0].fIslandIndices[fIsland.fIslandIndex];
29150 VelocityState^.Indices[1]:=ContactPair^.RigidBodies[1].fIslandIndices[fIsland.fIslandIndex];
29151 VelocityState^.CountPoints:=ContactPair^.Manifold.CountContacts;
29152
29153 PositionState:=@fPositionStates[ContactPairIndex];
29154 PositionState^.LocalNormal:=ContactPair^.Manifold.LocalNormal;
29155 PositionState^.LocalCenters[0]:=ContactPair^.RigidBodies[0].fSweep.LocalCenter;
29156 PositionState^.LocalCenters[1]:=ContactPair^.RigidBodies[1].fSweep.LocalCenter;
29157 PositionState^.WorldInverseInertiaTensors[0]:=ContactPair^.RigidBodies[0].fWorldInverseInertiaTensor;
29158 PositionState^.WorldInverseInertiaTensors[1]:=ContactPair^.RigidBodies[1].fWorldInverseInertiaTensor;
29159 PositionState^.InverseMasses[0]:=ContactPair^.RigidBodies[0].fInverseMass;
29160 PositionState^.InverseMasses[1]:=ContactPair^.RigidBodies[1].fInverseMass;
29161 PositionState^.Indices[0]:=ContactPair^.RigidBodies[0].fIslandIndices[fIsland.fIslandIndex];
29162 PositionState^.Indices[1]:=ContactPair^.RigidBodies[1].fIslandIndices[fIsland.fIslandIndex];
29163 PositionState^.CountPoints:=ContactPair^.Manifold.CountContacts;
29164
29165 VelocityState^.LostSpeculativeBounce:=ContactPair^.Manifold.LostSpeculativeBounce;
29166 ContactPair^.Manifold.LostSpeculativeBounce:=0;
29167
29168 for ContactIndex:=0 to ContactPair^.Manifold.CountContacts-1 do begin
29169
29170 Contact:=@ContactPair^.Manifold.Contacts[ContactIndex];
29171
29172 ContactPoint:=@VelocityState^.Points[ContactIndex];
29173
29174 ContactPoint^.RelativePositions[0]:=Vector3Origin;
29175 ContactPoint^.RelativePositions[1]:=Vector3Origin;
29176 if fPhysics.fWarmStarting then begin
29177 ContactPoint^.NormalImpulse:=Contact^.NormalImpulse*fDeltaTimeRatio;
29178 ContactPoint^.TangentImpulse[0]:=Contact^.TangentImpulse[0]*fDeltaTimeRatio;
29179 ContactPoint^.TangentImpulse[1]:=Contact^.TangentImpulse[1]*fDeltaTimeRatio;
29180 end else begin
29181 ContactPoint^.NormalImpulse:=0.0;
29182 ContactPoint^.TangentImpulse[0]:=0.0;
29183 ContactPoint^.TangentImpulse[1]:=0.0;
29184 end;
29185 ContactPoint^.Bias:=0.0;
29186 ContactPoint^.NormalMass:=0.0;
29187 ContactPoint^.TangentMass[0]:=0.0;
29188 ContactPoint^.TangentMass[1]:=0.0;
29189
29190 PositionState^.LocalPoints[ContactIndex]:=Contact^.LocalPoints[ContactIndex];
29191
29192 end;
29193
29194 end;
29195
29196 for ContactPairIndex:=0 to fCountSpeculativeContacts-1 do begin
29197 ContactPair:=fIsland.fSpeculativeContactPairs[ContactPairIndex];
29198 Contact:=@ContactPair^.Manifold.Contacts[0];
29199 SpeculativeContactState:=@fSpeculativeContactStates[ContactPairIndex];
29200 SpeculativeContactState^.Centers[0]:=ContactPair^.RigidBodies[0].fSweep.c0;
29201 SpeculativeContactState^.Centers[1]:=ContactPair^.RigidBodies[1].fSweep.c0;
29202 SpeculativeContactState^.LocalCenters[0]:=ContactPair^.RigidBodies[0].fSweep.LocalCenter;
29203 SpeculativeContactState^.LocalCenters[1]:=ContactPair^.RigidBodies[1].fSweep.LocalCenter;
29204 SpeculativeContactState^.WorldInverseInertiaTensors[0]:=ContactPair^.RigidBodies[0].fWorldInverseInertiaTensor;
29205 SpeculativeContactState^.WorldInverseInertiaTensors[1]:=ContactPair^.RigidBodies[1].fWorldInverseInertiaTensor;
29206 SpeculativeContactState^.InverseMasses[0]:=ContactPair^.RigidBodies[0].fInverseMass;
29207 SpeculativeContactState^.InverseMasses[1]:=ContactPair^.RigidBodies[1].fInverseMass;
29208 SpeculativeContactState^.Restitution:=ContactPair^.Restitution;
29209 SpeculativeContactState^.Friction:=ContactPair^.Friction;
29210 SpeculativeContactState^.Indices[0]:=ContactPair^.RigidBodies[0].fIslandIndices[fIsland.fIslandIndex];
29211 SpeculativeContactState^.Indices[1]:=ContactPair^.RigidBodies[1].fIslandIndices[fIsland.fIslandIndex];
29212 SpeculativeContactState^.LostSpeculativeBounce:=ContactPair^.Manifold.LostSpeculativeBounce;
29213 SpeculativeContactState^.RelativePositions[0]:=Vector3Origin;
29214 SpeculativeContactState^.RelativePositions[1]:=Vector3Origin;
29215 SpeculativeContactState^.NormalImpulse:=Contact^.NormalImpulse;
29216 SpeculativeContactState^.TangentImpulse[0]:=Contact^.TangentImpulse[0];
29217 SpeculativeContactState^.TangentImpulse[1]:=Contact^.TangentImpulse[1];
29218 SpeculativeContactState^.NormalMass:=0.0;
29219 SpeculativeContactState^.TangentMass[0]:=0.0;
29220 SpeculativeContactState^.TangentMass[1]:=0.0;
29221 end;
29222
29223 end;
29224
29225 procedure TKraftSolver.InitializeConstraints;
29226 var ContactPairIndex,ContactIndex,TangentIndex,IndexA,IndexB:longint;
29227 VelocityState:PKraftSolverVelocityState;
29228 PositionState:PKraftSolverPositionState;
29229 ContactPoint:PKraftSolverVelocityStateContactPoint;
29230 SolverContact:PKraftSolverContact;
29231 iA,iB:PKraftMatrix3x3;
29232 mA,mB,NormalMass,TangentMass,dv,LostSpeculativeBounce,RestitutionBias:TKraftScalar;
29233 LocalCenterA,LocalCenterB,cA,vA,wA,rnA,rtA,cB,vB,wB,rnB,rtB,P,Temp:TKraftVector3;
29234 TangentVectors:array[0..1] of TKraftVector3;
29235 qA,qB:TKraftQuaternion;
29236 tA,tB:TKraftMatrix4x4;
29237 SolverContactManifold:TKraftSolverContactManifold;
29238 //Normal,t0,t1:TKraftVector3;
29239 SpeculativeContactState:PKraftSolverSpeculativeContactState;
29240 begin
29241
29242 TangentVectors[0]:=Vector3Origin;
29243 TangentVectors[1]:=Vector3Origin;
29244
29245 for ContactPairIndex:=0 to fCountContacts-1 do begin
29246
29247 VelocityState:=@fVelocityStates[ContactPairIndex];
29248
29249 PositionState:=@fPositionStates[ContactPairIndex];
29250
29251 IndexA:=VelocityState^.Indices[0];
29252 IndexB:=VelocityState^.Indices[1];
29253
29254 iA:=@VelocityState^.WorldInverseInertiaTensors[0];
29255 iB:=@VelocityState^.WorldInverseInertiaTensors[1];
29256
29257 mA:=VelocityState^.InverseMasses[0];
29258 mB:=VelocityState^.InverseMasses[1];
29259
29260 LocalCenterA:=PositionState^.LocalCenters[0];
29261 LocalCenterB:=PositionState^.LocalCenters[1];
29262
29263 cA:=fPositions[IndexA].Position;
29264 qA:=fPositions[IndexA].Orientation;
29265 tA:=QuaternionToMatrix4x4(qA);
29266 Temp:=Vector3Sub(cA,Vector3TermMatrixMulBasis(LocalCenterA,tA));
29267 PKraftVector3(pointer(@tA[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29268
29269 cB:=fPositions[IndexB].Position;
29270 qB:=fPositions[IndexB].Orientation;
29271 tB:=QuaternionToMatrix4x4(qB);
29272 Temp:=Vector3Sub(cB,Vector3TermMatrixMulBasis(LocalCenterB,tB));
29273 PKraftVector3(pointer(@tB[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29274
29275 vA:=fVelocities[IndexA].LinearVelocity;
29276 wA:=fVelocities[IndexA].AngularVelocity;
29277
29278 vB:=fVelocities[IndexB].LinearVelocity;
29279 wB:=fVelocities[IndexB].AngularVelocity;
29280
29281 if fPositionCorrectionMode=kpcmBaumgarte then begin
29282 fIsland.fContactPairs[ContactPairIndex]^.GetSolverContactManifold(SolverContactManifold,tA,tB,kcpcmmBaumgarte);
29283 end else begin
29284 fIsland.fContactPairs[ContactPairIndex]^.GetSolverContactManifold(SolverContactManifold,tA,tB,kcpcmmVelocitySolver);
29285 end;
29286
29287 VelocityState^.CountPoints:=SolverContactManifold.CountContacts;
29288
29289 VelocityState^.Normal:=SolverContactManifold.Normal;
29290
29291 LostSpeculativeBounce:=VelocityState^.LostSpeculativeBounce/Max(1,SolverContactManifold.CountContacts);
29292
29293 ComputeBasis(VelocityState^.Normal,TangentVectors[0],TangentVectors[1]);
29294
29295 for ContactIndex:=0 to SolverContactManifold.CountContacts-1 do begin
29296
29297 ContactPoint:=@VelocityState^.Points[ContactIndex];
29298
29299 SolverContact:[email protected][ContactIndex];
29300
29301 P:=SolverContact^.Point;
29302 ContactPoint^.RelativePositions[0]:=Vector3Sub(P,cA);
29303 ContactPoint^.RelativePositions[1]:=Vector3Sub(P,cB);
29304
29305 // Precalculate JM^-1JT for contact and friction constraints
29306 rnA:=Vector3Cross(ContactPoint^.RelativePositions[0],VelocityState^.Normal);
29307 rnB:=Vector3Cross(ContactPoint^.RelativePositions[1],VelocityState^.Normal);
29308
29309 NormalMass:=mA+mB+Vector3Dot(rnA,Vector3TermMatrixMul(rnA,iA^))+Vector3Dot(rnB,Vector3TermMatrixMul(rnB,iB^));
29310
29311 if NormalMass>0.0 then begin
29312 ContactPoint^.NormalMass:=1.0/NormalMass;
29313 end else begin
29314 ContactPoint^.NormalMass:=0.0;
29315 end;
29316
29317 for TangentIndex:=0 to 1 do begin
29318 rtA:=Vector3Cross(TangentVectors[TangentIndex],ContactPoint^.RelativePositions[0]);
29319 rtB:=Vector3Cross(TangentVectors[TangentIndex],ContactPoint^.RelativePositions[1]);
29320 TangentMass:=mA+mB+Vector3Dot(rtA,Vector3TermMatrixMul(rtA,iA^))+Vector3Dot(rtB,Vector3TermMatrixMul(rtB,iB^));
29321 if TangentMass>0.0 then begin
29322 ContactPoint^.TangentMass[TangentIndex]:=1.0/TangentMass;
29323 end else begin
29324 ContactPoint^.TangentMass[TangentIndex]:=0.0;
29325 end;
29326 end;
29327
29328 if fPositionCorrectionMode=kpcmBaumgarte then begin
29329 ContactPoint^.BaumgarteBias:=(-fPhysics.fContactBaumgarte)*(1.0/fDeltaTime)*min(0.0,SolverContact^.Separation+fPhysics.fPenetrationSlop);
29330 end else begin
29331 ContactPoint^.BaumgarteBias:=0.0;
29332 end;
29333
29334 ContactPoint^.BaumgarteBias:=ContactPoint^.BaumgarteBias+LostSpeculativeBounce;
29335
29336 dv:=Vector3Dot(Vector3Sub(Vector3Add(vB,
29337 Vector3Cross(wB,
29338 ContactPoint^.RelativePositions[1])),
29339 Vector3Add(vA,
29340 Vector3Cross(wA,
29341 ContactPoint^.RelativePositions[0]))),
29342 VelocityState^.Normal);
29343 if dv<(-fPhysics.fVelocityThreshold) then begin
29344 ContactPoint^.Bias:=ContactPoint^.BaumgarteBias-(VelocityState^.Restitution*dv);
29345 end else begin
29346 ContactPoint^.Bias:=ContactPoint^.BaumgarteBias;
29347 end;
29348
29349 end;
29350
29351 end;
29352
29353 for ContactPairIndex:=0 to fCountSpeculativeContacts-1 do begin
29354
29355 SpeculativeContactState:=@fSpeculativeContactStates[ContactPairIndex];
29356
29357 IndexA:=SpeculativeContactState^.Indices[0];
29358 IndexB:=SpeculativeContactState^.Indices[1];
29359
29360 iA:=@SpeculativeContactState^.WorldInverseInertiaTensors[0];
29361 iB:=@SpeculativeContactState^.WorldInverseInertiaTensors[1];
29362
29363 mA:=SpeculativeContactState^.InverseMasses[0];
29364 mB:=SpeculativeContactState^.InverseMasses[1];
29365
29366 LocalCenterA:=SpeculativeContactState^.LocalCenters[0];
29367 LocalCenterB:=SpeculativeContactState^.LocalCenters[1];
29368
29369 cA:=fPositions[IndexA].Position;
29370 qA:=fPositions[IndexA].Orientation;
29371 tA:=QuaternionToMatrix4x4(qA);
29372 Temp:=Vector3Sub(cA,Vector3TermMatrixMulBasis(LocalCenterA,tA));
29373 PKraftVector3(pointer(@tA[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29374
29375 cB:=fPositions[IndexB].Position;
29376 qB:=fPositions[IndexB].Orientation;
29377 tB:=QuaternionToMatrix4x4(qB);
29378 Temp:=Vector3Sub(cB,Vector3TermMatrixMulBasis(LocalCenterB,tB));
29379 PKraftVector3(pointer(@tB[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29380
29381 vA:=fVelocities[IndexA].LinearVelocity;
29382 wA:=fVelocities[IndexA].AngularVelocity;
29383
29384 vB:=fVelocities[IndexB].LinearVelocity;
29385 wB:=fVelocities[IndexB].AngularVelocity;
29386
29387 fIsland.fSpeculativeContactPairs[ContactPairIndex]^.GetSolverContactManifold(SolverContactManifold,tA,tB,kcpcmmVelocitySolver);
29388
29389 SpeculativeContactState^.Normal:=SolverContactManifold.Normal;
29390
29391 SolverContact:[email protected][0];
29392
29393 SpeculativeContactState^.RelativePositions[0]:=Vector3Sub(SolverContactManifold.Points[0],cA);
29394 SpeculativeContactState^.RelativePositions[1]:=Vector3Sub(SolverContactManifold.Points[1],cB);
29395
29396 SpeculativeContactState^.Separation:=SolverContact^.Separation;
29397
29398 // Precalculate JM^-1JT for contact and friction constraints
29399 rnA:=Vector3Cross(SpeculativeContactState^.RelativePositions[0],SpeculativeContactState^.Normal);
29400 rnB:=Vector3Cross(SpeculativeContactState^.RelativePositions[1],SpeculativeContactState^.Normal);
29401
29402 NormalMass:=mA+mB+Vector3Dot(rnA,Vector3TermMatrixMul(rnA,iA^))+Vector3Dot(rnB,Vector3TermMatrixMul(rnB,iB^));
29403
29404 if NormalMass>0.0 then begin
29405 SpeculativeContactState^.NormalMass:=1.0/NormalMass;
29406 end else begin
29407 SpeculativeContactState^.NormalMass:=0.0;
29408 end;
29409
29410 for TangentIndex:=0 to 1 do begin
29411 rtA:=Vector3Cross(TangentVectors[TangentIndex],SpeculativeContactState^.RelativePositions[0]);
29412 rtB:=Vector3Cross(TangentVectors[TangentIndex],SpeculativeContactState^.RelativePositions[1]);
29413 TangentMass:=mA+mB+Vector3Dot(rtA,Vector3TermMatrixMul(rtA,iA^))+Vector3Dot(rtB,Vector3TermMatrixMul(rtB,iB^));
29414 if TangentMass>0.0 then begin
29415 SpeculativeContactState^.TangentMass[TangentIndex]:=1.0/TangentMass;
29416 end else begin
29417 SpeculativeContactState^.TangentMass[TangentIndex]:=0.0;
29418 end;
29419 end;
29420
29421 // Precalculate speculative velocity
29422 SpeculativeContactState^.SpeculativeVelocity:=-(SpeculativeContactState^.Separation/fDeltaTime);
29423
29424 // Add in restitution bias to lost speculative bounce
29425 RestitutionBias:=SpeculativeContactState^.LostSpeculativeBounce;
29426 dv:=Vector3Dot(Vector3Sub(Vector3Add(vB,
29427 Vector3Cross(wB,
29428 SpeculativeContactState^.RelativePositions[1])),
29429 Vector3Add(vA,
29430 Vector3Cross(wA,
29431 SpeculativeContactState^.RelativePositions[0]))),
29432 SpeculativeContactState^.Normal);
29433 SpeculativeContactState^.RestitutionBias:=RestitutionBias;
29434 if dv<(-fPhysics.fVelocityThreshold) then begin
29435 RestitutionBias:=Max(RestitutionBias,-(SpeculativeContactState^.Restitution*dv));
29436 end;
29437 SpeculativeContactState^.LostSpeculativeBounce:=RestitutionBias;
29438
29439 end;
29440
29441
29442 end;
29443
29444 procedure TKraftSolver.WarmStart;
29445 var ContactPairIndex,ContactIndex,IndexA,IndexB,CountPoints:longint;
29446 VelocityState:PKraftSolverVelocityState;
29447 ContactPoint:PKraftSolverVelocityStateContactPoint;
29448 iA,iB:PKraftMatrix3x3;
29449 mA,mB,dv,RestitutionBias:TKraftScalar;
29450 Normal,vA,lA,wA,vB,lB,wB,P:TKraftVector3;
29451 TangentVectors:array[0..1] of TKraftVector3;
29452 SpeculativeContactState:PKraftSolverSpeculativeContactState;
29453 begin
29454
29455 for ContactPairIndex:=0 to fCountContacts-1 do begin
29456
29457 VelocityState:=@fVelocityStates[ContactPairIndex];
29458 IndexA:=VelocityState^.Indices[0];
29459 IndexB:=VelocityState^.Indices[1];
29460 iA:=@VelocityState^.WorldInverseInertiaTensors[0];
29461 iB:=@VelocityState^.WorldInverseInertiaTensors[1];
29462 mA:=VelocityState^.InverseMasses[0];
29463 mB:=VelocityState^.InverseMasses[1];
29464 CountPoints:=VelocityState^.CountPoints;
29465 Normal:=VelocityState^.Normal;
29466
29467 ComputeBasis(Normal,TangentVectors[0],TangentVectors[1]);
29468
29469 vA:=fVelocities[IndexA].LinearVelocity;
29470 wA:=fVelocities[IndexA].AngularVelocity;
29471 vB:=fVelocities[IndexB].LinearVelocity;
29472 wB:=fVelocities[IndexB].AngularVelocity;
29473
29474 lA:=fLinearFactors[IndexA];
29475 lB:=fLinearFactors[IndexB];
29476
29477 for ContactIndex:=0 to CountPoints-1 do begin
29478
29479 ContactPoint:=@VelocityState^.Points[ContactIndex];
29480
29481 P:=Vector3Add(Vector3ScalarMul(Normal,ContactPoint^.NormalImpulse),
29482 Vector3Add(Vector3ScalarMul(TangentVectors[0],ContactPoint^.TangentImpulse[0]),
29483 Vector3ScalarMul(TangentVectors[1],ContactPoint^.TangentImpulse[1])));
29484
29485 Vector3DirectSub(vA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29486 Vector3DirectSub(wA,Vector3TermMatrixMul(Vector3Cross(ContactPoint^.RelativePositions[0],P),iA^));
29487
29488 Vector3DirectAdd(vB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29489 Vector3DirectAdd(wB,Vector3TermMatrixMul(Vector3Cross(ContactPoint^.RelativePositions[1],P),iB^));
29490
29491 if fPositionCorrectionMode=kpcmBaumgarte then begin
29492 dv:=Vector3Dot(Vector3Sub(Vector3Add(vB,
29493 Vector3Cross(wB,
29494 ContactPoint^.RelativePositions[1])),
29495 Vector3Add(vA,
29496 Vector3Cross(wA,
29497 ContactPoint^.RelativePositions[0]))),
29498 VelocityState^.Normal);
29499 if dv<(-fPhysics.fVelocityThreshold) then begin
29500 ContactPoint^.Bias:=ContactPoint^.BaumgarteBias-(VelocityState^.Restitution*dv);
29501 end;
29502 end;
29503
29504 end;
29505
29506 fVelocities[IndexA].LinearVelocity:=vA;
29507 fVelocities[IndexA].AngularVelocity:=wA;
29508 fVelocities[IndexB].LinearVelocity:=vB;
29509 fVelocities[IndexB].AngularVelocity:=wB;
29510
29511 end;
29512
29513 for ContactPairIndex:=0 to fCountSpeculativeContacts-1 do begin
29514
29515 SpeculativeContactState:=@fSpeculativeContactStates[ContactPairIndex];
29516
29517 IndexA:=SpeculativeContactState^.Indices[0];
29518 IndexB:=SpeculativeContactState^.Indices[1];
29519 iA:=@SpeculativeContactState^.WorldInverseInertiaTensors[0];
29520 iB:=@SpeculativeContactState^.WorldInverseInertiaTensors[1];
29521 mA:=SpeculativeContactState^.InverseMasses[0];
29522 mB:=SpeculativeContactState^.InverseMasses[1];
29523 Normal:=SpeculativeContactState^.Normal;
29524
29525 ComputeBasis(Normal,TangentVectors[0],TangentVectors[1]);
29526
29527 vA:=fVelocities[IndexA].LinearVelocity;
29528 wA:=fVelocities[IndexA].AngularVelocity;
29529 vB:=fVelocities[IndexB].LinearVelocity;
29530 wB:=fVelocities[IndexB].AngularVelocity;
29531
29532 lA:=fLinearFactors[IndexA];
29533 lB:=fLinearFactors[IndexB];
29534
29535 P:=Vector3Add(Vector3ScalarMul(Normal,SpeculativeContactState^.NormalImpulse),
29536 Vector3Add(Vector3ScalarMul(TangentVectors[0],SpeculativeContactState^.TangentImpulse[0]),
29537 Vector3ScalarMul(TangentVectors[1],SpeculativeContactState^.TangentImpulse[1])));
29538
29539 Vector3DirectSub(vA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29540 Vector3DirectSub(wA,Vector3TermMatrixMul(Vector3Cross(SpeculativeContactState^.RelativePositions[0],P),iA^));
29541
29542 Vector3DirectAdd(vB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29543 Vector3DirectAdd(wB,Vector3TermMatrixMul(Vector3Cross(SpeculativeContactState^.RelativePositions[1],P),iB^));
29544
29545 // Add in restitution bias to lost speculative bounce
29546 RestitutionBias:=SpeculativeContactState^.RestitutionBias;
29547 dv:=Vector3Dot(Vector3Sub(Vector3Add(vB,
29548 Vector3Cross(wB,
29549 SpeculativeContactState^.RelativePositions[1])),
29550 Vector3Add(vA,
29551 Vector3Cross(wA,
29552 SpeculativeContactState^.RelativePositions[0]))),
29553 SpeculativeContactState^.Normal);
29554 if dv<(-fPhysics.fVelocityThreshold) then begin
29555 RestitutionBias:=Max(RestitutionBias,-(SpeculativeContactState^.Restitution*dv));
29556 end;
29557 SpeculativeContactState^.LostSpeculativeBounce:=RestitutionBias;
29558
29559 fVelocities[IndexA].LinearVelocity:=vA;
29560 fVelocities[IndexA].AngularVelocity:=wA;
29561 fVelocities[IndexB].LinearVelocity:=vB;
29562 fVelocities[IndexB].AngularVelocity:=wB;
29563
29564 end;
29565
29566 end;
29567
29568 procedure TKraftSolver.SolveVelocityConstraints;
29569 var ContactPairIndex,ContactIndex,TangentIndex,IndexA,IndexB,CountPoints:longint;
29570 VelocityState:PKraftSolverVelocityState;
29571 ContactPoint:PKraftSolverVelocityStateContactPoint;
29572 iA,iB:PKraftMatrix3x3;
29573 mA,mB,Friction,Lambda,MaxLambda,vn,Old:TKraftScalar;
29574 Normal,vA,lA,wA,rA,vB,lB,wB,rB,dv,P:TKraftVector3;
29575 TangentVectors:array[0..1] of TKraftVector3;
29576 begin
29577
29578 for ContactPairIndex:=0 to fCountContacts-1 do begin
29579
29580 VelocityState:=@fVelocityStates[ContactPairIndex];
29581 IndexA:=VelocityState^.Indices[0];
29582 IndexB:=VelocityState^.Indices[1];
29583 iA:=@VelocityState^.WorldInverseInertiaTensors[0];
29584 iB:=@VelocityState^.WorldInverseInertiaTensors[1];
29585 mA:=VelocityState^.InverseMasses[0];
29586 mB:=VelocityState^.InverseMasses[1];
29587 CountPoints:=VelocityState^.CountPoints;
29588 Normal:=VelocityState^.Normal;
29589 Friction:=VelocityState^.Friction;
29590 ComputeBasis(Normal,TangentVectors[0],TangentVectors[1]);
29591
29592 vA:=fVelocities[IndexA].LinearVelocity;
29593 wA:=fVelocities[IndexA].AngularVelocity;
29594 vB:=fVelocities[IndexB].LinearVelocity;
29595 wB:=fVelocities[IndexB].AngularVelocity;
29596
29597 lA:=fLinearFactors[IndexA];
29598 lB:=fLinearFactors[IndexB];
29599
29600 for ContactIndex:=0 to CountPoints-1 do begin
29601
29602 ContactPoint:=@VelocityState^.Points[ContactIndex];
29603
29604 rA:=ContactPoint^.RelativePositions[0];
29605 rB:=ContactPoint^.RelativePositions[1];
29606
29607 if fEnableFriction then begin
29608
29609 MaxLambda:=Friction*ContactPoint^.NormalImpulse;
29610
29611 for TangentIndex:=0 to 1 do begin
29612
29613 dv:=Vector3Sub(Vector3Add(vB,Vector3Cross(wB,rB)),Vector3Add(vA,Vector3Cross(wA,rA)));
29614
29615 Lambda:=(-Vector3Dot(dv,TangentVectors[TangentIndex]))*ContactPoint^.TangentMass[TangentIndex];
29616
29617 Old:=ContactPoint^.TangentImpulse[TangentIndex];
29618 ContactPoint^.TangentImpulse[TangentIndex]:=Min(Max(Old+Lambda,-MaxLambda),MaxLambda);
29619 Lambda:=ContactPoint^.TangentImpulse[TangentIndex]-Old;
29620
29621 P:=Vector3ScalarMul(TangentVectors[TangentIndex],Lambda);
29622
29623 Vector3DirectSub(vA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29624 Vector3DirectSub(wA,Vector3TermMatrixMul(Vector3Cross(rA,P),iA^));
29625
29626 Vector3DirectAdd(vB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29627 Vector3DirectAdd(wB,Vector3TermMatrixMul(Vector3Cross(rB,P),iB^));
29628
29629 end;
29630
29631 end;
29632
29633 dv:=Vector3Sub(Vector3Add(vB,Vector3Cross(wB,rB)),Vector3Add(vA,Vector3Cross(wA,rA)));
29634
29635 vn:=Vector3Dot(dv,Normal);
29636
29637 Lambda:=ContactPoint^.NormalMass*(ContactPoint^.Bias-vn);
29638
29639 Old:=ContactPoint^.NormalImpulse;
29640 ContactPoint^.NormalImpulse:=Max(0.0,Old+Lambda);
29641 Lambda:=ContactPoint^.NormalImpulse-Old;
29642
29643 P:=Vector3ScalarMul(Normal,Lambda);
29644
29645 Vector3DirectSub(vA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29646 Vector3DirectSub(wA,Vector3TermMatrixMul(Vector3Cross(rA,P),iA^));
29647
29648 Vector3DirectAdd(vB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29649 Vector3DirectAdd(wB,Vector3TermMatrixMul(Vector3Cross(rB,P),iB^));
29650
29651 end;
29652
29653 fVelocities[IndexA].LinearVelocity:=vA;
29654 fVelocities[IndexA].AngularVelocity:=wA;
29655 fVelocities[IndexB].LinearVelocity:=vB;
29656 fVelocities[IndexB].AngularVelocity:=wB;
29657
29658 end;
29659
29660 end;
29661
29662 function TKraftSolver.SolvePositionConstraints:boolean;
29663 var ContactPairIndex,ContactIndex,IndexA,IndexB:longint;
29664 PositionState:PKraftSolverPositionState;
29665 SolverContact:PKraftSolverContact;
29666 iA,iB:PKraftMatrix3x3;
29667 MinSeparation,mA,mB,Separation,C,K,Impulse:TKraftScalar;
29668 LocalCenterA,LocalCenterB,cA,cB,Normal,Point,rA,rB,rnA,rnB,P,Temp,lA,lB:TKraftVector3;
29669 qA,qB:TKraftQuaternion;
29670 tA,tB:TKraftMatrix4x4;
29671 SolverContactManifold:TKraftSolverContactManifold;
29672 begin
29673
29674 if fPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
29675
29676 MinSeparation:=0.0;
29677 for ContactPairIndex:=0 to fCountContacts-1 do begin
29678
29679 PositionState:=@fPositionStates[ContactPairIndex];
29680
29681 IndexA:=PositionState^.Indices[0];
29682 IndexB:=PositionState^.Indices[1];
29683
29684 iA:=@PositionState^.WorldInverseInertiaTensors[0];
29685 iB:=@PositionState^.WorldInverseInertiaTensors[1];
29686
29687 mA:=PositionState^.InverseMasses[0];
29688 mB:=PositionState^.InverseMasses[1];
29689
29690 LocalCenterA:=PositionState^.LocalCenters[0];
29691 LocalCenterB:=PositionState^.LocalCenters[1];
29692
29693 lA:=fLinearFactors[IndexA];
29694 lB:=fLinearFactors[IndexB];
29695
29696 cA:=fPositions[IndexA].Position;
29697 qA:=fPositions[IndexA].Orientation;
29698 tA:=QuaternionToMatrix4x4(qA);
29699 Temp:=Vector3Sub(cA,Vector3TermMatrixMulBasis(LocalCenterA,tA));
29700 PKraftVector3(pointer(@tA[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29701
29702 cB:=fPositions[IndexB].Position;
29703 qB:=fPositions[IndexB].Orientation;
29704 tB:=QuaternionToMatrix4x4(qB);
29705 Temp:=Vector3Sub(cB,Vector3TermMatrixMulBasis(LocalCenterB,tB));
29706 PKraftVector3(pointer(@tB[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29707
29708 fIsland.fContactPairs[ContactPairIndex]^.GetSolverContactManifold(SolverContactManifold,tA,tB,kcpcmmPositionSolver);
29709
29710 Normal:=SolverContactManifold.Normal;
29711
29712 for ContactIndex:=0 to SolverContactManifold.CountContacts-1 do begin
29713
29714 SolverContact:[email protected][ContactIndex];
29715
29716 Point:=SolverContact^.Point;
29717 Separation:=SolverContact^.Separation;
29718
29719 rA:=Vector3Sub(Point,cA);
29720 rB:=Vector3Sub(Point,cB);
29721
29722 if MinSeparation>Separation then begin
29723 MinSeparation:=Separation;
29724 end;
29725
29726 C:=Min(Max(fPhysics.fContactBaumgarte*(Separation+fPhysics.fLinearSlop),-fPhysics.fMaximalLinearCorrection),0.0);
29727
29728 rnA:=Vector3Cross(rA,Normal);
29729 rnB:=Vector3Cross(rB,Normal);
29730
29731 K:=mA+mB+Vector3Dot(rnA,Vector3TermMatrixMul(rnA,iA^))+Vector3Dot(rnB,Vector3TermMatrixMul(rnB,iB^));
29732
29733 if K>0.0 then begin
29734 Impulse:=-(C/K);
29735 end else begin
29736 Impulse:=0.0;
29737 end;
29738
29739 P:=Vector3ScalarMul(Normal,Impulse);
29740
29741 Vector3DirectSub(cA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29742 QuaternionDirectSpin(qA,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(P)),iA^),1.0);
29743
29744 Vector3DirectAdd(cB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29745 QuaternionDirectSpin(qB,Vector3TermMatrixMul(Vector3Cross(rB,P),iB^),1.0);
29746
29747 end;
29748
29749 fPositions[IndexA].Position:=cA;
29750 fPositions[IndexA].Orientation:=qA;
29751
29752 fPositions[IndexB].Position:=cB;
29753 fPositions[IndexB].Orientation:=qB;
29754
29755 end;
29756
29757 result:=MinSeparation>=((-3.0)*fPhysics.fLinearSlop);
29758
29759 end else begin
29760
29761 result:=true;
29762
29763 end;
29764
29765 end;
29766
29767 function TKraftSolver.SolveTimeOfImpactConstraints(IndexA,IndexB:longint):boolean;
29768 var ContactPairIndex,ContactIndex,CurrentIndexA,CurrentIndexB:longint;
29769 PositionState:PKraftSolverPositionState;
29770 SolverContact:PKraftSolverContact;
29771 iA,iB:PKraftMatrix3x3;
29772 MinSeparation,mA,mB,Separation,C,K,Impulse:TKraftScalar;
29773 LocalCenterA,LocalCenterB,cA,cB,Normal,Point,rA,rB,rnA,rnB,P,Temp,lA,lB:TKraftVector3;
29774 qA,qB:TKraftQuaternion;
29775 tA,tB:TKraftMatrix4x4;
29776 SolverContactManifold:TKraftSolverContactManifold;
29777 begin
29778
29779 if fPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
29780
29781 MinSeparation:=0.0;
29782
29783 for ContactPairIndex:=0 to fCountContacts-1 do begin
29784
29785 PositionState:=@fPositionStates[ContactPairIndex];
29786
29787 CurrentIndexA:=PositionState^.Indices[0];
29788 CurrentIndexB:=PositionState^.Indices[1];
29789
29790 LocalCenterA:=PositionState^.LocalCenters[0];
29791 LocalCenterB:=PositionState^.LocalCenters[1];
29792
29793 if (CurrentIndexA=IndexA) or (CurrentIndexA=IndexB) then begin
29794 iA:=@PositionState^.WorldInverseInertiaTensors[0];
29795 mA:=PositionState^.InverseMasses[0];
29796 end else begin
29797 mA:=0.0;
29798 iA:=@Matrix3x3Null;
29799 end;
29800
29801 if (CurrentIndexB=IndexA) or (CurrentIndexB=IndexB) then begin
29802 iB:=@PositionState^.WorldInverseInertiaTensors[1];
29803 mB:=PositionState^.InverseMasses[1];
29804 end else begin
29805 mB:=0.0;
29806 iB:=@Matrix3x3Null;
29807 end;
29808
29809 lA:=fLinearFactors[IndexA];
29810 lB:=fLinearFactors[IndexB];
29811
29812 cA:=fPositions[IndexA].Position;
29813 qA:=fPositions[IndexA].Orientation;
29814 tA:=QuaternionToMatrix4x4(qA);
29815 Temp:=Vector3Sub(cA,Vector3TermMatrixMulBasis(LocalCenterA,tA));
29816 PKraftVector3(pointer(@tA[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29817
29818 cB:=fPositions[IndexB].Position;
29819 qB:=fPositions[IndexB].Orientation;
29820 tB:=QuaternionToMatrix4x4(qB);
29821 Temp:=Vector3Sub(cB,Vector3TermMatrixMulBasis(LocalCenterB,tB));
29822 PKraftVector3(pointer(@tB[3,0]))^.xyz:=PKraftVector3(pointer(@Temp))^.xyz;
29823
29824 fIsland.fContactPairs[ContactPairIndex]^.GetSolverContactManifold(SolverContactManifold,tA,tB,kcpcmmPositionSolver);
29825
29826 Normal:=SolverContactManifold.Normal;
29827
29828 for ContactIndex:=0 to SolverContactManifold.CountContacts-1 do begin
29829
29830 SolverContact:[email protected][ContactIndex];
29831
29832 Point:=SolverContact^.Point;
29833 Separation:=SolverContact^.Separation;
29834
29835 rA:=Vector3Sub(Point,cA);
29836 rB:=Vector3Sub(Point,cB);
29837
29838 if MinSeparation>Separation then begin
29839 MinSeparation:=Separation;
29840 end;
29841
29842 C:=Min(Max(fPhysics.fTimeOfImpactBaumgarte*(Separation+fPhysics.fLinearSlop),-fPhysics.fMaximalLinearCorrection),0.0);
29843
29844 rnA:=Vector3Cross(rA,Normal);
29845 rnB:=Vector3Cross(rB,Normal);
29846
29847 K:=mA+mB+Vector3Dot(rnA,Vector3TermMatrixMul(rnA,iA^))+Vector3Dot(rnB,Vector3TermMatrixMul(rnB,iB^));
29848
29849 if K>0.0 then begin
29850 Impulse:=-(C/K);
29851 end else begin
29852 Impulse:=0.0;
29853 end;
29854
29855 P:=Vector3ScalarMul(Normal,Impulse);
29856
29857 Vector3DirectSub(cA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29858 QuaternionDirectSpin(qA,Vector3TermMatrixMul(Vector3Cross(rA,Vector3Neg(P)),iA^),1.0);
29859
29860 Vector3DirectAdd(cB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29861 QuaternionDirectSpin(qB,Vector3TermMatrixMul(Vector3Cross(rB,P),iB^),1.0);
29862
29863 end;
29864
29865 fPositions[IndexA].Position:=cA;
29866 fPositions[IndexA].Orientation:=qA;
29867
29868 fPositions[IndexB].Position:=cB;
29869 fPositions[IndexB].Orientation:=qB;
29870
29871 end;
29872
29873 result:=MinSeparation>=((-1.5)*fPhysics.fLinearSlop);
29874
29875 end else begin
29876
29877 result:=true;
29878
29879 end;
29880
29881 end;
29882
29883 procedure TKraftSolver.SolveSpeculativeContactConstraints;
29884 var ContactPairIndex,TangentIndex,IndexA,IndexB:longint;
29885 SpeculativeContactState:PKraftSolverSpeculativeContactState;
29886 iA,iB:PKraftMatrix3x3;
29887 mA,mB,Friction,Lambda,MaxLambda,vn,Old:TKraftScalar;
29888 Normal,vA,lA,wA,rA,vB,lB,wB,rB,dv,P:TKraftVector3;
29889 TangentVectors:array[0..1] of TKraftVector3;
29890 begin
29891
29892 for ContactPairIndex:=0 to fCountSpeculativeContacts-1 do begin
29893
29894 SpeculativeContactState:=@fSpeculativeContactStates[ContactPairIndex];
29895 IndexA:=SpeculativeContactState^.Indices[0];
29896 IndexB:=SpeculativeContactState^.Indices[1];
29897 iA:=@SpeculativeContactState^.WorldInverseInertiaTensors[0];
29898 iB:=@SpeculativeContactState^.WorldInverseInertiaTensors[1];
29899 mA:=SpeculativeContactState^.InverseMasses[0];
29900 mB:=SpeculativeContactState^.InverseMasses[1];
29901 Normal:=SpeculativeContactState^.Normal;
29902 Friction:=SpeculativeContactState^.Friction;
29903 ComputeBasis(Normal,TangentVectors[0],TangentVectors[1]);
29904
29905 vA:=fVelocities[IndexA].LinearVelocity;
29906 wA:=fVelocities[IndexA].AngularVelocity;
29907 vB:=fVelocities[IndexB].LinearVelocity;
29908 wB:=fVelocities[IndexB].AngularVelocity;
29909
29910 lA:=fLinearFactors[IndexA];
29911 lB:=fLinearFactors[IndexB];
29912
29913 rA:=SpeculativeContactState^.RelativePositions[0];
29914 rB:=SpeculativeContactState^.RelativePositions[1];
29915
29916 if fEnableFriction then begin
29917
29918 MaxLambda:=Friction*SpeculativeContactState^.NormalImpulse;
29919
29920 for TangentIndex:=0 to 1 do begin
29921
29922 dv:=Vector3Sub(Vector3Add(vB,Vector3Cross(wB,rB)),Vector3Add(vA,Vector3Cross(wA,rA)));
29923
29924 Lambda:=(-Vector3Dot(dv,TangentVectors[TangentIndex]))*SpeculativeContactState^.TangentMass[TangentIndex];
29925
29926 Old:=SpeculativeContactState^.TangentImpulse[TangentIndex];
29927 SpeculativeContactState^.TangentImpulse[TangentIndex]:=Min(Max(Old+Lambda,-MaxLambda),MaxLambda);
29928 Lambda:=SpeculativeContactState^.TangentImpulse[TangentIndex]-Old;
29929
29930 P:=Vector3ScalarMul(TangentVectors[TangentIndex],Lambda);
29931
29932 Vector3DirectSub(vA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29933 Vector3DirectSub(wA,Vector3TermMatrixMul(Vector3Cross(rA,P),iA^));
29934
29935 Vector3DirectAdd(vB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29936 Vector3DirectAdd(wB,Vector3TermMatrixMul(Vector3Cross(rB,P),iB^));
29937
29938 end;
29939
29940 end;
29941
29942 dv:=Vector3Sub(Vector3Add(vB,Vector3Cross(wB,rB)),Vector3Add(vA,Vector3Cross(wA,rA)));
29943
29944 vn:=Vector3Dot(dv,Normal);
29945
29946 Lambda:=SpeculativeContactState^.NormalMass*(SpeculativeContactState^.SpeculativeVelocity-vn);
29947
29948 Old:=SpeculativeContactState^.NormalImpulse;
29949 SpeculativeContactState^.NormalImpulse:=Max(0.0,Old+Lambda);
29950 Lambda:=SpeculativeContactState^.NormalImpulse-Old;
29951
29952 P:=Vector3ScalarMul(Normal,Lambda);
29953
29954 Vector3DirectSub(vA,Vector3Mul(P,Vector3ScalarMul(lA,mA)));
29955 Vector3DirectSub(wA,Vector3TermMatrixMul(Vector3Cross(rA,P),iA^));
29956
29957 Vector3DirectAdd(vB,Vector3Mul(P,Vector3ScalarMul(lB,mB)));
29958 Vector3DirectAdd(wB,Vector3TermMatrixMul(Vector3Cross(rB,P),iB^));
29959
29960 fVelocities[IndexA].LinearVelocity:=vA;
29961 fVelocities[IndexA].AngularVelocity:=wA;
29962 fVelocities[IndexB].LinearVelocity:=vB;
29963 fVelocities[IndexB].AngularVelocity:=wB;
29964
29965 end;
29966
29967 end;
29968
29969 procedure TKraftSolver.StoreImpulses;
29970 var i,j:longint;
29971 VelocityState:PKraftSolverVelocityState;
29972 ContactPair:PKraftContactPair;
29973 Contact:PKraftContact;
29974 ContactPoint:PKraftSolverVelocityStateContactPoint;
29975 SpeculativeContactState:PKraftSolverSpeculativeContactState;
29976 begin
29977 for i:=0 to fCountContacts-1 do begin
29978 VelocityState:=@fVelocityStates[i];
29979 ContactPair:=fIsland.fContactPairs[i];
29980 ContactPair^.Manifold.LostSpeculativeBounce:=0.0;
29981 for j:=0 to VelocityState^.CountPoints-1 do begin
29982 Contact:=@ContactPair^.Manifold.Contacts[j];
29983 ContactPoint:=@VelocityState^.Points[j];
29984 Contact^.NormalImpulse:=ContactPoint^.NormalImpulse;
29985 Contact^.TangentImpulse[0]:=ContactPoint^.TangentImpulse[0];
29986 Contact^.TangentImpulse[1]:=ContactPoint^.TangentImpulse[1];
29987 end;
29988 end;
29989 for i:=0 to fCountSpeculativeContacts-1 do begin
29990 SpeculativeContactState:=@fSpeculativeContactStates[i];
29991 ContactPair:=fIsland.fSpeculativeContactPairs[i];
29992 Contact:=@ContactPair^.Manifold.Contacts[0];
29993 ContactPair^.Manifold.LostSpeculativeBounce:=SpeculativeContactState^.LostSpeculativeBounce;
29994 Contact^.NormalImpulse:=SpeculativeContactState^.NormalImpulse;
29995 Contact^.TangentImpulse[0]:=SpeculativeContactState^.TangentImpulse[0];
29996 Contact^.TangentImpulse[1]:=SpeculativeContactState^.TangentImpulse[1];
29997 end;
29998 end;
29999
30000 constructor TKraftIsland.Create(const APhysics:TKraft;const AIndex:longint);
30001 begin
30002 inherited Create;
30003
30004 fPhysics:=APhysics;
30005
30006 fIslandIndex:=AIndex;
30007
30008 fRigidBodies:=nil;
30009 SetLength(fRigidBodies,64);
30010 fCountRigidBodies:=0;
30011
30012 fConstraints:=nil;
30013 SetLength(fConstraints,64);
30014 fCountConstraints:=0;
30015
30016 fContactPairs:=nil;
30017 SetLength(fContactPairs,64);
30018 fCountContactPairs:=0;
30019
30020 fStaticContactPairs:=nil;
30021 SetLength(fStaticContactPairs,64);
30022 fCountStaticContactPairs:=0;
30023
30024 fSpeculativeContactPairs:=nil;
30025 SetLength(fSpeculativeContactPairs,4096);
30026 fCountSpeculativeContactPairs:=0;
30027
30028 fSolver:=TKraftSolver.Create(fPhysics,self);
30029
30030 end;
30031
30032 destructor TKraftIsland.Destroy;
30033 begin
30034 SetLength(fRigidBodies,0);
30035 SetLength(fConstraints,0);
30036 SetLength(fContactPairs,0);
30037 SetLength(fStaticContactPairs,0);
30038 SetLength(fSpeculativeContactPairs,0);
30039 fSolver.Free;
30040 inherited Destroy;
30041 end;
30042
30043 procedure TKraftIsland.Clear;
30044 begin
30045 fCountRigidBodies:=0;
30046 fCountConstraints:=0;
30047 fCountContactPairs:=0;
30048 fCountStaticContactPairs:=0;
30049 fCountSpeculativeContactPairs:=0;
30050 end;
30051
30052 function TKraftIsland.AddRigidBody(RigidBody:TKraftRigidBody):longint;
30053 begin
30054 RigidBody.fIsland:=self;
30055 if (fCountRigidBodies+1)>length(fRigidBodies) then begin
30056 SetLength(fRigidBodies,(fCountRigidBodies+1)*2);
30057 end;
30058 fRigidBodies[fCountRigidBodies]:=RigidBody;
30059 if fIslandIndex>=length(RigidBody.fIslandIndices) then begin
30060 SetLength(RigidBody.fIslandIndices,(fIslandIndex+1)*2);
30061 end;
30062 RigidBody.fIslandIndices[fIslandIndex]:=fCountRigidBodies;
30063 result:=fCountRigidBodies;
30064 inc(fCountRigidBodies);
30065 end;
30066
30067 procedure TKraftIsland.AddConstraint(Constraint:TKraftConstraint);
30068 begin
30069 if (fCountConstraints+1)>length(fConstraints) then begin
30070 SetLength(fConstraints,(fCountConstraints+1)*2);
30071 end;
30072 fConstraints[fCountConstraints]:=Constraint;
30073 inc(fCountConstraints);
30074 end;
30075
30076 procedure TKraftIsland.AddContactPair(ContactPair:PKraftContactPair);
30077 begin
30078 ContactPair^.Island:=self;
30079 if ContactPair^.Manifold.ContactManifoldType=kcmtSpeculative then begin
30080 if (fCountSpeculativeContactPairs+1)>length(fSpeculativeContactPairs) then begin
30081 SetLength(fSpeculativeContactPairs,(fCountSpeculativeContactPairs+1)*2);
30082 end;
30083 fSpeculativeContactPairs[fCountSpeculativeContactPairs]:=ContactPair;
30084 inc(fCountSpeculativeContactPairs);
30085 end else begin
30086 if (assigned(ContactPair^.RigidBodies[0]) and (ContactPair^.RigidBodies[0].fRigidBodyType=krbtDynamic)) and
30087 (assigned(ContactPair^.RigidBodies[1]) and (ContactPair^.RigidBodies[1].fRigidBodyType=krbtDynamic)) then begin
30088 // Dynamic vs dynamic (solving before dynamic vs static in a solver iteration)
30089 if (fCountContactPairs+1)>length(fContactPairs) then begin
30090 SetLength(fContactPairs,(fCountContactPairs+1)*2);
30091 end;
30092 fContactPairs[fCountContactPairs]:=ContactPair;
30093 inc(fCountContactPairs);
30094 end else begin
30095 // Dynamic vs static (solving after dynamic vs dynamic in a solver iteration)
30096 if (fCountStaticContactPairs+1)>length(fStaticContactPairs) then begin
30097 SetLength(fStaticContactPairs,(fCountStaticContactPairs+1)*2);
30098 end;
30099 fStaticContactPairs[fCountStaticContactPairs]:=ContactPair;
30100 inc(fCountStaticContactPairs);
30101 end;
30102 end;
30103 end;
30104
30105 procedure TKraftIsland.MergeContactPairs;
30106 var NewCountContactPairs:longint;
30107 begin
30108 NewCountContactPairs:=fCountContactPairs+fCountStaticContactPairs;
30109 if length(fContactPairs)<NewCountContactPairs then begin
30110 SetLength(fContactPairs,NewCountContactPairs*2);
30111 end;
30112 if fCountStaticContactPairs>0 then begin
30113 Move(fStaticContactPairs[0],fContactPairs[fCountContactPairs],fCountStaticContactPairs*SizeOf(PKraftContactPair));
30114 inc(fCountContactPairs,fCountStaticContactPairs);
30115 end;
30116 end;
30117
30118 procedure TKraftIsland.Solve(const TimeStep:TKraftTimeStep);
30119 var Iteration,Index:longint;
30120 RigidBody:TKraftRigidBody;
30121 Constraint:TKraftConstraint;
30122 MinSleepTime,s:TKraftScalar;
30123 First,OK:boolean;
30124 SolverVelocity:PKraftSolverVelocity;
30125 SolverPosition:PKraftSolverPosition;
30126 GyroscopicForce:TKraftVector3;
30127 Position,LinearVelocity,AngularVelocity,Translation,Rotation:TKraftVector3;
30128 Orientation:TKraftQuaternion;
30129 begin
30130
30131 fSolver.Store;
30132
30133 // Integrate velocities and create state buffers, calculate world inertia
30134 for Index:=0 to fCountRigidBodies-1 do begin
30135
30136 RigidBody:=fRigidBodies[Index];
30137
30138 Position:=RigidBody.fSweep.c;
30139 Orientation:=RigidBody.fSweep.q;
30140 RigidBody.fSweep.c0:=RigidBody.fSweep.c;
30141 RigidBody.fSweep.q0:=RigidBody.fSweep.q;
30142
30143 if RigidBody.fRigidBodyType=krbtDynamic then begin
30144
30145 // Apply gravity force
30146 if krbfHasOwnGravity in RigidBody.fFlags then begin
30147 RigidBody.fForce:=Vector3Add(RigidBody.fForce,Vector3ScalarMul(RigidBody.fGravity,RigidBody.fMass*RigidBody.fGravityScale));
30148 end else begin
30149 RigidBody.fForce:=Vector3Add(RigidBody.fForce,Vector3ScalarMul(fPhysics.fGravity,RigidBody.fMass*RigidBody.fGravityScale));
30150 end;
30151
30152 // Calculate world space inertia tensor
30153 RigidBody.UpdateWorldInertiaTensor;
30154
30155 // Apply gyroscopic force
30156 if RigidBody.fEnableGyroscopicForce then begin
30157 // Gyroscopic force calculation using full newton-euler equations with implicit euler step, so it's stable.
30158 GyroscopicForce:=Vector3Sub(Vector3Sub(RigidBody.fAngularVelocity,
30159 Vector3TermMatrixMulInverse(EvaluateEulerEquation(RigidBody.fAngularVelocity,
30160 RigidBody.fAngularVelocity,
30161 Vector3Origin,
30162 TimeStep.DeltaTime,
30163 RigidBody.fWorldInertiaTensor),
30164 EvaluateEulerEquationDerivation(RigidBody.fAngularVelocity,
30165 RigidBody.fAngularVelocity,
30166 TimeStep.DeltaTime,
30167 RigidBody.fWorldInertiaTensor))),
30168 RigidBody.fAngularVelocity);
30169 if (RigidBody.fMaximalGyroscopicForce>EPSILON) and (Vector3LengthSquared(GyroscopicForce)>sqr(RigidBody.fMaximalGyroscopicForce)) then begin
30170 Vector3Scale(GyroscopicForce,RigidBody.fMaximalGyroscopicForce/Vector3Length(GyroscopicForce));
30171 end;
30172 RigidBody.fTorque:=Vector3Add(RigidBody.fTorque,GyroscopicForce);
30173 end;
30174
30175 // Integrate linear velocity
30176 RigidBody.fLinearVelocity:=Vector3Add(RigidBody.fLinearVelocity,VEctor3Mul(RigidBody.fForce,Vector3ScalarMul(RigidBody.fLinearFactor,RigidBody.InverseMass*TimeStep.DeltaTime)));
30177
30178 // Integrate angular velocity
30179 RigidBody.fAngularVelocity:=Vector3Add(RigidBody.fAngularVelocity,Vector3ScalarMul(Vector3TermMatrixMul(RigidBody.fTorque,RigidBody.fWorldInverseInertiaTensor),TimeStep.DeltaTime));
30180
30181 if assigned(RigidBody.fOnDamping) then begin
30182 RigidBody.fOnDamping(RigidBody,TimeStep);
30183 end;
30184
30185 // From Box2D
30186 // Apply damping.
30187 // ODE: dv/dt + c * v = 0
30188 // Solution: v(t) = v0 * exp(-c * t)
30189 // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt)
30190 // v2 = exp(-c * dt) * v1
30191 // Pade approximation:
30192 // v2 = v1 * 1 / (1 + c * dt)
30193 Vector3Scale(RigidBody.fLinearVelocity,1.0/(1.0+(RigidBody.fLinearVelocityDamp*TimeStep.DeltaTime)));
30194 Vector3Scale(RigidBody.fAngularVelocity,1.0/(1.0+(RigidBody.fAngularVelocityDamp*TimeStep.DeltaTime)));
30195
30196 // From PAPPE 1.0
30197 if RigidBody.fAdditionalDamping then begin
30198 if (Vector3LengthSquared(RigidBody.fLinearVelocity)<RigidBody.fLinearVelocityAdditionalDampThresholdSqr) and
30199 (Vector3LengthSquared(RigidBody.fAngularVelocity)<RigidBody.fAngularVelocityAdditionalDampThresholdSqr) then begin
30200 Vector3Scale(RigidBody.fLinearVelocity,RigidBody.fAdditionalDamp);
30201 Vector3Scale(RigidBody.fAngularVelocity,RigidBody.fAdditionalDamp);
30202 end;
30203 s:=Vector3Length(RigidBody.fLinearVelocity);
30204 if s<RigidBody.fLinearVelocityDamp then begin
30205 if s>RigidBody.fAdditionalDamp then begin
30206 RigidBody.fLinearVelocity:=Vector3Sub(RigidBody.fLinearVelocity,Vector3ScalarMul(Vector3NormEx(RigidBody.fLinearVelocity),RigidBody.fAdditionalDamp));
30207 end else begin
30208 RigidBody.fLinearVelocity:=Vector3Origin;
30209 end;
30210 end;
30211 s:=Vector3Length(RigidBody.fAngularVelocity);
30212 if s<RigidBody.fAngularVelocityDamp then begin
30213 if s>RigidBody.fAdditionalDamp then begin
30214 RigidBody.fAngularVelocity:=Vector3Sub(RigidBody.fAngularVelocity,Vector3ScalarMul(Vector3NormEx(RigidBody.fAngularVelocity),RigidBody.fAdditionalDamp));
30215 end else begin
30216 RigidBody.fAngularVelocity:=Vector3Origin;
30217 end;
30218 end;
30219 end;
30220
30221 end;
30222
30223 // Transfer velocities
30224 SolverVelocity:[email protected][Index];
30225 SolverVelocity^.LinearVelocity:=RigidBody.fLinearVelocity;
30226 SolverVelocity^.AngularVelocity:=RigidBody.fAngularVelocity;
30227
30228 // Transfer positions
30229 SolverPosition:[email protected][Index];
30230 SolverPosition^.Position:=Position;
30231 SolverPosition^.Orientation:=Orientation;
30232
30233 // Transfer linear factors
30234 fSolver.fLinearFactors[Index]:=RigidBody.fLinearFactor;
30235
30236 end;
30237
30238 fSolver.Initialize(TimeStep);
30239
30240 fSolver.InitializeConstraints;
30241
30242 if fPhysics.fWarmStarting then begin
30243 fSolver.WarmStart;
30244 end;
30245
30246 for Index:=0 to fCountConstraints-1 do begin
30247 Constraint:=fConstraints[Index];
30248 if assigned(Constraint) then begin
30249 Constraint.InitializeConstraintsAndWarmStart(self,TimeStep);
30250 end;
30251 end;
30252 for Iteration:=1 to Max(fPhysics.fVelocityIterations,fPhysics.fSpeculativeIterations) do begin
30253 if Iteration<=fPhysics.fVelocityIterations then begin
30254 for Index:=0 to fCountConstraints-1 do begin
30255 Constraint:=fConstraints[Index];
30256 if assigned(Constraint) and not (kcfBreaked in Constraint.fFlags) then begin
30257 if ((Constraint.fFlags*[kcfActive,kcfBreakable,kcfBreaked])=[kcfActive,kcfBreakable]) and
30258 ((Vector3Length(Constraint.GetReactionForce(TimeStep.InverseDeltaTime))>Constraint.fBreakThresholdForce) or
30259 (Vector3Length(Constraint.GetReactionTorque(TimeStep.InverseDeltaTime))>Constraint.fBreakThresholdTorque)) then begin
30260 Constraint.fFlags:=Constraint.fFlags+[kcfBreaked,kcfFreshBreaked];
30261 continue;
30262 end;
30263 Constraint.SolveVelocityConstraint(self,TimeStep);
30264 end;
30265 end;
30266 fSolver.SolveVelocityConstraints;
30267 end;
30268 if (fSolver.fCountSpeculativeContacts>0) and (Iteration<=fPhysics.fSpeculativeIterations) then begin
30269 fSolver.SolveSpeculativeContactConstraints;
30270 end;
30271 end;
30272 fSolver.StoreImpulses;
30273
30274 for Index:=0 to fCountRigidBodies-1 do begin
30275
30276 RigidBody:=fRigidBodies[Index];
30277
30278 if RigidBody.fRigidBodyType=krbtDynamic then begin
30279
30280 SolverPosition:[email protected][Index];
30281 Position:=SolverPosition^.Position;
30282 Orientation:=SolverPosition^.Orientation;
30283
30284 SolverVelocity:[email protected][Index];
30285 LinearVelocity:=SolverVelocity^.LinearVelocity;
30286 AngularVelocity:=SolverVelocity^.AngularVelocity;
30287
30288 // writeln(Vector3Length(LinearVelocity)*TimeStep.DeltaTime:1:8);
30289
30290 if fPhysics.fMaximalLinearVelocity>EPSILON then begin
30291 Translation:=Vector3ScalarMul(LinearVelocity,TimeStep.DeltaTime);
30292 if Vector3LengthSquared(Translation)>sqr(fPhysics.fMaximalLinearVelocity) then begin
30293 Vector3Scale(LinearVelocity,fPhysics.fMaximalLinearVelocity/Vector3Length(Translation));
30294 end;
30295 end;
30296 if RigidBody.fMaximalLinearVelocity>EPSILON then begin
30297 Translation:=Vector3ScalarMul(LinearVelocity,TimeStep.DeltaTime);
30298 if Vector3LengthSquared(Translation)>sqr(RigidBody.fMaximalLinearVelocity) then begin
30299 Vector3Scale(LinearVelocity,RigidBody.fMaximalLinearVelocity/Vector3Length(Translation));
30300 end;
30301 end;
30302
30303 if fPhysics.fMaximalAngularVelocity>EPSILON then begin
30304 Rotation:=Vector3ScalarMul(AngularVelocity,TimeStep.DeltaTime);
30305 if Vector3LengthSquared(Rotation)>sqr(fPhysics.fMaximalAngularVelocity) then begin
30306 Vector3Scale(AngularVelocity,fPhysics.fMaximalAngularVelocity/Vector3Length(Rotation));
30307 end;
30308 end;
30309 if RigidBody.fMaximalAngularVelocity>EPSILON then begin
30310 Rotation:=Vector3ScalarMul(AngularVelocity,TimeStep.DeltaTime);
30311 if Vector3LengthSquared(Rotation)>sqr(RigidBody.fMaximalAngularVelocity) then begin
30312 Vector3Scale(AngularVelocity,RigidBody.fMaximalAngularVelocity/Vector3Length(Rotation));
30313 end;
30314 end;
30315
30316 fPhysics.Integrate(Position,Orientation,LinearVelocity,AngularVelocity,TimeStep.DeltaTime);
30317
30318 SolverPosition^.Position:=Position;
30319 SolverPosition^.Orientation:=Orientation;
30320 SolverVelocity^.LinearVelocity:=LinearVelocity;
30321 SolverVelocity^.AngularVelocity:=AngularVelocity;
30322
30323 end;
30324
30325 end;
30326
30327 for Index:=0 to fCountConstraints-1 do begin
30328 Constraint:=fConstraints[Index];
30329 if assigned(Constraint) and
30330 (((Constraint.fFlags*[kcfActive,kcfBreakable,kcfBreaked])=[kcfActive,kcfBreakable]) and
30331 ((Vector3Length(Constraint.GetReactionForce(TimeStep.InverseDeltaTime))>Constraint.fBreakThresholdForce) or
30332 (Vector3Length(Constraint.GetReactionTorque(TimeStep.InverseDeltaTime))>Constraint.fBreakThresholdTorque))) then begin
30333 Constraint.fFlags:=Constraint.fFlags+[kcfBreaked,kcfFreshBreaked];
30334 end;
30335 end;
30336
30337 if (fPhysics.fContactPositionCorrectionMode=kpcmNonLinearGaussSeidel) or
30338 (fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel) then begin
30339 for Iteration:=1 to fPhysics.fPositionIterations do begin
30340 OK:=true;
30341 if (fPhysics.fContactPositionCorrectionMode=kpcmNonLinearGaussSeidel) and not fSolver.SolvePositionConstraints then begin
30342 OK:=false;
30343 end;
30344 if fPhysics.fConstraintPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
30345 for Index:=0 to fCountConstraints-1 do begin
30346 Constraint:=fConstraints[Index];
30347 if assigned(Constraint) and not (kcfBreaked in Constraint.fFlags) then begin
30348 if not Constraint.SolvePositionConstraint(self,TimeStep) then begin
30349 OK:=false;
30350 end;
30351 end;
30352 end;
30353 end;
30354 if OK then begin
30355 break;
30356 end;
30357 end;
30358 end;
30359
30360 for Index:=0 to fCountRigidBodies-1 do begin
30361 RigidBody:=fRigidBodies[Index];
30362 if RigidBody.fRigidBodyType=krbtDynamic then begin
30363
30364 SolverPosition:[email protected][Index];
30365 RigidBody.fSweep.c:=SolverPosition^.Position;
30366 RigidBody.fSweep.q:=SolverPosition^.Orientation;
30367
30368 SolverVelocity:[email protected][Index];
30369 RigidBody.fLinearVelocity:=SolverVelocity^.LinearVelocity;
30370 RigidBody.fAngularVelocity:=SolverVelocity^.AngularVelocity;
30371
30372 RigidBody.SynchronizeTransformIncludingShapes;
30373 RigidBody.UpdateWorldInertiaTensor;
30374 end;
30375 end;
30376
30377 if fPhysics.fAllowSleep then begin
30378
30379 // Find minimum sleep time of the entire island
30380 MinSleepTime:=3.40e+38;
30381 First:=true;
30382 for Index:=0 to fCountRigidBodies-1 do begin
30383 RigidBody:=fRigidBodies[Index];
30384 if RigidBody.fRigidBodyType<>krbtStatic then begin
30385 if (Vector3LengthSquared(RigidBody.fLinearVelocity)>sqr(fPhysics.fLinearVelocityThreshold)) or
30386 (Vector3LengthSquared(RigidBody.fAngularVelocity)>sqr(fPhysics.fAngularVelocityThreshold)) then begin
30387 MinSleepTime:=0.0;
30388 RigidBody.fSleepTime:=0.0;
30389 First:=false;
30390 end else if krbfAllowSleep in RigidBody.fFlags then begin
30391 RigidBody.fSleepTime:=RigidBody.fSleepTime+TimeStep.DeltaTime;
30392 if First or (MinSleepTime>RigidBody.fSleepTime) then begin
30393 First:=false;
30394 MinSleepTime:=RigidBody.fSleepTime;
30395 end;
30396 end;
30397 end;
30398 end;
30399
30400 // Put entire island to sleep so long as the minimum found sleep time is below the threshold.
30401 // If the minimum sleep time reaches below the sleeping threshold, the entire island will be
30402 // reformed next step and sleep test will be tried again.
30403 if MinSleepTime>fPhysics.fSleepTimeThreshold then begin
30404 for Index:=0 to fCountRigidBodies-1 do begin
30405 if krbfAllowSleep in fRigidBodies[Index].fFlags then begin
30406 fRigidBodies[Index].SetToSleep;
30407 end;
30408 end;
30409 end;
30410
30411 end;
30412
30413 end;
30414
30415 procedure TKraftIsland.SolveTimeOfImpact(const TimeStep:TKraftTimeStep;const IndexA,IndexB:longint);
30416 var Iteration,Index:longint;
30417 RigidBody:TKraftRigidBody;
30418 SolverVelocity:PKraftSolverVelocity;
30419 SolverPosition:PKraftSolverPosition;
30420 Position,LinearVelocity,AngularVelocity,Translation,Rotation:TKraftVector3;
30421 Orientation:TKraftQuaternion;
30422 begin
30423
30424 fSolver.Store;
30425
30426 // Integrate velocities and create state buffers
30427 for Index:=0 to fCountRigidBodies-1 do begin
30428 RigidBody:=fRigidBodies[Index];
30429 SolverVelocity:[email protected][Index];
30430 SolverVelocity^.LinearVelocity:=RigidBody.fLinearVelocity;
30431 SolverVelocity^.AngularVelocity:=RigidBody.fAngularVelocity;
30432 SolverPosition:[email protected][Index];
30433 SolverPosition^.Position:=RigidBody.fSweep.c;
30434 SolverPosition^.Orientation:=RigidBody.fSweep.q;
30435 end;
30436
30437 fSolver.Initialize(TimeStep);
30438
30439 for Iteration:=0 to fPhysics.fTimeOfImpactIterations-1 do begin
30440 if fSolver.SolveTimeOfImpactConstraints(IndexA,IndexB) then begin
30441 break;
30442 end;
30443 end;
30444
30445 // Leap of faith to new safe state.
30446 for Index:=0 to fCountRigidBodies-1 do begin
30447 RigidBody:=fRigidBodies[Index];
30448 if RigidBody.fRigidBodyType=krbtDynamic then begin
30449 SolverPosition:[email protected][Index];
30450 RigidBody.fSweep.c0:=SolverPosition^.Position;
30451 RigidBody.fSweep.q0:=SolverPosition^.Orientation;
30452 end;
30453 end;
30454
30455 fSolver.InitializeConstraints;
30456
30457 // No warm starting is needed for TOI events because warm
30458 // starting impulses were applied in the discrete solver.
30459
30460 for Iteration:=0 to fPhysics.fVelocityIterations-1 do begin
30461 fSolver.SolveVelocityConstraints;
30462 end;
30463
30464 // Don't store the TOI contact forces for warm starting
30465 // because they can be quite large.
30466
30467 for Index:=0 to fCountRigidBodies-1 do begin
30468
30469 RigidBody:=fRigidBodies[Index];
30470
30471 if RigidBody.fRigidBodyType=krbtDynamic then begin
30472
30473 SolverPosition:[email protected][Index];
30474 Position:=SolverPosition^.Position;
30475 Orientation:=SolverPosition^.Orientation;
30476
30477 SolverVelocity:[email protected][Index];
30478 LinearVelocity:=SolverVelocity^.LinearVelocity;
30479 AngularVelocity:=SolverVelocity^.AngularVelocity;
30480
30481 if fPhysics.fMaximalLinearVelocity>EPSILON then begin
30482 Translation:=Vector3ScalarMul(LinearVelocity,TimeStep.DeltaTime);
30483 if Vector3LengthSquared(Translation)>sqr(fPhysics.fMaximalLinearVelocity) then begin
30484 Vector3Scale(LinearVelocity,fPhysics.fMaximalLinearVelocity/Vector3Length(Translation));
30485 end;
30486 end;
30487 if RigidBody.fMaximalLinearVelocity>EPSILON then begin
30488 Translation:=Vector3ScalarMul(LinearVelocity,TimeStep.DeltaTime);
30489 if Vector3LengthSquared(Translation)>sqr(RigidBody.fMaximalLinearVelocity) then begin
30490 Vector3Scale(LinearVelocity,RigidBody.fMaximalLinearVelocity/Vector3Length(Translation));
30491 end;
30492 end;
30493
30494 if fPhysics.fMaximalAngularVelocity>EPSILON then begin
30495 Rotation:=Vector3ScalarMul(AngularVelocity,TimeStep.DeltaTime);
30496 if Vector3LengthSquared(Rotation)>sqr(fPhysics.fMaximalAngularVelocity) then begin
30497 Vector3Scale(AngularVelocity,fPhysics.fMaximalAngularVelocity/Vector3Length(Rotation));
30498 end;
30499 end;
30500 if RigidBody.fMaximalAngularVelocity>EPSILON then begin
30501 Rotation:=Vector3ScalarMul(AngularVelocity,TimeStep.DeltaTime);
30502 if Vector3LengthSquared(Rotation)>sqr(RigidBody.fMaximalAngularVelocity) then begin
30503 Vector3Scale(AngularVelocity,RigidBody.fMaximalAngularVelocity/Vector3Length(Rotation));
30504 end;
30505 end;
30506
30507 fPhysics.Integrate(Position,Orientation,LinearVelocity,AngularVelocity,TimeStep.DeltaTime);
30508
30509 RigidBody.fSweep.c:=Position;
30510 RigidBody.fSweep.q:=Orientation;
30511
30512 RigidBody.fLinearVelocity:=LinearVelocity;
30513 RigidBody.fAngularVelocity:=AngularVelocity;
30514
30515 RigidBody.SynchronizeTransformIncludingShapes;
30516 RigidBody.UpdateWorldInertiaTensor;
30517 end;
30518 end;
30519
30520 end;
30521
30522 {$ifndef KraftPasMP}
30523 constructor TKraftJobThread.Create(const APhysics:TKraft;const AJobManager:TKraftJobManager;const AThreadNumber:longint);
30524 begin
30525 //{$ifdef memdebug}ScanMemoryPoolForCorruptions;{$endif}
30526 fPhysics:=APhysics;
30527 fJobManager:=AJobManager;
30528 fThreadNumber:=AThreadNumber;
30529 fEvent:=TEvent.Create(nil,false,false,'');
30530 fDoneEvent:=TEvent.Create(nil,false,false,'');
30531 //{$ifdef memdebug}ScanMemoryPoolForCorruptions;{$endif}
30532 inherited Create(false);
30533 end;
30534
30535 destructor TKraftJobThread.Destroy;
30536 begin
30537 //{$ifdef memdebug}ScanMemoryPoolForCorruptions;{$endif}
30538 FreeAndNil(fEvent);
30539 FreeAndNil(fDoneEvent);
30540 //{$ifdef memdebug}ScanMemoryPoolForCorruptions;{$endif}
30541 inherited Destroy;
30542 end;
30543
30544 procedure TKraftJobThread.Execute;
30545 var JobIndex:longint;
30546 begin
30547 {$ifdef HAS_FPU_TYPES}
30548 SetPrecisionMode(PhysicsFPUPrecisionMode);
30549 SetExceptionMask(PhysicsFPUExceptionMask);
30550 {$endif}
30551 SIMDSetOurFlags;
30552 InterlockedIncrement(fJobManager.fCountAliveThreads);
30553 while not (Terminated or fJobManager.fThreadsTerminated) do begin
30554 fEvent.WaitFor(INFINITE);
30555 if Terminated or fJobManager.fThreadsTerminated then begin
30556 break;
30557 end else begin
30558 repeat
30559 JobIndex:=InterlockedDecrement(fJobManager.fCountRemainJobs);
30560 if JobIndex>=0 then begin
30561 if assigned(fJobManager.fOnProcessJob) then begin
30562 fJobManager.fOnProcessJob(JobIndex,fThreadNumber);
30563 end;
30564 end else begin
30565 break;
30566 end;
30567 until false;
30568 fDoneEvent.SetEvent;
30569 end;
30570 end;
30571 InterlockedDecrement(fJobManager.fCountAliveThreads);
30572 end;
30573
30574 constructor TKraftJobManager.Create(const APhysics:TKraft);
30575 var Index:longint;
30576 begin
30577 inherited Create;
30578 fPhysics:=APhysics;
30579 fThreads:=nil;
30580 fCountThreads:=APhysics.fCountThreads;
30581 SetLength(fThreads,fCountThreads);
30582 fCountAliveThreads:=0;
30583 fGranularity:=1;
30584 fThreadsTerminated:=false;
30585 fOnProcessJob:=nil;
30586 for Index:=0 to fCountThreads-1 do begin
30587 fThreads[Index]:=TKraftJobThread.Create(fPhysics,self,Index);
30588 {$if defined(FPC) or defined(MSWINDOWS)}
30589 fThreads[Index].Priority:=tpHigher;
30590 {$ifend}
30591 end;
30592 end;
30593
30594 destructor TKraftJobManager.Destroy;
30595 var Index:longint;
30596 begin
30597 fThreadsTerminated:=true;
30598 for Index:=0 to fCountThreads-1 do begin
30599 fThreads[Index].Terminate;
30600 fThreads[Index].fEvent.SetEvent;
30601 fThreads[Index].WaitFor;
30602 FreeAndNil(fThreads[Index]);
30603 end;
30604 SetLength(fThreads,0);
30605 inherited Destroy;
30606 end;
30607
30608 procedure TKraftJobManager.WakeUp;
30609 var Index:longint;
30610 begin
30611 for Index:=0 to fCountThreads-1 do begin
30612 fThreads[Index].fEvent.SetEvent;
30613 end;
30614 end;
30615
30616 procedure TKraftJobManager.WaitFor;
30617 var Index:longint;
30618 begin
30619 for Index:=0 to fCountThreads-1 do begin
30620 fThreads[Index].fDoneEvent.WaitFor(INFINITE);
30621 end;
30622 end;
30623
30624 procedure TKraftJobManager.ProcessJobs;
30625 begin
30626 WakeUp;
30627 WaitFor;
30628 end;
30629 {$endif}
30630
30631 {$ifdef KraftPasMP}
30632 constructor TKraft.Create(const APasMP:TPasMP);
30633 {$else}
30634 constructor TKraft.Create(const ACountThreads:longint=-1);
30635 {$endif}
30636 const TriangleVertex0:TKraftVector3=(x:0.0;y:0.0;z:0.0{$ifdef SIMD};w:0.0{$endif});
30637 TriangleVertex1:TKraftVector3=(x:1.0;y:0.0;z:0.01{$ifdef SIMD};w:0.0{$endif});
30638 TriangleVertex2:TKraftVector3=(x:0.0;y:1.0;z:0.02{$ifdef SIMD};w:0.0{$endif});
30639 var Index:longint;
30640 {$ifndef KraftPasMP}
30641 {$ifdef win32}
30642 i,j:longint;
30643 sinfo:SYSTEM_INFO;
30644 dwProcessAffinityMask,dwSystemAffinityMask:ptruint;
30645 function GetRealCountOfCPUCores:longint; {$ifdef caninline}inline;{$endif}
30646 const RelationProcessorCore=0;
30647 RelationNumaNode=1;
30648 RelationCache=2;
30649 RelationProcessorPackage=3;
30650 RelationGroup=4;
30651 RelationAll=$ffff;
30652 CacheUnified=0;
30653 CacheInstruction=1;
30654 CacheData=2;
30655 CacheTrace=3;
30656 type TLogicalProcessorRelationship=dword;
30657 TProcessorCacheType=dword;
30658 TCacheDescriptor=packed record
30659 Level:byte;
30660 Associativity:byte;
30661 LineSize:word;
30662 Size:dword;
30663 pcType:TProcessorCacheType;
30664 end;
30665 PSystemLogicalProcessorInformation=^TSystemLogicalProcessorInformation;
30666 TSystemLogicalProcessorInformation=packed record
30667 ProcessorMask:ptruint;
30668 case Relationship:TLogicalProcessorRelationship of
30669 0:(
30670 Flags:byte;
30671 );
30672 1:(
30673 NodeNumber:dword;
30674 );
30675 2:(
30676 Cache:TCacheDescriptor;
30677 );
30678 3:(
30679 Reserved:array[0..1] of int64;
30680 );
30681 end;
30682 TGetLogicalProcessorInformation=function(Buffer:PSystemLogicalProcessorInformation;out ReturnLength:DWORD):BOOL; stdcall;
30683 var GetLogicalProcessorInformation:TGetLogicalProcessorInformation;
30684 Buffer:array of TSystemLogicalProcessorInformation;
30685 ReturnLength:dword;
30686 Index,Count:longint;
30687 begin
30688 result:=-1;
30689 Buffer:=nil;
30690 try
30691 GetLogicalProcessorInformation:=GetProcAddress(GetModuleHandle('kernel32'),'GetLogicalProcessorInformation');
30692 if assigned(GetLogicalProcessorInformation) then begin
30693 SetLength(Buffer,16);
30694 Count:=0;
30695 repeat
30696 ReturnLength:=length(Buffer)*SizeOf(TSystemLogicalProcessorInformation);
30697 if GetLogicalProcessorInformation(@Buffer[0],ReturnLength) then begin
30698 Count:=ReturnLength div SizeOf(TSystemLogicalProcessorInformation);
30699 end else begin
30700 if GetLastError=ERROR_INSUFFICIENT_BUFFER then begin
30701 SetLength(Buffer,(ReturnLength div SizeOf(TSystemLogicalProcessorInformation))+1);
30702 continue;
30703 end;
30704 end;
30705 break;
30706 until false;
30707 if Count>0 then begin
30708 result:=0;
30709 for Index:=0 to Count-1 do begin
30710 if Buffer[Index].Relationship=RelationProcessorCore then begin
30711 inc(result);
30712 end;
30713 end;
30714 end;
30715 end;
30716 finally
30717 SetLength(Buffer,0);
30718 end;
30719 end;
30720 {$endif}
30721 {$endif}
30722 begin
30723 inherited Create;
30724
30725 fSingleThreaded:=false;
30726
30727 fHighResolutionTimer:=TKraftHighResolutionTimer.Create;
30728
30729 fIsSolving:=false;
30730
30731 {$ifdef KraftPasMP}
30732 fPasMP:=APasMP;
30733
30734 fCountThreads:=fPasMP.CountJobWorkerThreads;
30735 {$else}
30736
30737 fCountThreads:=ACountThreads;
30738
30739 {$ifdef win32}
30740 if fCountThreads<0 then begin
30741 fCountThreads:=GetRealCountOfCPUCores;
30742 GetSystemInfo(sinfo);
30743 GetProcessAffinityMask(GetCurrentProcess,dwProcessAffinityMask,dwSystemAffinityMask);
30744 j:=0;
30745 for i:=0 to sinfo.dwNumberOfProcessors-1 do begin
30746 if (dwProcessAffinityMask and (1 shl i))<>0 then begin
30747 inc(j);
30748 if j>=MAX_THREADS then begin
30749 break;
30750 end;
30751 end;
30752 end;
30753 if (fCountThreads<0) or (fCountThreads>j) then begin
30754 fCountThreads:=j;
30755 end;
30756 end;
30757 //SetThreadIdealProcessor(GetCurrentThread,0);
30758 {$endif}
30759
30760 fCountThreads:=Min(Max(fCountThreads,0),MAX_THREADS);
30761 {$endif}
30762
30763 fNewShapes:=false;
30764
30765 fConvexHullFirst:=nil;
30766 fConvexHullLast:=nil;
30767
30768 fMeshFirst:=nil;
30769 fMeshLast:=nil;
30770
30771 fConstraintFirst:=nil;
30772 fConstraintLast:=nil;
30773
30774 fCountRigidBodies:=0;
30775 fRigidBodyIDCounter:=0;
30776
30777 fRigidBodyFirst:=nil;
30778 fRigidBodyLast:=nil;
30779
30780 fStaticRigidBodyCount:=0;
30781
30782 fStaticRigidBodyFirst:=nil;
30783 fStaticRigidBodyLast:=nil;
30784
30785 fDynamicRigidBodyCount:=0;
30786
30787 fDynamicRigidBodyFirst:=nil;
30788 fDynamicRigidBodyLast:=nil;
30789
30790 fKinematicRigidBodyCount:=0;
30791
30792 fKinematicRigidBodyFirst:=nil;
30793 fKinematicRigidBodyLast:=nil;
30794
30795 fStaticAABBTree:=TKraftDynamicAABBTree.Create;
30796 fSleepingAABBTree:=TKraftDynamicAABBTree.Create;
30797 fDynamicAABBTree:=TKraftDynamicAABBTree.Create;
30798 fKinematicAABBTree:=TKraftDynamicAABBTree.Create;
30799
30800 fIslands:=nil;
30801 SetLength(fIslands,16);
30802 for Index:=0 to length(fIslands)-1 do begin
30803 fIslands[Index]:=TKraftIsland.Create(self,Index);
30804 end;
30805 fCountIslands:=0;
30806
30807 fBroadPhase:=TKraftBroadPhase.Create(self);
30808
30809 fContactManager:=TKraftContactManager.Create(self);
30810
30811 fWorldFrequency:=60.0;
30812
30813 fWorldDeltaTime:=1.0/fWorldFrequency;
30814
30815 fWorldInverseDeltaTime:=fWorldFrequency;
30816
30817 fLastInverseDeltaTime:=0.0;
30818
30819 fAllowSleep:=true;
30820
30821 fAllowedPenetration:=0.0;
30822
30823 fGravity.x:=0.0;
30824 fGravity.y:=-9.83;
30825 fGravity.z:=0.0;
30826
30827 fGravityProperty:=TKraftVector3Property.Create(@fGravity);
30828
30829 fMaximalLinearVelocity:=2.0;
30830
30831 fMaximalAngularVelocity:=pi*0.5;
30832
30833 fLinearVelocityThreshold:=0.1;
30834
30835 fAngularVelocityThreshold:=2.0*(pi/180.0);
30836
30837 fSleepTimeThreshold:=0.5;
30838
30839 fVelocityThreshold:=1.0;
30840
30841 fContactBaumgarte:=0.2;
30842
30843 fConstraintBaumgarte:=0.2;
30844
30845 fTimeOfImpactBaumgarte:=0.75;
30846
30847 fPenetrationSlop:=0.05;
30848
30849 fLinearSlop:=0.005;
30850
30851 fAngularSlop:=(2.0/180.0)*pi;
30852
30853 fMaximalLinearCorrection:=0.2;
30854
30855 fMaximalAngularCorrection:=(8.0/180.0)*pi;
30856
30857 fWarmStarting:=true;
30858
30859 fContinuousMode:=kcmNone;
30860 //fContinuousMode:=kcmMotionClamping;
30861 //fContinuousMode:=kcmTimeOfImpactSubSteps;
30862
30863 fContinuousAgainstDynamics:=false;
30864
30865 //fTimeOfImpactAlgorithm:=ktoiaConservativeAdvancement;
30866 fTimeOfImpactAlgorithm:=ktoiaBilateralAdvancement;
30867
30868 fMaximalSubSteps:=16;
30869
30870 fContactPositionCorrectionMode:=kpcmNonLinearGaussSeidel;
30871
30872 fConstraintPositionCorrectionMode:=kpcmNonLinearGaussSeidel;
30873
30874 fVelocityIterations:=8;
30875
30876 fPositionIterations:=3;
30877
30878 fSpeculativeIterations:=8;
30879
30880 fTimeOfImpactIterations:=20;
30881
30882 fPerturbationIterations:=MAX_CONTACTS;
30883
30884 fPersistentContactManifold:=false;
30885
30886 fAlwaysPerturbating:=false;
30887
30888 fEnableFriction:=true;
30889
30890 fLinearVelocityRK4Integration:=false;
30891
30892 fAngularVelocityRK4Integration:=false;
30893
30894 fContactBreakingThreshold:=0.02;
30895
30896 fTriangleShapes:=nil;
30897 SetLength(fTriangleShapes,Max(1,fCountThreads));
30898 for Index:=0 to length(fTriangleShapes)-1 do begin
30899 fTriangleShapes[Index]:=TKraftShapeTriangle.Create(self,nil,TriangleVertex0,TriangleVertex1,TriangleVertex2);
30900 fTriangleShapes[Index].UpdateShapeAABB;
30901 fTriangleShapes[Index].CalculateMassData;
30902 end;
30903
30904 {$ifndef KraftPasMP}
30905 if fCountThreads>1 then begin
30906 fJobManager:=TKraftJobManager.Create(self);
30907 end else begin
30908 fJobManager:=nil;
30909 end;
30910 {$endif}
30911
30912 SIMDSetOurFlags;
30913
30914 end;
30915
30916 destructor TKraft.Destroy;
30917 var Index:longint;
30918 begin
30919
30920 {$ifndef KraftPasMP}
30921 if assigned(fJobManager) then begin
30922 FreeAndNil(fJobManager);
30923 end;
30924 {$endif}
30925
30926 for Index:=0 to length(fTriangleShapes)-1 do begin
30927 fTriangleShapes[Index].Free;
30928 end;
30929 SetLength(fTriangleShapes,0);
30930
30931 while assigned(fConstraintLast) do begin
30932 fConstraintLast.Free;
30933 end;
30934
30935 while assigned(fRigidBodyLast) do begin
30936 fRigidBodyLast.Free;
30937 end;
30938
30939 while assigned(fMeshLast) do begin
30940 fMeshLast.Free;
30941 end;
30942
30943 while assigned(fConvexHullLast) do begin
30944 fConvexHullLast.Free;
30945 end;
30946
30947 fBroadPhase.Free;
30948
30949 fStaticAABBTree.Free;
30950 fSleepingAABBTree.Free;
30951 fDynamicAABBTree.Free;
30952 fKinematicAABBTree.Free;
30953
30954 for Index:=0 to length(fIslands)-1 do begin
30955 fIslands[Index].Free;
30956 end;
30957 SetLength(fIslands,0);
30958
30959 fContactManager.Free;
30960
30961 fHighResolutionTimer.Free;
30962
30963 fGravityProperty.Free;
30964
30965 inherited Destroy;
30966 end;
30967
30968 procedure TKraft.SetFrequency(const AFrequency:TKraftScalar);
30969 begin
30970 fWorldFrequency:=AFrequency;
30971 fWorldDeltaTime:=1.0/fWorldFrequency;
30972 fWorldInverseDeltaTime:=fWorldFrequency;
30973 end;
30974
30975 procedure TKraft.Integrate(var Position:TKraftVector3;var Orientation:TKraftQuaternion;const LinearVelocity,AngularVelocity:TKraftVector3;const DeltaTime:TKraftScalar);
30976 const OneDiv3=1.0/3.0;
30977 OneDiv6=1.0/6.0;
30978 OneDiv24=1.0/24.0;
30979 var {ThetaLenSquared,ThetaLen,s,w,}DeltaTimeDiv6,DeltaTimeDiv3:TKraftScalar;
30980 // Theta:TKraftVector3;
30981 HalfSpinQuaternion:TKraftQuaternion;
30982 Quaternions:array[0..3] of TKraftQuaternion;
30983 Positions:array[0..3] of TKraftVector3;
30984 begin
30985
30986 DeltaTimeDiv6:=DeltaTime*OneDiv6;
30987 DeltaTimeDiv3:=DeltaTime*OneDiv3;
30988
30989 if fLinearVelocityRK4Integration then begin
30990 Positions[0]:=LinearVelocity;
30991 Positions[1]:=Vector3Add(Positions[0],Vector3ScalarMul(LinearVelocity,DeltaTime*0.5));
30992 Positions[2]:=Vector3Add(Positions[1],Vector3ScalarMul(LinearVelocity,DeltaTime*0.5));
30993 Positions[3]:=Vector3Add(Positions[2],Vector3ScalarMul(LinearVelocity,DeltaTime));
30994 Vector3DirectAdd(Position,
30995 Vector3Add(Vector3ScalarMul(Vector3Add(Positions[0],Positions[3]),DeltaTimeDiv6),
30996 Vector3ScalarMul(Vector3Add(Positions[1],Positions[2]),DeltaTimeDiv3)));
30997 end else begin
30998 Vector3DirectAdd(Position,Vector3ScalarMul(LinearVelocity,DeltaTime));
30999 end;
31000
31001 if fAngularVelocityRK4Integration then begin
31002 HalfSpinQuaternion.x:=AngularVelocity.x*0.5;
31003 HalfSpinQuaternion.y:=AngularVelocity.y*0.5;
31004 HalfSpinQuaternion.z:=AngularVelocity.z*0.5;
31005 HalfSpinQuaternion.w:=0;
31006 Quaternions[0]:=QuaternionMul(HalfSpinQuaternion,QuaternionTermNormalize(Orientation));
31007 Quaternions[1]:=QuaternionMul(HalfSpinQuaternion,QuaternionTermNormalize(QuaternionAdd(Orientation,QuaternionScalarMul(Quaternions[0],DeltaTime*0.5))));
31008 Quaternions[2]:=QuaternionMul(HalfSpinQuaternion,QuaternionTermNormalize(QuaternionAdd(Orientation,QuaternionScalarMul(Quaternions[1],DeltaTime*0.5))));
31009 Quaternions[3]:=QuaternionMul(HalfSpinQuaternion,QuaternionTermNormalize(QuaternionAdd(Orientation,QuaternionScalarMul(Quaternions[2],DeltaTime))));
31010 Orientation:=QuaternionTermNormalize(QuaternionAdd(Orientation,
31011 QuaternionAdd(QuaternionScalarMul(QuaternionAdd(Quaternions[0],Quaternions[3]),DeltaTimeDiv6),
31012 QuaternionScalarMul(QuaternionAdd(Quaternions[1],Quaternions[2]),DeltaTimeDiv3))));
31013 end else begin
31014 HalfSpinQuaternion.x:=AngularVelocity.x;
31015 HalfSpinQuaternion.y:=AngularVelocity.y;
31016 HalfSpinQuaternion.z:=AngularVelocity.z;
31017 HalfSpinQuaternion.w:=0;
31018 Orientation:=QuaternionTermNormalize(QuaternionAdd(Orientation,QuaternionMul(QuaternionScalarMul(HalfSpinQuaternion,DeltaTime*0.5),Orientation)));{}
31019 //Orientation:=QuaternionTermNormalize(QuaternionIntegrate(Orientation,AngularVelocity,DeltaTime));
31020 { Theta:=Vector3ScalarMul(AngularVelocity,DeltaTime*0.5);
31021 ThetaLenSquared:=Vector3LengthSquared(Theta);
31022 if (sqr(ThetaLenSquared)*OneDiv24)<EPSILON then begin
31023 w:=1.0-(ThetaLenSquared*0.5);
31024 s:=1.0-(ThetaLenSquared*OneDiv6);
31025 end else begin
31026 ThetaLen:=sqrt(ThetaLenSquared);
31027 w:=cos(ThetaLen);
31028 s:=sin(ThetaLen)/ThetaLen;
31029 end;
31030 Quaternions[0].x:=Theta.x*s;
31031 Quaternions[0].y:=Theta.y*s;
31032 Quaternions[0].z:=Theta.z*s;
31033 Quaternions[0].w:=w;
31034 Orientation:=QuaternionTermNormalize(QuaternionMul(Quaternions[0],Orientation));{}
31035 end;
31036
31037 end;
31038
31039 procedure TKraft.BuildIslands;
31040 var IslandIndex,LastCount,SubIndex:longint;
31041 SeedRigidBody,SeedRigidBodyStack,CurrentRigidBody,OtherRigidBody,StaticRigidBodiesList:TKraftRigidBody;
31042 CurrentConstraintEdge:PKraftConstraintEdge;
31043 CurrentConstraint:TKraftConstraint;
31044 Island:TKraftIsland;
31045 ContactPairEdge:PKraftContactPairEdge;
31046 ContactPair:PKraftContactPair;
31047 begin
31048
31049 if fCountRigidBodies>length(fIslands) then begin
31050 LastCount:=length(fIslands);
31051 SetLength(fIslands,fCountRigidBodies*2);
31052 for SubIndex:=LastCount to length(fIslands)-1 do begin
31053 fIslands[SubIndex]:=TKraftIsland.Create(self,SubIndex);
31054 end;
31055 end;
31056
31057 CurrentRigidBody:=fRigidBodyFirst;
31058 while assigned(CurrentRigidBody) do begin
31059 CurrentRigidBody.fIsland:=nil;
31060 CurrentRigidBody.fFlags:=CurrentRigidBody.fFlags-[krbfIslandVisited,krbfIslandStatic];
31061 //Exclude(ContactPair^.Flags,[krbfIslandVisited,krbfIslandStatic]);
31062 CurrentRigidBody:=CurrentRigidBody.fRigidBodyNext;
31063 end;
31064
31065 CurrentConstraint:=fConstraintFirst;
31066 while assigned(CurrentConstraint) do begin
31067 Exclude(CurrentConstraint.fFlags,kcfVisited);
31068 CurrentConstraint:=CurrentConstraint.fNext;
31069 end;
31070
31071 ContactPair:=fContactManager.fContactPairFirst;
31072 while assigned(ContactPair) do begin
31073 ContactPair.Island:=nil;
31074 Exclude(ContactPair^.Flags,kcfInIsland);
31075 ContactPair:=ContactPair^.Next;
31076 end;
31077
31078 fCountIslands:=0;
31079
31080 SeedRigidBody:=fRigidBodyFirst;
31081 while assigned(SeedRigidBody) do begin
31082
31083 if (krbfIslandVisited in SeedRigidBody.fFlags) or // Seed can't be visited and apart of an island already
31084 ((SeedRigidBody.fFlags*[krbfAwake,krbfActive])<>[krbfAwake,krbfActive]) or // Seed must be awake
31085 (SeedRigidBody.fRigidBodyType=krbtStatic) then begin // Seed can't be a static body in order to keep islands as small as possible
31086 SeedRigidBody:=SeedRigidBody.fRigidBodyNext;
31087 continue;
31088 end;
31089
31090 // Allocate island
31091 IslandIndex:=fCountIslands;
31092 inc(fCountIslands);
31093 if fCountIslands>length(fIslands) then begin
31094 LastCount:=length(fIslands);
31095 SetLength(fIslands,fCountIslands*2);
31096 for SubIndex:=LastCount to length(fIslands)-1 do begin
31097 fIslands[SubIndex]:=TKraftIsland.Create(self,SubIndex);
31098 end;
31099 end;
31100 Island:=fIslands[IslandIndex];
31101 Island.Clear;
31102
31103 StaticRigidBodiesList:=nil;
31104
31105 // Add first rigid body to the stack
31106 Include(SeedRigidBody.fFlags,krbfIslandVisited);
31107 SeedRigidBody.fNextOnIslandBuildStack:=nil;
31108 SeedRigidBodyStack:=SeedRigidBody;
31109
31110 // Process seed rigid body loop
31111 while assigned(SeedRigidBodyStack) do begin
31112
31113 // Pop next rigid body from the stack
31114 CurrentRigidBody:=SeedRigidBodyStack;
31115 SeedRigidBodyStack:=CurrentRigidBody.fNextOnIslandBuildStack;
31116 CurrentRigidBody.fNextOnIslandBuildStack:=nil;
31117
31118 // Add to the island
31119 Island.AddRigidBody(CurrentRigidBody);
31120
31121 // Awaken all bodies connected to the island
31122 CurrentRigidBody.SetToAwake;
31123
31124 // Do not search across static bodies to keep island formations as small as possible, however the static
31125 // body itself should be apart of the island in order to properly represent a full contact
31126 if CurrentRigidBody.fRigidBodyType=krbtStatic then begin
31127
31128 if not (krbfIslandStatic in CurrentRigidBody.fFlags) then begin
31129 Include(CurrentRigidBody.fFlags,krbfIslandStatic);
31130 CurrentRigidBody.fNextStaticRigidBody:=StaticRigidBodiesList;
31131 StaticRigidBodiesList:=CurrentRigidBody;
31132 end;
31133
31134 continue;
31135 end;
31136
31137 // Process all contact pairs
31138 if not (krbfSensor in CurrentRigidBody.fFlags) then begin
31139 ContactPairEdge:=CurrentRigidBody.fContactPairEdgeFirst;
31140 while assigned(ContactPairEdge) do begin
31141 ContactPair:=ContactPairEdge^.ContactPair;
31142 // Skip contacts that have been added to an island already and we can safely skip contacts if these didn't actually collide with anything,
31143 // and skip also sensors
31144 if ((ContactPair^.Flags*[kcfColliding,kcfInIsland])=[kcfColliding]) and
31145 not ((krbfSensor in ContactPairEdge^.OtherRigidBody.fFlags) or
31146 (ksfSensor in ContactPair^.Shapes[0].fFlags) or
31147 (ksfSensor in ContactPair^.Shapes[1].fFlags)) then begin
31148 ContactPair^.Flags:=ContactPair^.Flags+[kcfInIsland];
31149 Island.AddContactPair(ContactPair);
31150 OtherRigidBody:=ContactPairEdge^.OtherRigidBody;
31151 if assigned(OtherRigidBody) and ((OtherRigidBody.fFlags*[krbfIslandVisited,krbfSensor])=[]) then begin
31152 Include(OtherRigidBody.fFlags,krbfIslandVisited);
31153 OtherRigidBody.fNextOnIslandBuildStack:=SeedRigidBodyStack;
31154 SeedRigidBodyStack:=OtherRigidBody;
31155 end;
31156 end;
31157 ContactPairEdge:=ContactPairEdge^.Next;
31158 end;
31159 end;
31160
31161 // Process all collected constraints
31162 CurrentConstraintEdge:=CurrentRigidBody.fConstraintEdgeFirst;
31163 while assigned(CurrentConstraintEdge) do begin
31164 CurrentConstraint:=CurrentConstraintEdge^.Constraint;
31165 if (assigned(CurrentConstraint) and not (kcfVisited in CurrentConstraint.fFlags)) and ((CurrentConstraint.fFlags*[kcfActive,kcfBreaked])=[kcfActive]) then begin
31166 Include(CurrentConstraint.fFlags,kcfVisited);
31167 Island.AddConstraint(CurrentConstraint);
31168 OtherRigidBody:=CurrentConstraintEdge^.OtherRigidBody;
31169 if (OtherRigidBody<>CurrentRigidBody) and assigned(OtherRigidBody) and ((OtherRigidBody.fFlags*[krbfIslandVisited,krbfSensor])=[]) then begin
31170 Include(OtherRigidBody.fFlags,krbfIslandVisited);
31171 OtherRigidBody.fNextOnIslandBuildStack:=SeedRigidBodyStack;
31172 SeedRigidBodyStack:=OtherRigidBody;
31173 end;
31174 end;
31175 CurrentConstraintEdge:=CurrentConstraintEdge^.Next;
31176 end;
31177
31178 end;
31179
31180 Island.MergeContactPairs;
31181
31182 // Allow static bodies and with these collected constraints to participate in other islands
31183 while assigned(StaticRigidBodiesList) do begin
31184 CurrentRigidBody:=StaticRigidBodiesList;
31185 CurrentConstraintEdge:=CurrentRigidBody.fConstraintEdgeFirst;
31186 while assigned(CurrentConstraintEdge) do begin
31187 CurrentConstraint:=CurrentConstraintEdge^.Constraint;
31188 if assigned(CurrentConstraint) then begin
31189 Exclude(CurrentConstraint.fFlags,kcfVisited);
31190 end;
31191 CurrentConstraintEdge:=CurrentConstraintEdge^.Next;
31192 end;
31193 StaticRigidBodiesList:=CurrentRigidBody.fNextStaticRigidBody;
31194 CurrentRigidBody.fFlags:=CurrentRigidBody.fFlags-[krbfIslandVisited,krbfIslandStatic];
31195 end;
31196
31197 SeedRigidBody:=SeedRigidBody.fRigidBodyNext;
31198
31199 end;
31200
31201 end;
31202
31203 {$ifdef KraftPasMP}
31204 procedure TKraft.ProcessSolveIslandParallelForFunction(const Job:PPasMPJob;const ThreadIndex:longint;const Data:pointer;const FromIndex,ToIndex:TPasMPNativeInt);
31205 var Index:longint;
31206 begin
31207 for Index:=FromIndex to ToIndex do begin
31208 fIslands[Index].Solve(fJobTimeStep);
31209 end;
31210 end;
31211 {$else}
31212 procedure TKraft.ProcessSolveIslandJob(const JobIndex,ThreadIndex:longint);
31213 begin
31214 fIslands[JobIndex].Solve(fJobTimeStep);
31215 end;
31216 {$endif}
31217
31218 procedure TKraft.SolveIslands(const TimeStep:TKraftTimeStep);
31219 var Index:longint;
31220 begin
31221 fJobTimeStep:=TimeStep;
31222 fIsSolving:=true;
31223 {$ifdef KraftPasMP}
31224 if assigned(fPasMP) and (fCountIslands>1) and not fSingleThreaded then begin
31225 fPasMP.Invoke(fPasMP.ParallelFor(nil,0,fCountIslands-1,ProcessSolveIslandParallelForFunction,Max(1,fCountIslands div (fCountThreads*16)),4));
31226 {$else}
31227 if assigned(fJobManager) and (fCountIslands>1) and not fSingleThreaded then begin
31228 fJobManager.fOnProcessJob:=ProcessSolveIslandJob;
31229 fJobManager.fCountRemainJobs:=fCountIslands;
31230 fJobManager.fGranularity:=Max(1,fCountIslands div (fCountThreads*16));
31231 fJobManager.ProcessJobs;
31232 {$endif}
31233 end else begin
31234 for Index:=0 to fCountIslands-1 do begin
31235 fIslands[Index].Solve(fJobTimeStep);
31236 end;
31237 end;
31238 fIsSolving:=false;
31239 end;
31240
31241 // Conservative advancement
31242 function TKraft.GetConservativeAdvancementTimeOfImpact(const ShapeA:TKraftShape;const SweepA:TKraftSweep;const ShapeB:TKraftShape;const ShapeBTriangleIndex:longint;const SweepB:TKraftSweep;const TimeStep:TKraftTimeStep;const ThreadIndex:longint;var Beta:TKraftScalar):boolean;
31243 const Radius=1e-3;
31244 var Tries:longint;
31245 BoundingRadiusA,BoundingRadiusB,MaximumAngularProjectedVelocity,RelativeLinearVelocityLength,Lambda,LastLambda,
31246 ProjectedLinearVelocity,DistanceLambda,Distance,ContinuousMinimumRadiusScaleFactor:TKraftScalar;
31247 MeshShape:TKraftShapeMesh;
31248 MeshTriangle:PKraftMeshTriangle;
31249 ShapeTriangle:TKraftShapeTriangle;
31250 Shapes:array[0..1] of TKraftShape;
31251 RelativeLinearVelocity:TKraftVector3;
31252 LinearVelocities,AngularVelocities:array[0..1] of TKraftVector3;
31253 Transforms:array[0..1] of TKraftMatrix4x4;
31254 GJK:TKraftGJK;
31255 GJKCachedSimplex:TKraftGJKCachedSimplex;
31256 begin
31257
31258 result:=false;
31259
31260 Shapes[0]:=ShapeA;
31261
31262 if (ShapeBTriangleIndex>=0) and (ShapeB is TKraftShapeMesh) then begin
31263 MeshShape:=TKraftShapeMesh(ShapeB);
31264 ShapeTriangle:=TKraftShapeTriangle(fTriangleShapes[ThreadIndex]);
31265 Shapes[1]:=ShapeTriangle;
31266 MeshTriangle:[email protected][ShapeBTriangleIndex];
31267 ShapeTriangle.fLocalTransform:=MeshShape.fLocalTransform;
31268 ShapeTriangle.fWorldTransform:=MeshShape.fWorldTransform;
31269 ShapeTriangle.fConvexHull.fVertices[0].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[0]];
31270 ShapeTriangle.fConvexHull.fVertices[1].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[1]];
31271 ShapeTriangle.fConvexHull.fVertices[2].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[2]];
31272 ShapeTriangle.UpdateData;
31273 end else begin
31274 Shapes[1]:=ShapeB;
31275 end;
31276
31277 CalculateVelocity(SweepA.c0,SweepA.q0,SweepA.c,SweepA.q,1.0,LinearVelocities[0],AngularVelocities[0]);
31278 CalculateVelocity(SweepB.c0,SweepB.q0,SweepB.c,SweepB.q,1.0,LinearVelocities[1],AngularVelocities[1]);
31279
31280 BoundingRadiusA:=Shapes[0].fAngularMotionDisc;
31281 BoundingRadiusB:=Shapes[1].fAngularMotionDisc;
31282
31283 MaximumAngularProjectedVelocity:=((Vector3Length(AngularVelocities[0])*BoundingRadiusA)+(Vector3Length(AngularVelocities[1])*BoundingRadiusB));
31284
31285 RelativeLinearVelocity:=Vector3Sub(LinearVelocities[1],LinearVelocities[0]);
31286
31287 RelativeLinearVelocityLength:=Vector3Length(RelativeLinearVelocity);
31288
31289 if abs(RelativeLinearVelocityLength+MaximumAngularProjectedVelocity)<EPSILON then begin
31290 exit;
31291 end;
31292
31293 ContinuousMinimumRadiusScaleFactor:=Max(ShapeA.fContinuousMinimumRadiusScaleFactor,ShapeB.fContinuousMinimumRadiusScaleFactor);
31294
31295 if (ContinuousMinimumRadiusScaleFactor>EPSILON) and
31296 (RelativeLinearVelocityLength<Max(EPSILON,Min(Shapes[0].fShapeSphere.Radius,Shapes[1].fShapeSphere.Radius)*ContinuousMinimumRadiusScaleFactor)) then begin
31297 exit;
31298 end;
31299
31300 Lambda:=0.0;
31301
31302 LastLambda:=Lambda;
31303
31304 GJKCachedSimplex.Count:=0;
31305
31306 GJK.CachedSimplex:=@GJKCachedSimplex;
31307 GJK.Simplex.Count:=0;
31308 GJK.Shapes[0]:=Shapes[0];
31309 GJK.Shapes[1]:=Shapes[1];
31310 GJK.Transforms[0]:=@Transforms[0];
31311 GJK.Transforms[1]:=@Transforms[1];
31312 GJK.UseRadii:=true;
31313
31314 Transforms[0]:=Matrix4x4TermMul(Shapes[0].fLocalTransform,SweepTransform(SweepA,0.0));
31315 Transforms[1]:=Matrix4x4TermMul(Shapes[1].fLocalTransform,SweepTransform(SweepB,0.0));
31316
31317 if GJK.Run then begin
31318
31319 Distance:=GJK.Distance+fAllowedPenetration;
31320
31321 ProjectedLinearVelocity:=Vector3Dot(RelativeLinearVelocity,GJK.Normal);
31322 if (ProjectedLinearVelocity+MaximumAngularProjectedVelocity)<=EPSILON then begin
31323 exit;
31324 end;
31325
31326 Tries:=0;
31327
31328 while Distance>Radius do begin
31329
31330 ProjectedLinearVelocity:=Vector3Dot(RelativeLinearVelocity,GJK.Normal);
31331 if (ProjectedLinearVelocity+MaximumAngularProjectedVelocity)<=EPSILON then begin
31332 exit;
31333 end;
31334
31335 DistanceLambda:=Distance/(ProjectedLinearVelocity+MaximumAngularProjectedVelocity);
31336
31337 Lambda:=Lambda+DistanceLambda;
31338 if ((Lambda<0.0) or (Lambda>1.0)) or (Lambda<=LastLambda) then begin
31339 exit;
31340 end;
31341
31342 LastLambda:=Lambda;
31343
31344 Transforms[0]:=Matrix4x4TermMul(Shapes[0].fLocalTransform,SweepTransform(SweepA,Lambda));
31345 Transforms[1]:=Matrix4x4TermMul(Shapes[1].fLocalTransform,SweepTransform(SweepB,Lambda));
31346
31347 if GJK.Run then begin
31348
31349 Distance:=GJK.Distance+fAllowedPenetration;
31350
31351 inc(Tries);
31352 if Tries>TimeOfImpactMaximumIterations then begin
31353 exit;
31354 end;
31355
31356 end else begin
31357 exit;
31358 end;
31359
31360 end;
31361
31362 //writeln(Lambda:1:8);
31363
31364 Beta:=Lambda;
31365 result:=true;
31366
31367 end;
31368
31369 end;
31370
31371 // Bilateral advancement
31372 function TKraft.GetBilateralAdvancementTimeOfImpact(const ShapeA:TKraftShape;const SweepA:TKraftSweep;const ShapeB:TKraftShape;const ShapeBTriangleIndex:longint;const SweepB:TKraftSweep;const TimeStep:TKraftTimeStep;const ThreadIndex:longint;var Beta:TKraftScalar):boolean;
31373 const sfmNONE=0;
31374 sfmVERTICES=1;
31375 sfmEDGEA=2;
31376 sfmEDGEB=3;
31377 sfmFACEA=4;
31378 sfmFACEB=5;
31379 sfmEDGES=6;
31380 var Iteration,TryIteration,RootIteration,SeparationFunctionMode:longint;
31381 //Unprocessed,Overlapping:boolean;
31382 t0,t1,s0,s1,a0,a1,t,s,{tS,tT0,tT1,}TotalRadius,Target,Tolerance,{Distance,CurrentDistance,L,}
31383 ContinuousMinimumRadiusScaleFactor:TKraftScalar;
31384 ShapeTriangle:TKraftShapeTriangle;
31385 MeshShape:TKraftShapeMesh;
31386 MeshTriangle:PKraftMeshTriangle;
31387 Axis,{LocalVertex,va,vb,}eA,eB:TKraftVector3;
31388 LocalPlane:TKraftPlane;
31389 GJK:TKraftGJK;
31390 Shapes:array[0..1] of TKraftShape;
31391 WitnessPoints:array[0..1] of TKraftVector3;
31392 Transforms:array[0..1] of TKraftMatrix4x4;
31393 //LinearVelocities,AngularVelocities:array[0..1] of TKraftVector3;
31394 UniqueGJKVertexIndices:array[0..1,0..2] of longint;
31395 UniqueGJKVertices:array[0..1,0..2] of TKraftVector3;
31396 CountUniqueGJKVertices:array[0..1] of longint;
31397 GJKCachedSimplex:TKraftGJKCachedSimplex;
31398 function Evaluate:TKraftScalar; //{$ifdef caninline}inline;{$endif}
31399 begin
31400 case SeparationFunctionMode of
31401 sfmVERTICES:begin
31402 result:=Vector3Dot(Axis,
31403 Vector3Sub(Vector3TermMatrixMul(WitnessPoints[1],Transforms[1]),
31404 Vector3TermMatrixMul(WitnessPoints[0],Transforms[0])));
31405 end;
31406 sfmEDGEA,sfmFACEA,sfmEDGES:begin
31407 result:=PlaneVectorDistance(LocalPlane,Vector3TermMatrixMulInverted(Vector3TermMatrixMul(WitnessPoints[1],Transforms[1]),Transforms[0]));
31408 end;
31409 sfmEDGEB,sfmFACEB:begin
31410 result:=PlaneVectorDistance(LocalPlane,Vector3TermMatrixMulInverted(Vector3TermMatrixMul(WitnessPoints[0],Transforms[0]),Transforms[1]));
31411 end;
31412 else begin
31413 result:=0.0;
31414 Assert(false);
31415 end;
31416 end;
31417 end;
31418 function FindMinSeparation:TKraftScalar; //{$ifdef caninline}inline;{$endif}
31419 begin
31420 case SeparationFunctionMode of
31421 sfmVERTICES:begin
31422 WitnessPoints[0]:=Shapes[0].GetLocalFeatureSupportVertex(Shapes[0].GetLocalFeatureSupportIndex(Vector3TermMatrixMulTransposedBasis(Axis,Transforms[0])));
31423 WitnessPoints[1]:=Shapes[1].GetLocalFeatureSupportVertex(Shapes[1].GetLocalFeatureSupportIndex(Vector3TermMatrixMulTransposedBasis(Vector3Neg(Axis),Transforms[1])));
31424 end;
31425 sfmEDGEA,sfmFACEA,sfmEDGES:begin
31426 WitnessPoints[1]:=Shapes[1].GetLocalFeatureSupportVertex(Shapes[1].GetLocalFeatureSupportIndex(Vector3Neg(Vector3TermMatrixMulTransposedBasis(Vector3TermMatrixMulBasis(Axis,Transforms[0]),Transforms[1]))));
31427 end;
31428 sfmEDGEB,sfmFACEB:begin
31429 WitnessPoints[0]:=Shapes[0].GetLocalFeatureSupportVertex(Shapes[0].GetLocalFeatureSupportIndex(Vector3Neg(Vector3TermMatrixMulTransposedBasis(Vector3TermMatrixMulBasis(Axis,Transforms[1]),Transforms[0]))));
31430 end;
31431 end;
31432 result:=Evaluate;
31433 end;
31434 begin
31435
31436 result:=false;
31437
31438 Shapes[0]:=ShapeA;
31439
31440 if (ShapeBTriangleIndex>=0) and (ShapeB is TKraftShapeMesh) then begin
31441 MeshShape:=TKraftShapeMesh(ShapeB);
31442 ShapeTriangle:=TKraftShapeTriangle(fTriangleShapes[ThreadIndex]);
31443 Shapes[1]:=ShapeTriangle;
31444 MeshTriangle:[email protected][ShapeBTriangleIndex];
31445 ShapeTriangle.fLocalTransform:=MeshShape.fLocalTransform;
31446 ShapeTriangle.fWorldTransform:=MeshShape.fWorldTransform;
31447 ShapeTriangle.fConvexHull.fVertices[0].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[0]];
31448 ShapeTriangle.fConvexHull.fVertices[1].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[1]];
31449 ShapeTriangle.fConvexHull.fVertices[2].Position:=MeshShape.fMesh.fVertices[MeshTriangle^.Vertices[2]];
31450 ShapeTriangle.UpdateData;
31451 end else begin
31452 Shapes[1]:=ShapeB;
31453 end;
31454
31455 ContinuousMinimumRadiusScaleFactor:=Max(ShapeA.fContinuousMinimumRadiusScaleFactor,ShapeB.fContinuousMinimumRadiusScaleFactor);
31456 if (ContinuousMinimumRadiusScaleFactor>EPSILON) and
31457 (Vector3Length(Vector3Sub(Vector3Sub(SweepB.c0,SweepB.c),Vector3Sub(SweepA.c0,SweepA.c)))<Max(EPSILON,Min(Shapes[0].fShapeSphere.Radius,Shapes[1].fShapeSphere.Radius)*ContinuousMinimumRadiusScaleFactor)) then begin
31458 exit;
31459 end;
31460
31461 TotalRadius:=Shapes[0].fFeatureRadius+Shapes[1].fFeatureRadius;
31462
31463 Target:=Max(fLinearSlop,TotalRadius-(3.0*fLinearSlop));
31464
31465 Tolerance:=fLinearSlop*0.25;
31466
31467 GJKCachedSimplex.Count:=0;
31468
31469 GJK.CachedSimplex:=@GJKCachedSimplex;
31470 GJK.Shapes[0]:=Shapes[0];
31471 GJK.Shapes[1]:=Shapes[1];
31472 GJK.Transforms[0]:=@Transforms[0];
31473 GJK.Transforms[1]:=@Transforms[1];
31474 GJK.UseRadii:=false;
31475
31476 // Compute current closest features. Setup a separation function to evaluate
31477 // overlap on the axis between the closest features. Terminate if closest
31478 // features are repeated.
31479
31480 t0:=0.0;
31481
31482 Axis:=Vector3Origin;
31483
31484 SeparationFunctionMode:=sfmNONE;
31485
31486 UniqueGJKVertexIndices[0,0]:=0;
31487 UniqueGJKVertexIndices[0,1]:=0;
31488 UniqueGJKVertexIndices[1,0]:=0;
31489 UniqueGJKVertexIndices[1,1]:=0;
31490
31491 CountUniqueGJKVertices[0]:=0;
31492 CountUniqueGJKVertices[1]:=0;
31493
31494 for Iteration:=1 to TimeOfImpactMaximumIterations do begin
31495
31496 Transforms[0]:=Matrix4x4TermMul(Shapes[0].fLocalTransform,SweepTransform(SweepA,t0));
31497 Transforms[1]:=Matrix4x4TermMul(Shapes[1].fLocalTransform,SweepTransform(SweepB,t0));
31498
31499 if not GJK.Run then begin
31500 Beta:=0.0;
31501 result:=false;
31502 exit;
31503 end;
31504
31505 // TOI is not defined if shapes began in an overlapping configuration
31506 if GJK.Distance<EPSILON then begin
31507 Beta:=0.0;
31508 result:=false;
31509 exit;
31510 end;
31511
31512 // Check for initial convergent state
31513 if GJK.Distance<(Target+Tolerance) then begin
31514 Beta:=t0;
31515 result:=true;
31516 exit;
31517 end;
31518
31519 // Extract features from GJK
31520 case GJK.Simplex.Count of
31521 1:begin
31522
31523 // GJK point simplex
31524
31525 UniqueGJKVertexIndices[0,0]:=GJK.Simplex.Vertices[0]^.iA;
31526 UniqueGJKVertexIndices[1,0]:=GJK.Simplex.Vertices[0]^.iB;
31527 CountUniqueGJKVertices[0]:=1;
31528 CountUniqueGJKVertices[1]:=1;
31529
31530 end;
31531 2:begin
31532
31533 // GJK line simplex
31534
31535 UniqueGJKVertexIndices[0,0]:=GJK.Simplex.Vertices[0]^.iA;
31536 UniqueGJKVertexIndices[0,1]:=GJK.Simplex.Vertices[1]^.iA;
31537 if UniqueGJKVertexIndices[0,0]<>UniqueGJKVertexIndices[0,1] then begin
31538 CountUniqueGJKVertices[0]:=2;
31539 end else begin
31540 CountUniqueGJKVertices[0]:=1;
31541 end;
31542
31543 UniqueGJKVertexIndices[1,0]:=GJK.Simplex.Vertices[0]^.iB;
31544 UniqueGJKVertexIndices[1,1]:=GJK.Simplex.Vertices[1]^.iB;
31545 if UniqueGJKVertexIndices[1,0]<>UniqueGJKVertexIndices[1,1] then begin
31546 CountUniqueGJKVertices[1]:=2;
31547 end else begin
31548 CountUniqueGJKVertices[1]:=1;
31549 end;
31550
31551 end;
31552 3:begin
31553
31554 // GJK triangle simplex
31555
31556 UniqueGJKVertexIndices[0,0]:=GJK.Simplex.Vertices[0]^.iA;
31557 if UniqueGJKVertexIndices[0,0]<>GJK.Simplex.Vertices[1]^.iA then begin
31558 UniqueGJKVertexIndices[0,1]:=GJK.Simplex.Vertices[1]^.iA;
31559 if UniqueGJKVertexIndices[0,1]<>GJK.Simplex.Vertices[2]^.iA then begin
31560 UniqueGJKVertexIndices[0,2]:=GJK.Simplex.Vertices[2]^.iA;
31561 CountUniqueGJKVertices[0]:=3;
31562 end else begin
31563 CountUniqueGJKVertices[0]:=2;
31564 end;
31565 end else if UniqueGJKVertexIndices[0,0]<>GJK.Simplex.Vertices[2]^.iA then begin
31566 UniqueGJKVertexIndices[0,1]:=GJK.Simplex.Vertices[2]^.iA;
31567 CountUniqueGJKVertices[0]:=2;
31568 end else begin
31569 CountUniqueGJKVertices[0]:=1;
31570 end;
31571
31572 UniqueGJKVertexIndices[1,0]:=GJK.Simplex.Vertices[0]^.iB;
31573 if UniqueGJKVertexIndices[1,0]<>GJK.Simplex.Vertices[1]^.iB then begin
31574 UniqueGJKVertexIndices[1,1]:=GJK.Simplex.Vertices[1]^.iB;
31575 if UniqueGJKVertexIndices[1,1]<>GJK.Simplex.Vertices[2]^.iB then begin
31576 UniqueGJKVertexIndices[1,2]:=GJK.Simplex.Vertices[2]^.iB;
31577 CountUniqueGJKVertices[1]:=3;
31578 end else begin
31579 CountUniqueGJKVertices[1]:=2;
31580 end;
31581 end else if UniqueGJKVertexIndices[1,0]<>GJK.Simplex.Vertices[2]^.iB then begin
31582 UniqueGJKVertexIndices[1,1]:=GJK.Simplex.Vertices[2]^.iB;
31583 CountUniqueGJKVertices[1]:=2;
31584 end else begin
31585 CountUniqueGJKVertices[1]:=1;
31586 end;
31587
31588 end;
31589 4:begin
31590 // GJK tetrahedron simplex, which contains the origin, which means that there is a overlapping configuration, where
31591 // the time of impact is not defined if shapes are already in an overlapping configuration
31592 Beta:=0.0;
31593 result:=false;
31594 exit;
31595 end;
31596 else begin
31597 // This might happen if the GJK implementation is faulty.
31598 end;
31599 end;
31600
31601 // Initialize the found features for the separation function
31602 case CountUniqueGJKVertices[0] of
31603 1:begin
31604 // Vertex on A
31605 case CountUniqueGJKVertices[1] of
31606 1:begin
31607 // Vertex on A and vertex on B
31608 Axis:=Vector3NormEx(Vector3Sub(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]),
31609 Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0])));
31610 SeparationFunctionMode:=sfmVERTICES;
31611 end;
31612 2:begin
31613 // Vertex on A and edge on B
31614 UniqueGJKVertices[0,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]),Transforms[0]),Transforms[1]);
31615 UniqueGJKVertices[1,0]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]);
31616 UniqueGJKVertices[1,1]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,1]);
31617 Axis:=Vector3Sub(UniqueGJKVertices[1,1],UniqueGJKVertices[1,0]);
31618 LocalPlane.Normal:=Vector3NormEx(Vector3Cross(Vector3Cross(Axis,Vector3Sub(UniqueGJKVertices[0,0],UniqueGJKVertices[1,0])),Axis));
31619 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[1,0]);
31620 SeparationFunctionMode:=sfmEDGEB;
31621 end;
31622 3:begin
31623 // Vertex on A and face on B
31624 UniqueGJKVertices[0,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]),Transforms[0]),Transforms[1]);
31625 UniqueGJKVertices[1,0]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]);
31626 UniqueGJKVertices[1,1]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,1]);
31627 UniqueGJKVertices[1,2]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,2]);
31628 Axis:=Vector3NormEx(Vector3Cross(Vector3Sub(UniqueGJKVertices[1,0],UniqueGJKVertices[1,1]),Vector3Sub(UniqueGJKVertices[1,2],UniqueGJKVertices[1,1])));
31629 if Vector3Dot(UniqueGJKVertices[0,0],Axis)<0.0 then begin
31630 Axis:=Vector3Neg(Axis);
31631 end;
31632 LocalPlane.Normal:=Axis;
31633 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[1,0]);
31634 SeparationFunctionMode:=sfmFACEB;
31635 end;
31636 end;
31637 end;
31638 2:begin
31639 // Edge A
31640 case CountUniqueGJKVertices[1] of
31641 1:begin
31642 // Edge on A and vertex on B
31643 UniqueGJKVertices[0,0]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]);
31644 UniqueGJKVertices[0,1]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,1]);
31645 UniqueGJKVertices[1,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]),Transforms[1]),Transforms[0]);
31646 Axis:=Vector3Sub(UniqueGJKVertices[0,1],UniqueGJKVertices[0,0]);
31647 LocalPlane.Normal:=Vector3NormEx(Vector3Cross(Vector3Cross(Axis,Vector3Sub(UniqueGJKVertices[1,0],UniqueGJKVertices[0,0])),Axis));
31648 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[0,0]);
31649 SeparationFunctionMode:=sfmEDGEA;
31650 end;
31651 2:begin
31652 // Edge on A and edge on B
31653 UniqueGJKVertices[0,0]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]);
31654 UniqueGJKVertices[0,1]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,1]);
31655 UniqueGJKVertices[1,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]),Transforms[1]),Transforms[0]);
31656 UniqueGJKVertices[1,1]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,1]),Transforms[1]),Transforms[0]);
31657 eA:=Vector3Sub(UniqueGJKVertices[0,1],UniqueGJKVertices[0,0]);
31658 eB:=Vector3Sub(UniqueGJKVertices[1,1],UniqueGJKVertices[1,0]);
31659 Axis:=Vector3NormEx(Vector3Cross(eA,eB));
31660 if Vector3Dot(Vector3Sub(eB,eA),Axis)<0.0 then begin
31661 Axis:=Vector3Neg(Axis);
31662 end;
31663 LocalPlane.Normal:=Axis;
31664 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,eA);
31665 SeparationFunctionMode:=sfmEDGES;
31666 end;
31667 3:begin
31668 // Edge on A and face on B
31669 UniqueGJKVertices[0,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]),Transforms[0]),Transforms[1]);
31670 UniqueGJKVertices[0,1]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,1]),Transforms[0]),Transforms[1]);
31671 UniqueGJKVertices[1,0]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]);
31672 UniqueGJKVertices[1,1]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,1]);
31673 UniqueGJKVertices[1,2]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,2]);
31674 Axis:=Vector3NormEx(Vector3Cross(Vector3Sub(UniqueGJKVertices[1,0],UniqueGJKVertices[1,1]),Vector3Sub(UniqueGJKVertices[1,2],UniqueGJKVertices[1,1])));
31675 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,0],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,1],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2]) then begin
31676 if Vector3Dot(UniqueGJKVertices[0,0],Axis)<0.0 then begin
31677 Axis:=Vector3Neg(Axis);
31678 end;
31679 end else begin
31680 if Vector3Dot(UniqueGJKVertices[0,1],Axis)<0.0 then begin
31681 Axis:=Vector3Neg(Axis);
31682 end;
31683 end;
31684 LocalPlane.Normal:=Axis;
31685 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[1,0]);
31686 SeparationFunctionMode:=sfmFACEB;
31687 end;
31688 end;
31689 end;
31690 3:begin
31691 // Face on A
31692 case CountUniqueGJKVertices[1] of
31693 1:begin
31694 // Face on A and vertex on B
31695 UniqueGJKVertices[0,0]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]);
31696 UniqueGJKVertices[0,1]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,1]);
31697 UniqueGJKVertices[0,2]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,2]);
31698 UniqueGJKVertices[1,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]),Transforms[1]),Transforms[0]);
31699 Axis:=Vector3NormEx(Vector3Cross(Vector3Sub(UniqueGJKVertices[0,0],UniqueGJKVertices[0,1]),Vector3Sub(UniqueGJKVertices[0,2],UniqueGJKVertices[0,1])));
31700 if Vector3Dot(UniqueGJKVertices[1,0],Axis)<0.0 then begin
31701 Axis:=Vector3Neg(Axis);
31702 end;
31703 LocalPlane.Normal:=Axis;
31704 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[0,0]);
31705 SeparationFunctionMode:=sfmFACEA;
31706 end;
31707 2:begin
31708 // Face on A and edge on B
31709 UniqueGJKVertices[0,0]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]);
31710 UniqueGJKVertices[0,1]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,1]);
31711 UniqueGJKVertices[0,2]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,2]);
31712 UniqueGJKVertices[1,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]),Transforms[1]),Transforms[0]);
31713 UniqueGJKVertices[1,1]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,1]),Transforms[1]),Transforms[0]);
31714 Axis:=Vector3NormEx(Vector3Cross(Vector3Sub(UniqueGJKVertices[0,0],UniqueGJKVertices[0,1]),Vector3Sub(UniqueGJKVertices[0,2],UniqueGJKVertices[0,1])));
31715 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,0],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,1],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2]) then begin
31716 if Vector3Dot(UniqueGJKVertices[1,0],Axis)<0.0 then begin
31717 Axis:=Vector3Neg(Axis);
31718 end;
31719 end else begin
31720 if Vector3Dot(UniqueGJKVertices[1,1],Axis)<0.0 then begin
31721 Axis:=Vector3Neg(Axis);
31722 end;
31723 end;
31724 LocalPlane.Normal:=Axis;
31725 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[0,0]);
31726 SeparationFunctionMode:=sfmFACEA;
31727 end;
31728 3:begin
31729 // Face on A and face on B
31730 UniqueGJKVertices[0,0]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,0]);
31731 UniqueGJKVertices[0,1]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,1]);
31732 UniqueGJKVertices[0,2]:=Shapes[0].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[0,2]);
31733 UniqueGJKVertices[1,0]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,0]);
31734 UniqueGJKVertices[1,1]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,1]);
31735 UniqueGJKVertices[1,2]:=Shapes[1].GetLocalFeatureSupportVertex(UniqueGJKVertexIndices[1,2]);
31736 if CalculateArea(UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2])<CalculateArea(UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2]) then begin
31737 // Face B has a larger area than face A
31738 UniqueGJKVertices[0,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(UniqueGJKVertices[0,0],Transforms[0]),Transforms[1]);
31739 UniqueGJKVertices[0,1]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(UniqueGJKVertices[0,1],Transforms[0]),Transforms[1]);
31740 UniqueGJKVertices[0,2]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(UniqueGJKVertices[0,2],Transforms[0]),Transforms[1]);
31741 Axis:=Vector3NormEx(Vector3Cross(Vector3Sub(UniqueGJKVertices[1,0],UniqueGJKVertices[1,1]),Vector3Sub(UniqueGJKVertices[1,2],UniqueGJKVertices[1,1])));
31742 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,0],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,1],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2]) then begin
31743 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,0],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,2],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2]) then begin
31744 if Vector3Dot(UniqueGJKVertices[0,0],Axis)<0.0 then begin
31745 Axis:=Vector3Neg(Axis);
31746 end;
31747 end else begin
31748 if Vector3Dot(UniqueGJKVertices[0,2],Axis)<0.0 then begin
31749 Axis:=Vector3Neg(Axis);
31750 end;
31751 end;
31752 end else begin
31753 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,1],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[0,2],UniqueGJKVertices[1,0],UniqueGJKVertices[1,1],UniqueGJKVertices[1,2]) then begin
31754 if Vector3Dot(UniqueGJKVertices[0,1],Axis)<0.0 then begin
31755 Axis:=Vector3Neg(Axis);
31756 end;
31757 end else begin
31758 if Vector3Dot(UniqueGJKVertices[0,2],Axis)<0.0 then begin
31759 Axis:=Vector3Neg(Axis);
31760 end;
31761 end;
31762 end;
31763 LocalPlane.Normal:=Axis;
31764 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[1,0]);
31765 SeparationFunctionMode:=sfmFACEB;
31766 end else begin
31767 // Face A has a larger area than face B
31768 UniqueGJKVertices[1,0]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(UniqueGJKVertices[1,0],Transforms[1]),Transforms[0]);
31769 UniqueGJKVertices[1,1]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(UniqueGJKVertices[1,1],Transforms[1]),Transforms[0]);
31770 UniqueGJKVertices[1,2]:=Vector3TermMatrixMulInverted(Vector3TermMatrixMul(UniqueGJKVertices[1,2],Transforms[1]),Transforms[0]);
31771 Axis:=Vector3NormEx(Vector3Cross(Vector3Sub(UniqueGJKVertices[0,0],UniqueGJKVertices[0,1]),Vector3Sub(UniqueGJKVertices[0,2],UniqueGJKVertices[0,1])));
31772 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,0],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,1],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2]) then begin
31773 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,0],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,2],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2]) then begin
31774 if Vector3Dot(UniqueGJKVertices[1,0],Axis)<0.0 then begin
31775 Axis:=Vector3Neg(Axis);
31776 end;
31777 end else begin
31778 if Vector3Dot(UniqueGJKVertices[1,2],Axis)<0.0 then begin
31779 Axis:=Vector3Neg(Axis);
31780 end;
31781 end;
31782 end else begin
31783 if SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,1],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2])<SquaredDistanceFromPointToTriangle(UniqueGJKVertices[1,2],UniqueGJKVertices[0,0],UniqueGJKVertices[0,1],UniqueGJKVertices[0,2]) then begin
31784 if Vector3Dot(UniqueGJKVertices[1,1],Axis)<0.0 then begin
31785 Axis:=Vector3Neg(Axis);
31786 end;
31787 end else begin
31788 if Vector3Dot(UniqueGJKVertices[1,2],Axis)<0.0 then begin
31789 Axis:=Vector3Neg(Axis);
31790 end;
31791 end;
31792 end;
31793 LocalPlane.Normal:=Axis;
31794 LocalPlane.Distance:=-Vector3Dot(LocalPlane.Normal,UniqueGJKVertices[0,0]);
31795 SeparationFunctionMode:=sfmFACEA;
31796 end;
31797 end;
31798 end;
31799 end;
31800 end;
31801
31802 // Successively resolve the deepest point to compute the time of impact, loop is bounded by the number of Vertices to be resolved.
31803 t1:=1.0;
31804 for TryIteration:=1 to 64 do begin
31805
31806 // Compute deepest witness points at t1
31807 Transforms[0]:=Matrix4x4TermMul(Shapes[0].fLocalTransform,SweepTransform(SweepA,t1));
31808 Transforms[1]:=Matrix4x4TermMul(Shapes[1].fLocalTransform,SweepTransform(SweepB,t1));
31809 s1:=FindMinSeparation;
31810
31811 // Is the final configuration separated?
31812 if s1>(Target+Tolerance) then begin
31813 exit;
31814 end;
31815
31816 // Has the separation reached tolerance?
31817 if s1>(Target-Tolerance) then begin
31818 // Advance the sweeps
31819 t0:=t1;
31820 if t0>=(1.0-EPSILON) then begin
31821 exit;
31822 end else begin
31823 break;
31824 end;
31825 end;
31826
31827 // Compute the initial separation of the witness points
31828 Transforms[0]:=Matrix4x4TermMul(Shapes[0].fLocalTransform,SweepTransform(SweepA,t0));
31829 Transforms[1]:=Matrix4x4TermMul(Shapes[1].fLocalTransform,SweepTransform(SweepB,t0));
31830 s0:=Evaluate;
31831
31832 // Check for initial overlap
31833 if s0<(Target-Tolerance) then begin
31834 // This might happen if the root finder runs out of iterations. Also more likely to happen with a poor separation function.
31835 Beta:=t0;
31836 result:=false;
31837 exit;
31838 end;
31839
31840 // Check for touching, t0 should hold the time of impact (could be 0.0)
31841 if s0<=(Target+Tolerance) then begin
31842 Beta:=t0;
31843 result:=true;
31844 exit;
31845 end;
31846
31847 // Compute the 1D root of: f(x)-Target=0
31848 a0:=t0;
31849 a1:=t1;
31850 for RootIteration:=0 to 63 do begin
31851
31852 if (RootIteration and 1)<>0 then begin
31853 t:=a1+((Target-s0)*((a1-a0)/(s1-s0)));
31854 end else begin
31855 t:=(a0+a1)*0.5;
31856 end;
31857
31858 Transforms[0]:=Matrix4x4TermMul(Shapes[0].fLocalTransform,SweepTransform(SweepA,t));
31859 Transforms[1]:=Matrix4x4TermMul(Shapes[1].fLocalTransform,SweepTransform(SweepB,t));
31860 s:=Evaluate;
31861
31862 if abs(s-Target)<Tolerance then begin
31863 // t1 holds a tentative value for t0
31864 t1:=t;
31865 break;
31866 end else if s>Target then begin
31867 a0:=t;
31868 s0:=s;
31869 end else begin
31870 a1:=t;
31871 s1:=s;
31872 end;
31873
31874 end;
31875
31876 end;
31877
31878 end;
31879
31880 end;
31881
31882 function TKraft.GetTimeOfImpact(const ShapeA:TKraftShape;const SweepA:TKraftSweep;const ShapeB:TKraftShape;const ShapeBTriangleIndex:longint;const SweepB:TKraftSweep;const TimeStep:TKraftTimeStep;const ThreadIndex:longint;var Beta:TKraftScalar):boolean;
31883 begin
31884 case fTimeOfImpactAlgorithm of
31885 ktoiaConservativeAdvancement:begin
31886 result:=GetConservativeAdvancementTimeOfImpact(ShapeA,SweepA,ShapeB,ShapeBTriangleIndex,SweepB,TimeStep,ThreadIndex,Beta);
31887 end;
31888 else {ktoiaBilateralAdvancement:}begin
31889 result:=GetBilateralAdvancementTimeOfImpact(ShapeA,SweepA,ShapeB,ShapeBTriangleIndex,SweepB,TimeStep,ThreadIndex,Beta);
31890 end;
31891 end;
31892 end;
31893
31894 procedure TKraft.Solve(const TimeStep:TKraftTimeStep);
31895 var RigidBody:TKraftRigidBody;
31896 begin
31897
31898 BuildIslands;
31899
31900 SolveIslands(TimeStep);
31901
31902 RigidBody:=fDynamicRigidBodyFirst;
31903 while assigned(RigidBody) do begin
31904 RigidBody.SynchronizeProxies;
31905 RigidBody:=RigidBody.fRigidBodyNext;
31906 end;
31907
31908 RigidBody:=fKinematicRigidBodyFirst;
31909 while assigned(RigidBody) do begin
31910 RigidBody.SynchronizeProxies;
31911 RigidBody:=RigidBody.fRigidBodyNext;
31912 end;
31913
31914 fContactManager.DoBroadPhase;
31915
31916 fContactManager.DoMidPhase;
31917
31918 end;
31919
31920 procedure TKraft.SolveContinuousMotionClamping(const TimeStep:TKraftTimeStep);
31921 var RigidBody:TKraftRigidBody;
31922 ContactPair:PKraftContactPair;
31923 Beta:TKraftScalar;
31924 NeedUpdate:boolean;
31925 ContactPairEdge:PKraftContactPairEdge;
31926 RigidBodies:array[0..1] of TKraftRigidBody;
31927 Sweeps:array[0..1] of TKraftSweep;
31928 begin
31929
31930 NeedUpdate:=false;
31931
31932 RigidBody:=fRigidBodyFirst;
31933 while assigned(RigidBody) do begin
31934 RigidBody.fSweep.Alpha0:=0.0;
31935 RigidBody.fTimeOfImpact:=1.0;
31936 RigidBody.fIsland:=nil;
31937 RigidBody.fFlags:=RigidBody.fFlags-[krbfIslandVisited,krbfIslandStatic];
31938 RigidBody:=RigidBody.fRigidBodyNext;
31939 end;
31940
31941 ContactPair:=fContactManager.fContactPairFirst;
31942 while assigned(ContactPair) do begin
31943 ContactPair^.Island:=nil;
31944 ContactPair^.Flags:=ContactPair^.Flags-[kcfInIsland,kcfTimeOfImpact];
31945 ContactPair^.TimeOfImpactCount:=0;
31946 ContactPair^.TimeOfImpact:=1.0;
31947 ContactPair:=ContactPair.Next;
31948 end;
31949
31950 RigidBody:=fRigidBodyFirst;
31951 while assigned(RigidBody) do begin
31952 if RigidBody.fRigidBodyType=krbtDynamic then begin
31953 ContactPairEdge:=RigidBody.fContactPairEdgeFirst;
31954 while assigned(ContactPairEdge) do begin
31955 ContactPair:=ContactPairEdge^.ContactPair;
31956 if (not (kcfInIsland in ContactPair^.Flags)) and
31957 (((RigidBody.fFlags*[krbfAwake,krbfActive])=[krbfAwake,krbfActive]) or
31958 ((ContactPairEdge^.OtherRigidBody.fFlags*[krbfAwake,krbfActive])=[krbfAwake,krbfActive])) and
31959 (not (((ksfSensor in ContactPair^.Shapes[0].fFlags) or
31960 (ksfSensor in ContactPair^.Shapes[1].fFlags)) or
31961 ((krbfSensor in RigidBody.fFlags) or
31962 (krbfSensor in ContactPairEdge^.OtherRigidBody.fFlags)))) and
31963 (not (((RigidBody.fRigidBodyType=krbtDynamic) and (ContactPairEdge^.OtherRigidBody.fRigidBodyType=krbtDynamic)) and not
31964 (fContinuousAgainstDynamics and
31965 ((krbfContinuousAgainstDynamics in RigidBody.fFlags) or
31966 (krbfContinuousAgainstDynamics in ContactPairEdge^.OtherRigidBody.fFlags)
31967 )
31968 )
31969 )
31970 ) then begin
31971 ContactPair^.Flags:=ContactPair^.Flags+[kcfInIsland];
31972 if not (kcfColliding in ContactPair^.Flags) then begin
31973 RigidBodies[0]:=ContactPair^.Shapes[0].fRigidBody;
31974 RigidBodies[1]:=ContactPair^.Shapes[1].fRigidBody;
31975 if assigned(RigidBodies[0]) and assigned(RigidBodies[1]) then begin
31976 Sweeps[0]:=SweepTermNormalize(RigidBodies[0].fSweep);
31977 Sweeps[1]:=SweepTermNormalize(RigidBodies[1].fSweep);
31978 if GetTimeOfImpact(ContactPair^.Shapes[0],
31979 Sweeps[0],
31980 ContactPair^.Shapes[1],
31981 ContactPair^.ElementIndex,
31982 Sweeps[1],
31983 TimeStep,
31984 0,
31985 Beta) then begin
31986 // Check for that the object will not get stucking, when it is alreading colliding at beginning
31987 if Beta>0.0 then begin
31988 RigidBodies[0].fTimeOfImpact:=Min(RigidBodies[0].fTimeOfImpact,Beta);
31989 RigidBodies[1].fTimeOfImpact:=Min(RigidBodies[1].fTimeOfImpact,Beta);
31990 end;
31991 end;
31992 end;
31993 end;
31994 end;
31995 ContactPairEdge:=ContactPairEdge^.Next;
31996 end;
31997 end;
31998 RigidBody:=RigidBody.fRigidBodyNext;
31999 end;
32000
32001 RigidBody:=fRigidBodyFirst;
32002 while assigned(RigidBody) do begin
32003 if (RigidBody.fRigidBodyType=krbtDynamic) and ({(RigidBody.fTimeOfImpact>0.0) and} (RigidBody.fTimeOfImpact<1.0)) then begin
32004 // writeln(RigidBody.fTimeOfImpact:1:8);
32005 RigidBody.Advance(RigidBody.fTimeOfImpact);
32006 RigidBody.SynchronizeProxies;
32007 NeedUpdate:=true;
32008 end;
32009 RigidBody:=RigidBody.fRigidBodyNext;
32010 end;
32011
32012 if NeedUpdate then begin
32013 fContactManager.DoBroadPhase;
32014 fContactManager.DoMidPhase;
32015 fContactManager.DoNarrowPhase;
32016 end;
32017
32018 end;
32019
32020 procedure TKraft.SolveContinuousTimeOfImpactSubSteps(const TimeStep:TKraftTimeStep);
32021 const FLAG_VISITED=1 shl 0;
32022 FLAG_STATIC=1 shl 1;
32023 var TryIndex,Index,SubIndex,LastCount,Count,IndexA,IndexB{,c{}:longint;
32024 NeedUpdate:boolean;
32025 RigidBody,CurrentRigidBody,OtherRigidBody:TKraftRigidBody;
32026 ContactPair,MinimumContactPair:PKraftContactPair;
32027 MinimumAlpha,Alpha,Alpha0,Beta:TKraftScalar;
32028 Island:TKraftIsland;
32029 ContactPairEdge:PKraftContactPairEdge;
32030 RigidBodies:array[0..1] of TKraftRigidBody;
32031 BackupSweeps:array[0..1] of TKraftSweep;
32032 SubTimeStep:TKraftTimeStep;
32033 begin
32034
32035 NeedUpdate:=false;
32036
32037 RigidBody:=fRigidBodyFirst;
32038 while assigned(RigidBody) do begin
32039 RigidBody.fSweep.Alpha0:=0.0;
32040 RigidBody.fIsland:=nil;
32041 RigidBody.fFlags:=RigidBody.fFlags-[krbfIslandVisited,krbfIslandStatic];
32042 RigidBody:=RigidBody.fRigidBodyNext;
32043 end;
32044
32045 Count:=0;
32046 ContactPair:=fContactManager.fContactPairFirst;
32047 while assigned(ContactPair) do begin
32048 ContactPair^.Island:=nil;
32049 ContactPair^.Flags:=ContactPair^.Flags-[kcfInIsland,kcfTimeOfImpact];
32050 ContactPair^.TimeOfImpactCount:=0;
32051 ContactPair^.TimeOfImpact:=1.0;
32052 inc(Count);
32053 ContactPair:=ContactPair.Next;
32054 end;
32055
32056 for TryIndex:=1 to Count do begin
32057
32058 MinimumContactPair:=nil;
32059 MinimumAlpha:=1.0;
32060
32061 //c:=0;
32062
32063 ContactPair:=fContactManager.fContactPairFirst;
32064 while assigned(ContactPair) do begin
32065
32066 if (ContactPair^.TimeOfImpactCount>=fMaximalSubSteps) or not (kcfEnabled in ContactPair^.Flags) then begin
32067 ContactPair:=ContactPair^.Next;
32068 continue;
32069 end;
32070
32071 if kcfTimeOfImpact in ContactPair^.Flags then begin
32072
32073 Alpha:=ContactPair^.TimeOfImpact;
32074
32075 end else begin
32076
32077 Alpha:=1.0;
32078
32079 if (ksfSensor in ContactPair^.Shapes[0].fFlags) or
32080 (ksfSensor in ContactPair^.Shapes[1].fFlags) then begin
32081 ContactPair:=ContactPair^.Next;
32082 continue;
32083 end;
32084
32085 RigidBodies[0]:=ContactPair^.Shapes[0].fRigidBody;
32086 RigidBodies[1]:=ContactPair^.Shapes[1].fRigidBody;
32087
32088 if not ((assigned(RigidBodies[0]) and assigned(RigidBodies[1])) and
32089 (((RigidBodies[0].fRigidBodyType=krbtDynamic) or (RigidBodies[1].fRigidBodyType=krbtDynamic)) and
32090 (((RigidBodies[0].fFlags*[krbfAwake,krbfActive])=[krbfAwake,krbfActive]) or
32091 ((RigidBodies[1].fFlags*[krbfAwake,krbfActive])=[krbfAwake,krbfActive])) and
32092 ((krbfContinuous in RigidBodies[0].fFlags) and (krbfContinuous in RigidBodies[1].fFlags)))) then begin
32093 ContactPair:=ContactPair^.Next;
32094 continue;
32095 end;
32096
32097 if ((krbfSensor in ContactPair^.RigidBodies[0].fFlags) or
32098 (krbfSensor in ContactPair^.RigidBodies[1].fFlags)) or
32099 (((RigidBodies[0].fRigidBodyType=krbtDynamic) and (RigidBodies[1].fRigidBodyType=krbtDynamic)) and not
32100 (fContinuousAgainstDynamics and
32101 ((krbfContinuousAgainstDynamics in RigidBodies[0].fFlags) or
32102 (krbfContinuousAgainstDynamics in RigidBodies[1].fFlags)))) then begin
32103 ContactPair:=ContactPair^.Next;
32104 continue;
32105 end;
32106
32107 { if (Vector3Length(RigidBodies[0].LinearVelocity)<EPSILON) and
32108 (Vector3Length(RigidBodies[0].AngularVelocity)<EPSILON) and
32109 (Vector3Length(RigidBodies[1].LinearVelocity)<EPSILON) and
32110 (Vector3Length(RigidBodies[1].AngularVelocity)<EPSILON) then begin
32111 ContactPair:=ContactPair^.Next;
32112 continue;
32113 end;{}
32114
32115 // Compute TOI for this elligable contact and place sweeps onto the same time interval
32116 if RigidBodies[0].fSweep.Alpha0<RigidBodies[1].fSweep.Alpha0 then begin
32117 Alpha0:=RigidBodies[1].fSweep.Alpha0;
32118 SweepAdvance(RigidBodies[0].fSweep,Alpha0);
32119 end else if RigidBodies[1].fSweep.Alpha0<RigidBodies[0].fSweep.Alpha0 then begin
32120 Alpha0:=RigidBodies[0].fSweep.Alpha0;
32121 SweepAdvance(RigidBodies[1].fSweep,Alpha0);
32122 end else begin
32123 Alpha0:=RigidBodies[0].fSweep.Alpha0;
32124 end;
32125
32126 Assert(Alpha0<1.0);
32127
32128 Beta:=0.0;
32129 if GetTimeOfImpact(ContactPair^.Shapes[0],
32130 SweepTermNormalize(RigidBodies[0].fSweep),
32131 ContactPair^.Shapes[1],
32132 ContactPair^.ElementIndex,
32133 SweepTermNormalize(RigidBodies[1].fSweep),
32134 TimeStep,
32135 0,
32136 Beta) then begin
32137 Alpha:=Min(Alpha0+((1.0-Alpha0)*Beta),1.0);
32138 end;
32139
32140 ContactPair^.TimeOfImpact:=Alpha;
32141 ContactPair^.Flags:=ContactPair^.Flags+[kcfTimeOfImpact];
32142
32143 end;
32144
32145 if MinimumAlpha>Alpha then begin
32146 MinimumAlpha:=Alpha;
32147 MinimumContactPair:=ContactPair;
32148 end;
32149
32150 // inc(c);
32151 ContactPair:=ContactPair^.Next;
32152
32153 end;
32154
32155 // End loop if no minimum contact exists (all have been processed, if any existed) or if time is almost exhausted
32156 if (not assigned(MinimumContactPair)) or ((1.0-EPSILON)<MinimumAlpha) then begin
32157 break;
32158 end;
32159
32160 { if c>=0 then begin
32161 writeln(TryIndex:4,' ',c:4,' ',MinimumAlpha:1:8);
32162 end;{}
32163
32164 RigidBodies[0]:=MinimumContactPair^.Shapes[0].fRigidBody;
32165 RigidBodies[1]:=MinimumContactPair^.Shapes[1].fRigidBody;
32166
32167 BackupSweeps[0]:=RigidBodies[0].fSweep;
32168 BackupSweeps[1]:=RigidBodies[1].fSweep;
32169
32170 RigidBodies[0].Advance(MinimumAlpha);
32171 RigidBodies[1].Advance(MinimumAlpha);
32172
32173 MinimumContactPair^.DetectCollisions(fContactManager,fTriangleShapes[0],0,false,0.0);
32174
32175 MinimumContactPair^.Flags:=MinimumContactPair^.Flags-[kcfTimeOfImpact];
32176 inc(MinimumContactPair^.TimeOfImpactCount);
32177
32178 if (not (kcfColliding in MinimumContactPair^.Flags)) or not (kcfEnabled in MinimumContactPair^.Flags) then begin
32179 MinimumContactPair^.Flags:=MinimumContactPair^.Flags-[kcfEnabled];
32180 RigidBodies[0].fSweep:=BackupSweeps[0];
32181 RigidBodies[1].fSweep:=BackupSweeps[1];
32182 RigidBodies[0].SynchronizeTransformIncludingShapes;
32183 RigidBodies[1].SynchronizeTransformIncludingShapes;
32184 continue;
32185 end;
32186
32187 RigidBodies[0].SetToAwake;
32188 RigidBodies[1].SetToAwake;
32189
32190 if length(fIslands)<1 then begin
32191 LastCount:=length(fIslands);
32192 SetLength(fIslands,2);
32193 for SubIndex:=LastCount to length(fIslands)-1 do begin
32194 fIslands[SubIndex]:=TKraftIsland.Create(self,SubIndex);
32195 end;
32196 end;
32197
32198 CurrentRigidBody:=fRigidBodyFirst;
32199 while assigned(CurrentRigidBody) do begin
32200 CurrentRigidBody.fIsland:=nil;
32201 CurrentRigidBody.fFlags:=CurrentRigidBody.fFlags-[krbfIslandVisited,krbfIslandStatic];
32202 CurrentRigidBody:=CurrentRigidBody.fRigidBodyNext;
32203 end;
32204
32205 Island:=fIslands[0];
32206 Island.Clear;
32207 IndexA:=Island.AddRigidBody(RigidBodies[0]);
32208 IndexB:=Island.AddRigidBody(RigidBodies[1]);
32209 Island.AddContactPair(MinimumContactPair);
32210
32211 Include(RigidBodies[0].fFlags,krbfIslandVisited);
32212 Include(RigidBodies[1].fFlags,krbfIslandVisited);
32213 Include(MinimumContactPair^.Flags,kcfInIsland);
32214
32215 for Index:=0 to 1 do begin
32216
32217 RigidBody:=RigidBodies[Index];
32218
32219 if RigidBody.fRigidBodyType=krbtDynamic then begin
32220
32221 ContactPairEdge:=RigidBody.fContactPairEdgeFirst;
32222 while assigned(ContactPairEdge) do begin
32223 ContactPair:=ContactPairEdge^.ContactPair;
32224 OtherRigidBody:=ContactPairEdge^.OtherRigidBody;
32225 if (not (kcfInIsland in ContactPair^.Flags)) and not
32226 ((((ksfSensor in ContactPair^.Shapes[0].fFlags) or
32227 (ksfSensor in ContactPair^.Shapes[1].fFlags)) or
32228 ((krbfSensor in RigidBody.fFlags) or
32229 (krbfSensor in OtherRigidBody.fFlags))) or
32230 ((OtherRigidBody.fRigidBodyType=krbtDynamic) and not
32231 (fContinuousAgainstDynamics and
32232 ((krbfContinuousAgainstDynamics in RigidBody.fFlags) or
32233 (krbfContinuousAgainstDynamics in OtherRigidBody.fFlags))))) then begin
32234
32235 BackupSweeps[0]:=OtherRigidBody.fSweep;
32236 if (not (krbfIslandVisited in OtherRigidBody.fFlags)) and not assigned(OtherRigidBody.fIsland) then begin
32237 OtherRigidBody.Advance(MinimumAlpha);
32238 end;
32239
32240 ContactPair^.DetectCollisions(fContactManager,fTriangleShapes[0],0,false,0.0);
32241
32242 if (not (kcfEnabled in ContactPair^.Flags)) or not (kcfColliding in ContactPair^.Flags) then begin
32243 OtherRigidBody.fSweep:=BackupSweeps[0];
32244 OtherRigidBody.SynchronizeTransformIncludingShapes;
32245 end else begin
32246
32247 Island.AddContactPair(ContactPair);
32248 ContactPair^.Flags:=ContactPair^.Flags+[kcfInIsland];
32249
32250 if (krbfIslandVisited in OtherRigidBody.fFlags) or assigned(OtherRigidBody.fIsland) then begin
32251 Island.AddRigidBody(OtherRigidBody);
32252 Include(OtherRigidBody.fFlags,krbfIslandVisited);
32253 if OtherRigidBody.fRigidBodyType<>krbtStatic then begin
32254 OtherRigidBody.SetToAwake;
32255 end;
32256 end;
32257
32258 end;
32259
32260 end;
32261 ContactPairEdge:=ContactPairEdge^.Next;
32262 end;
32263
32264 end;
32265
32266 end;
32267
32268 Island.MergeContactPairs;
32269
32270 SubTimeStep.DeltaTime:=(1.0-MinimumAlpha)*TimeStep.DeltaTime;
32271 SubTimeStep.InverseDeltaTime:=1.0/SubTimeStep.DeltaTime;
32272 SubTimeStep.DeltaTimeRatio:=1.0;
32273 SubTimeStep.WarmStarting:=false;
32274 Island.SolveTimeOfImpact(SubTimeStep,IndexA,IndexB);
32275
32276 for Index:=0 to Island.fCountRigidBodies-1 do begin
32277 RigidBody:=Island.fRigidBodies[Index];
32278 RigidBody.fIsland:=nil;
32279 RigidBody.fFlags:=RigidBody.fFlags-[krbfIslandVisited,krbfIslandStatic];
32280 if RigidBody.fRigidBodyType=krbtDynamic then begin
32281 RigidBody.SynchronizeProxies;
32282 ContactPairEdge:=RigidBody.fContactPairEdgeFirst;
32283 while assigned(ContactPairEdge) do begin
32284 ContactPair:=ContactPairEdge^.ContactPair;
32285 ContactPair^.Flags:=ContactPair^.Flags-[kcfInIsland,kcfTimeOfImpact];
32286 ContactPairEdge:=ContactPairEdge^.Next;
32287 end;
32288 end;
32289 end;
32290
32291 fContactManager.DoBroadPhase;
32292 fContactManager.DoMidPhase;
32293 NeedUpdate:=true;
32294
32295 end;
32296
32297 if NeedUpdate then begin
32298 fContactManager.DoNarrowPhase;
32299 end;
32300
32301 end;
32302
32303 procedure TKraft.StoreWorldTransforms;
32304 var RigidBody:TKraftRigidBody;
32305 begin
32306 RigidBody:=fRigidBodyFirst;
32307 while assigned(RigidBody) do begin
32308 RigidBody.StoreWorldTransform;
32309 RigidBody:=RigidBody.fRigidBodyNext;
32310 end;
32311 end;
32312
32313 procedure TKraft.InterpolateWorldTransforms(const Alpha:TKraftScalar);
32314 var RigidBody:TKraftRigidBody;
32315 begin
32316 RigidBody:=fRigidBodyFirst;
32317 while assigned(RigidBody) do begin
32318 RigidBody.InterpolateWorldTransform(Alpha);
32319 RigidBody:=RigidBody.fRigidBodyNext;
32320 end;
32321 end;
32322
32323 procedure TKraft.Step(const ADeltaTime:TKraftScalar=0);
32324 var RigidBody:TKraftRigidBody;
32325 Constraint,NextConstraint:TKraftConstraint;
32326 {$ifdef HAS_FPU_TYPES}
32327 OldFPUPrecisionMode:TFPUPrecisionMode;
32328 OldFPUExceptionMask:TFPUExceptionMask;
32329 {$endif}
32330 OldSIMDFlags:longword;
32331 StartTime:int64;
32332 TimeStep:TKraftTimeStep;
32333 begin
32334
32335 fBroadPhaseTime:=0;
32336 fMidPhaseTime:=0;
32337 fNarrowPhaseTime:=0;
32338 fSolverTime:=0;
32339 fContinuousTime:=0;
32340 fTotalTime:=fHighResolutionTimer.GetTime;
32341
32342 if abs(ADeltaTime)<EPSILON then begin
32343 TimeStep.DeltaTime:=fWorldDeltaTime;
32344 end else begin
32345 TimeStep.DeltaTime:=ADeltaTime;
32346 end;
32347 if IsZero(TimeStep.DeltaTime) then begin
32348 TimeStep.InverseDeltaTime:=1.0;
32349 end else begin
32350 TimeStep.InverseDeltaTime:=1.0/TimeStep.DeltaTime;
32351 end;
32352 TimeStep.DeltaTimeRatio:=fLastInverseDeltaTime*TimeStep.DeltaTime;
32353 TimeStep.WarmStarting:=fWarmStarting;
32354
32355 {$ifdef DebugDraw}
32356 fContactManager.fCountDebugClipVertexLists:=0;
32357 {$endif}
32358
32359 {$ifdef HAS_FPU_TYPES}
32360 OldFPUPrecisionMode:=GetPrecisionMode;
32361 if OldFPUPrecisionMode<>PhysicsFPUPrecisionMode then begin
32362 SetPrecisionMode(PhysicsFPUPrecisionMode);
32363 end;
32364
32365 OldFPUExceptionMask:=GetExceptionMask;
32366 if OldFPUExceptionMask<>PhysicsFPUExceptionMask then begin
32367 SetExceptionMask(PhysicsFPUExceptionMask);
32368 end;
32369 {$endif}
32370
32371 OldSIMDFlags:=SIMDGetFlags;
32372
32373 SIMDSetOurFlags;
32374
32375 RigidBody:=fRigidBodyFirst;
32376 while assigned(RigidBody) do begin
32377 if assigned(RigidBody.fOnPreStep) then begin
32378 RigidBody.fOnPreStep(RigidBody,TimeStep);
32379 end;
32380 RigidBody:=RigidBody.fRigidBodyNext;
32381 end;
32382
32383 if fNewShapes then begin
32384 fNewShapes:=false;
32385 fContactManager.DoBroadPhase;
32386 fContactManager.DoMidPhase;
32387 end;
32388
32389 fContactManager.DoNarrowPhase;
32390
32391 StartTime:=fHighResolutionTimer.GetTime;
32392 Solve(TimeStep);
32393 inc(fSolverTime,fHighResolutionTimer.GetTime-StartTime);
32394
32395 case fContinuousMode of
32396 kcmMotionClamping:begin
32397 StartTime:=fHighResolutionTimer.GetTime;
32398 SolveContinuousMotionClamping(TimeStep);
32399 inc(fContinuousTime,fHighResolutionTimer.GetTime-StartTime);
32400 end;
32401 kcmTimeOfImpactSubSteps:begin
32402 if fContactPositionCorrectionMode=kpcmNonLinearGaussSeidel then begin
32403 StartTime:=fHighResolutionTimer.GetTime;
32404 SolveContinuousTimeOfImpactSubSteps(TimeStep);
32405 inc(fContinuousTime,fHighResolutionTimer.GetTime-StartTime);
32406 end else begin
32407 StartTime:=fHighResolutionTimer.GetTime;
32408 SolveContinuousMotionClamping(TimeStep);
32409 inc(fContinuousTime,fHighResolutionTimer.GetTime-StartTime);
32410 end;
32411 end;
32412 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
32413 end;
32414
32415 Constraint:=fConstraintFirst;
32416 while assigned(Constraint) do begin
32417 NextConstraint:=Constraint.fNext;
32418 if kcfFreshBreaked in Constraint.fFlags then begin
32419 Exclude(Constraint.fFlags,kcfFreshBreaked);
32420 if assigned(Constraint.fOnBreak) then begin
32421 Constraint.fOnBreak(self,Constraint);
32422 end;
32423 end;
32424 Constraint:=NextConstraint;
32425 end;
32426
32427 RigidBody:=fRigidBodyFirst;
32428 while assigned(RigidBody) do begin
32429 if RigidBody.fRigidBodyType<>krbtSTATIC then begin
32430 RigidBody.fForce:=Vector3Origin;
32431 RigidBody.fTorque:=Vector3Origin;
32432 end;
32433 if assigned(RigidBody.fOnPostStep) then begin
32434 RigidBody.fOnPostStep(RigidBody,TimeStep);
32435 end;
32436 RigidBody:=RigidBody.fRigidBodyNext;
32437 end;
32438
32439 if TimeStep.DeltaTime>0.0 then begin
32440 fLastInverseDeltaTime:=TimeStep.InverseDeltaTime;
32441 end;
32442
32443 SIMDSetFlags(OldSIMDFlags);
32444
32445 {$ifdef HAS_FPU_TYPES}
32446 if OldFPUExceptionMask<>PhysicsFPUExceptionMask then begin
32447 SetExceptionMask(OldFPUExceptionMask);
32448 end;
32449
32450 if OldFPUPrecisionMode<>PhysicsFPUPrecisionMode then begin
32451 SetPrecisionMode(OldFPUPrecisionMode);
32452 end;
32453 {$endif}
32454
32455 fTotalTime:=fHighResolutionTimer.GetTime-fTotalTime;
32456
32457 end;
32458
32459 function TKraft.TestPoint(const Point:TKraftVector3):TKraftShape;
32460 var Hit:TKraftShape;
32461 {$ifdef KraftSingleThreadedUsage}
32462 procedure QueryTree(AABBTree:TKraftDynamicAABBTree);
32463 var LocalStack:PKraftDynamicAABBTreeLongintArray;
32464 LocalStackPointer,NodeID:longint;
32465 Node:PKraftDynamicAABBTreeNode;
32466 CurrentShape:TKraftShape;
32467 begin
32468 if assigned(AABBTree) then begin
32469 if AABBTree.fRoot>=0 then begin
32470 LocalStack:=AABBTree.fStack;
32471 LocalStack^[0]:=AABBTree.fRoot;
32472 LocalStackPointer:=1;
32473 while LocalStackPointer>0 do begin
32474 dec(LocalStackPointer);
32475 NodeID:=LocalStack^[LocalStackPointer];
32476 if NodeID>=0 then begin
32477 Node:[email protected][NodeID];
32478 if AABBContains(Node^.AABB,Point) then begin
32479 if Node^.Children[0]<0 then begin
32480 CurrentShape:=Node^.UserData;
32481 if assigned(CurrentShape) and CurrentShape.TestPoint(Point) then begin
32482 Hit:=CurrentShape;
32483 exit;
32484 end;
32485 end else begin
32486 if AABBTree.fStackCapacity<=(LocalStackPointer+2) then begin
32487 AABBTree.fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+2);
32488 ReallocMem(AABBTree.fStack,AABBTree.fStackCapacity*SizeOf(longint));
32489 LocalStack:=AABBTree.fStack;
32490 end;
32491 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
32492 LocalStack^[LocalStackPointer+1]:=Node^.Children[1];
32493 inc(LocalStackPointer,2);
32494 end;
32495 end;
32496 end;
32497 end;
32498 end;
32499 end;
32500 end;
32501 {$else}
32502 procedure QueryTree(AABBTree:TKraftDynamicAABBTree);
32503 procedure ProcessNode(NodeID:longint);
32504 var Node:PKraftDynamicAABBTreeNode;
32505 CurrentShape:TKraftShape;
32506 begin
32507 if (NodeID>=0) and not assigned(Hit) then begin
32508 Node:[email protected][NodeID];
32509 if AABBContains(Node^.AABB,Point) then begin
32510 if Node^.Children[0]<0 then begin
32511 CurrentShape:=Node^.UserData;
32512 if assigned(CurrentShape) and CurrentShape.TestPoint(Point) then begin
32513 Hit:=CurrentShape;
32514 exit;
32515 end;
32516 end else begin
32517 ProcessNode(Node^.Children[0]);
32518 ProcessNode(Node^.Children[1]);
32519 end;
32520 end;
32521 end;
32522 end;
32523 begin
32524 ProcessNode(AABBTree.fRoot);
32525 end;
32526 {$endif}
32527 begin
32528 Hit:=nil;
32529 QueryTree(fStaticAABBTree);
32530 if not assigned(Hit) then begin
32531 QueryTree(fSleepingAABBTree);
32532 end;
32533 if not assigned(Hit) then begin
32534 QueryTree(fDynamicAABBTree);
32535 end;
32536 if not assigned(Hit) then begin
32537 QueryTree(fKinematicAABBTree);
32538 end;
32539 result:=Hit;
32540 end;
32541
32542 function TKraft.RayCast(const Origin,Direction:TKraftVector3;const MaxTime:TKraftScalar;var Shape:TKraftShape;var Time:TKraftScalar;var Point,Normal:TKraftVector3;const CollisionGroups:TKraftRigidBodyCollisionGroups=[low(TKraftRigidBodyCollisionGroup)..high(TKraftRigidBodyCollisionGroup)]):boolean;
32543 var Hit:boolean;
32544 {$ifdef KraftSingleThreadedUsage}
32545 procedure QueryTree(AABBTree:TKraftDynamicAABBTree);
32546 var LocalStack:PKraftDynamicAABBTreeLongintArray;
32547 LocalStackPointer,NodeID:longint;
32548 Node:PKraftDynamicAABBTreeNode;
32549 CurrentShape:TKraftShape;
32550 RayCastData:TKraftRaycastData;
32551 begin
32552 if assigned(AABBTree) then begin
32553 if AABBTree.fRoot>=0 then begin
32554 LocalStack:=AABBTree.fStack;
32555 LocalStack^[0]:=AABBTree.fRoot;
32556 LocalStackPointer:=1;
32557 while LocalStackPointer>0 do begin
32558 dec(LocalStackPointer);
32559 NodeID:=LocalStack^[LocalStackPointer];
32560 if NodeID>=0 then begin
32561 Node:[email protected][NodeID];
32562 if AABBRayIntersect(Node^.AABB,Origin,Direction) then begin
32563 if Node^.Children[0]<0 then begin
32564 CurrentShape:=Node^.UserData;
32565 RayCastData.Origin:=Origin;
32566 RayCastData.Direction:=Direction;
32567 RayCastData.MaxTime:=MaxTime;
32568 if (assigned(CurrentShape) and (assigned(CurrentShape.fRigidBody) and ((CurrentShape.fRigidBody.fCollisionGroups*CollisionGroups)<>[]))) and CurrentShape.RayCast(RayCastData) then begin
32569 if (Hit and (RayCastData.TimeOfImpact<Time)) or not Hit then begin
32570 Hit:=true;
32571 Time:=RayCastData.TimeOfImpact;
32572 Point:=RayCastData.Point;
32573 Normal:=RayCastData.Normal;
32574 Shape:=CurrentShape;
32575 end;
32576 end;
32577 end else begin
32578 if AABBTree.fStackCapacity<=(LocalStackPointer+2) then begin
32579 AABBTree.fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+2);
32580 ReallocMem(AABBTree.fStack,AABBTree.fStackCapacity*SizeOf(longint));
32581 LocalStack:=AABBTree.fStack;
32582 end;
32583 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
32584 LocalStack^[LocalStackPointer+1]:=Node^.Children[1];
32585 inc(LocalStackPointer,2);
32586 end;
32587 end;
32588 end;
32589 end;
32590 end;
32591 end;
32592 end;
32593 {$else}
32594 procedure QueryTree(AABBTree:TKraftDynamicAABBTree);
32595 procedure ProcessNode(NodeID:longint);
32596 var Node:PKraftDynamicAABBTreeNode;
32597 CurrentShape:TKraftShape;
32598 RayCastData:TKraftRaycastData;
32599 begin
32600 if NodeID>=0 then begin
32601 Node:[email protected][NodeID];
32602 if AABBRayIntersect(Node^.AABB,Origin,Direction) then begin
32603 if Node^.Children[0]<0 then begin
32604 CurrentShape:=Node^.UserData;
32605 RayCastData.Origin:=Origin;
32606 RayCastData.Direction:=Direction;
32607 RayCastData.MaxTime:=MaxTime;
32608 if (assigned(CurrentShape) and (assigned(CurrentShape.fRigidBody) and ((CurrentShape.fRigidBody.fCollisionGroups*CollisionGroups)<>[]))) and CurrentShape.RayCast(RayCastData) then begin
32609 if (Hit and (RayCastData.TimeOfImpact<Time)) or not Hit then begin
32610 Hit:=true;
32611 Time:=RayCastData.TimeOfImpact;
32612 Point:=RayCastData.Point;
32613 Normal:=RayCastData.Normal;
32614 Shape:=CurrentShape;
32615 end;
32616 end;
32617 end else begin
32618 ProcessNode(Node^.Children[0]);
32619 ProcessNode(Node^.Children[1]);
32620 end;
32621 end;
32622 end;
32623 end;
32624 begin
32625 ProcessNode(AABBTree.fRoot);
32626 end;
32627 {$endif}
32628 begin
32629 Hit:=false;
32630 Time:=MaxTime;
32631 QueryTree(fStaticAABBTree);
32632 QueryTree(fSleepingAABBTree);
32633 QueryTree(fDynamicAABBTree);
32634 QueryTree(fKinematicAABBTree);
32635 result:=Hit;
32636 end;
32637
32638 function TKraft.PushSphere(var Center:TKraftVector3;const Radius:TKraftScalar;const CollisionGroups:TKraftRigidBodyCollisionGroups=[low(TKraftRigidBodyCollisionGroup)..high(TKraftRigidBodyCollisionGroup)];const TryIterations:longint=4;const OnPushSphereShapeContactHook:TKraftOnPushSphereShapeContactHook=nil):boolean;
32639 var Hit:boolean;
32640 AABB:TKraftAABB;
32641 Sphere:TKraftSphere;
32642 SumMinimumTranslationVector:TKraftVector3;
32643 Count:longint;
32644 procedure CollideSphereWithSphere(Shape:TKraftShapeSphere); {$ifdef caninline}inline;{$endif}
32645 var Position,Normal:TKraftVector3;
32646 Depth:TKraftScalar;
32647 begin
32648 Position:=Vector3Sub(Sphere.Center,Vector3TermMatrixMul(Shape.fLocalCenterOfMass,Shape.fWorldTransform));
32649 if Vector3Length(Position)<(Sphere.Radius+Shape.fRadius) then begin
32650 Normal:=Vector3SafeNorm(Position);
32651 Depth:=(Sphere.Radius+Shape.fRadius)-Vector3Length(Position);
32652 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Normal,Depth));
32653 inc(Count);
32654 Hit:=true;
32655 if assigned(OnPushSphereShapeContactHook) then begin
32656 OnPushSphereShapeContactHook(Shape);
32657 end;
32658 end;
32659 end;
32660 procedure CollideSphereWithCapsule(Shape:TKraftShapeCapsule); {$ifdef caninline}inline;{$endif}
32661 var Alpha,HalfLength,r1,r2,d,d1:TKraftScalar;
32662 Center,Position,Normal,GeometryDirection:TKraftVector3;
32663 begin
32664 r1:=Shape.fRadius;
32665 r2:=Sphere.Radius;
32666 GeometryDirection:=Vector3(Shape.fWorldTransform[1,0],Shape.fWorldTransform[1,1],Shape.fWorldTransform[1,2]);
32667 Center:=Vector3TermMatrixMul(Shape.fLocalCenterOfMass,Shape.fWorldTransform);
32668 Alpha:=(GeometryDirection.x*(Sphere.Center.x-Center.x))+
32669 (GeometryDirection.y*(Sphere.Center.y-Center.y))+
32670 (GeometryDirection.z*(Sphere.Center.z-Center.z));
32671 HalfLength:=Shape.fHeight*0.5;
32672 if Alpha>HalfLength then begin
32673 Alpha:=HalfLength;
32674 end else if alpha<-HalfLength then begin
32675 Alpha:=-HalfLength;
32676 end;
32677 Position:=Vector3Add(Center,Vector3ScalarMul(GeometryDirection,Alpha));
32678 d:=Vector3Dist(Position,Sphere.Center);
32679 if d<=(r1+r2) then begin
32680 if d<=EPSILON then begin
32681 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Vector3XAxis,r1+r2));
32682 end else begin
32683 d1:=1.0/d;
32684 Normal:=Vector3Neg(Vector3ScalarMul(Vector3Sub(Position,Sphere.Center),d1));
32685 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Normal,(r1+r2)-d));
32686 end;
32687 inc(Count);
32688 Hit:=true;
32689 if assigned(OnPushSphereShapeContactHook) then begin
32690 OnPushSphereShapeContactHook(Shape);
32691 end;
32692 end;
32693 end;
32694 procedure CollideSphereWithConvexHull(Shape:TKraftShapeConvexHull); {$ifdef caninline}inline;{$endif}
32695 var FaceIndex,ClosestFaceIndex,VertexIndex:longint;
32696 Distance,ClosestDistance,BestClosestPointDistance,d:TKraftScalar;
32697 SphereCenter,Normal,ClosestPoint,{BestClosestPoint,}BestClosestPointNormal,ab,ap,a,b,v,n:TKraftVector3;
32698 InsideSphere,InsidePolygon,HasBestClosestPoint:boolean;
32699 Face:PKraftConvexHullFace;
32700 begin
32701 BestClosestPointDistance:=MAX_SCALAR;
32702 BestClosestPointNormal:=Vector3Origin;
32703 HasBestClosestPoint:=false;
32704 ClosestPoint:=Vector3Origin;
32705 ClosestDistance:=MAX_SCALAR;
32706 ClosestFaceIndex:=-1;
32707 InsideSphere:=true;
32708 SphereCenter:=Vector3TermMatrixMulInverted(Sphere.Center,Shape.fWorldTransform);
32709 for FaceIndex:=0 to Shape.fConvexHull.fCountFaces-1 do begin
32710 Face:[email protected][FaceIndex];
32711 Distance:=PlaneVectorDistance(Face^.Plane,SphereCenter);
32712 if Distance>0.0 then begin
32713 // sphere center is not inside in the convex hull . . .
32714 if Distance<Sphere.Radius then begin
32715 // but touching . . .
32716 if Face^.CountVertices>0 then begin
32717 InsidePolygon:=true;
32718 n:=Face^.Plane.Normal;
32719 b:=Shape.fConvexHull.fVertices[Face^.Vertices[Face^.CountVertices-1]].Position;
32720 for VertexIndex:=0 to Face^.CountVertices-1 do begin
32721 a:=b;
32722 b:=Shape.fConvexHull.fVertices[Face^.Vertices[VertexIndex]].Position;
32723 ab:=Vector3Sub(b,a);
32724 ap:=Vector3Sub(SphereCenter,a);
32725 v:=Vector3Cross(ab,n);
32726 if Vector3Dot(ap,v)>0.0 then begin
32727 d:=Vector3LengthSquared(ab);
32728 if d<>0.0 then begin
32729 d:=Vector3Dot(ab,ap)/d;
32730 end else begin
32731 d:=0.0;
32732 end;
32733 ClosestPoint:=Vector3Lerp(a,b,d);
32734 InsidePolygon:=false;
32735 break;
32736 end;
32737 end;
32738 if InsidePolygon then begin
32739 // sphere is directly touching the convex hull . . .
32740 Normal:=Vector3SafeNorm(Vector3TermMatrixMulBasis(Shape.fConvexHull.fFaces[FaceIndex].Plane.Normal,Shape.fWorldTransform));
32741 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Normal,Sphere.Radius-Distance));
32742 inc(Count);
32743 Hit:=true;
32744 exit;
32745 end else begin
32746 // the sphere may not be directly touching the polyhedron, but it may be touching a point or an edge, if the distance between
32747 // the closest point on the poly and the center of the sphere is less than the sphere radius we have a hit.
32748 Normal:=Vector3Sub(SphereCenter,ClosestPoint);
32749 if Vector3LengthSquared(Normal)<sqr(Sphere.Radius) then begin
32750 Normal:=Vector3TermMatrixMulBasis(Normal,Shape.fWorldTransform);
32751 Distance:=Vector3LengthNormalize(Normal);
32752 if (not HasBestClosestPoint) or (BestClosestPointDistance>Distance) then begin
32753 HasBestClosestPoint:=true;
32754 BestClosestPointDistance:=Distance;
32755 //BestClosestPoint:=ClosestPoint;
32756 BestClosestPointNormal:=Normal;
32757 end;
32758 end;
32759 end;
32760 end;
32761 end;
32762 InsideSphere:=false;
32763 end else if InsideSphere and ((ClosestFaceIndex<0) or (ClosestDistance>abs(Distance))) then begin
32764 ClosestDistance:=abs(Distance);
32765 ClosestFaceIndex:=FaceIndex;
32766 end;
32767 end;
32768 if InsideSphere and (ClosestFaceIndex>=0) then begin
32769 // the sphere center is inside the convex hull . . .
32770 Normal:=Vector3SafeNorm(Vector3TermMatrixMulBasis(Shape.fConvexHull.fFaces[ClosestFaceIndex].Plane.Normal,Shape.fWorldTransform));
32771 SumMinimumTranslationVector:=Vector3Sub(SumMinimumTranslationVector,Vector3ScalarMul(Normal,ClosestDistance-Sphere.Radius));
32772 inc(Count);
32773 Hit:=true;
32774 if assigned(OnPushSphereShapeContactHook) then begin
32775 OnPushSphereShapeContactHook(Shape);
32776 end;
32777 end else if HasBestClosestPoint then begin
32778 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(BestClosestPointNormal),Sphere.Radius-BestClosestPointDistance));
32779 inc(Count);
32780 Hit:=true;
32781 if assigned(OnPushSphereShapeContactHook) then begin
32782 OnPushSphereShapeContactHook(Shape);
32783 end;
32784 end;
32785 end;
32786 procedure CollideSphereWithBox(Shape:TKraftShapeBox); {$ifdef caninline}inline;{$endif}
32787 //const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
32788 var IntersectionDist,ContactDist,DistSqr,Distance,FaceDist,MinDist:TKraftScalar;
32789 SphereRelativePosition,ClosestPoint,Normal:TKraftVector3;
32790 Axis,AxisSign:longint;
32791 begin
32792 SphereRelativePosition:=Vector3TermMatrixMulInverted(Sphere.Center,Shape.fWorldTransform);
32793 ClosestPoint.x:=Min(Max(SphereRelativePosition.x,-Shape.fExtents.x),Shape.fExtents.x);
32794 ClosestPoint.y:=Min(Max(SphereRelativePosition.y,-Shape.fExtents.y),Shape.fExtents.y);
32795 ClosestPoint.z:=Min(Max(SphereRelativePosition.z,-Shape.fExtents.z),Shape.fExtents.z);
32796 Normal:=Vector3Sub(SphereRelativePosition,ClosestPoint);
32797 DistSqr:=Vector3LengthSquared(Normal);
32798 IntersectionDist:=Sphere.Radius;
32799 ContactDist:=IntersectionDist+EPSILON;
32800 if DistSqr<=sqr(ContactDist) then begin
32801 if DistSqr<=EPSILON then begin
32802 begin
32803 FaceDist:=Shape.fExtents.x-SphereRelativePosition.x;
32804 MinDist:=FaceDist;
32805 Axis:=0;
32806 AxisSign:=1;
32807 end;
32808 begin
32809 FaceDist:=Shape.fExtents.x+SphereRelativePosition.x;
32810 if FaceDist<MinDist then begin
32811 MinDist:=FaceDist;
32812 Axis:=0;
32813 AxisSign:=-1;
32814 end;
32815 end;
32816 begin
32817 FaceDist:=Shape.fExtents.y-SphereRelativePosition.y;
32818 if FaceDist<MinDist then begin
32819 MinDist:=FaceDist;
32820 Axis:=1;
32821 AxisSign:=1;
32822 end;
32823 end;
32824 begin
32825 FaceDist:=Shape.fExtents.y+SphereRelativePosition.y;
32826 if FaceDist<MinDist then begin
32827 MinDist:=FaceDist;
32828 Axis:=1;
32829 AxisSign:=-1;
32830 end;
32831 end;
32832 begin
32833 FaceDist:=Shape.fExtents.z-SphereRelativePosition.z;
32834 if FaceDist<MinDist then begin
32835 MinDist:=FaceDist;
32836 Axis:=2;
32837 AxisSign:=1;
32838 end;
32839 end;
32840 begin
32841 FaceDist:=Shape.fExtents.z+SphereRelativePosition.z;
32842 if FaceDist<MinDist then begin
32843 MinDist:=FaceDist;
32844 Axis:=2;
32845 AxisSign:=-1;
32846 end;
32847 end;
32848 ClosestPoint:=SphereRelativePosition;
32849 ClosestPoint.xyz[Axis]:=Shape.fExtents.xyz[Axis]*AxisSign;
32850 Normal:=Vector3Origin;
32851 Normal.xyz[Axis]:=AxisSign;
32852 Distance:=-MinDist;
32853 end else begin
32854 Distance:=Vector3LengthNormalize(Normal);
32855 end;
32856 SumMinimumTranslationVector:=Vector3Sub(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(Vector3TermMatrixMulBasis(Normal,Shape.fWorldTransform)),Distance-IntersectionDist));
32857 inc(Count);
32858 Hit:=true;
32859 if assigned(OnPushSphereShapeContactHook) then begin
32860 OnPushSphereShapeContactHook(Shape);
32861 end;
32862 end;
32863 end;
32864 procedure CollideSphereWithPlane(Shape:TKraftShapePlane); {$ifdef caninline}inline;{$endif}
32865 var Distance:TKraftScalar;
32866 SphereCenter:TKraftVector3;
32867 begin
32868 SphereCenter:=Vector3TermMatrixMulInverted(Sphere.Center,Shape.fWorldTransform);
32869 Distance:=PlaneVectorDistance(Shape.fPlane,SphereCenter);
32870 if Distance<=Sphere.Radius then begin
32871 SumMinimumTranslationVector:=Vector3Sub(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(Vector3TermMatrixMulBasis(Shape.fPlane.Normal,Shape.fWorldTransform)),Distance-Sphere.Radius));
32872 inc(Count);
32873 Hit:=true;
32874 if assigned(OnPushSphereShapeContactHook) then begin
32875 OnPushSphereShapeContactHook(Shape);
32876 end;
32877 end;
32878 end;
32879 procedure CollideSphereWithTriangle(Shape:TKraftShapeTriangle);
32880 const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
32881 var i:longint;
32882 Radius,RadiusWithThreshold,DistanceFromPlane,ContactRadiusSqr,DistanceSqr:TKraftScalar;
32883 SphereCenter,Normal,P0ToCenter,ContactPoint,NearestOnEdge,ContactToCenter:TKraftVector3;
32884 IsInsideContactPlane,HasContact:boolean;
32885 v:array[0..2] of PKraftVector3;
32886 begin
32887 v[0]:[email protected][0].Position;
32888 v[1]:[email protected][1].Position;
32889 v[2]:[email protected][2].Position;
32890 SphereCenter:=Vector3TermMatrixMulInverted(Sphere.Center,Shape.fWorldTransform);
32891 Radius:=Sphere.Radius;
32892 RadiusWithThreshold:=Radius+EPSILON;
32893 Normal:=Shape.fConvexHull.fFaces[0].Plane.Normal;// Vector3SafeNorm(Vector3Cross(Vector3Sub(v[1]^,v[0]^),Vector3Sub(v[2]^,v[0]^)));
32894 P0ToCenter:=Vector3Sub(SphereCenter,v[0]^);
32895 DistanceFromPlane:=Vector3Dot(P0ToCenter,Normal);
32896 if DistanceFromPlane<0.0 then begin
32897 DistanceFromPlane:=-DistanceFromPlane;
32898 Normal:=Vector3Neg(Normal);
32899 end;
32900 IsInsideContactPlane:=DistanceFromPlane<RadiusWithThreshold;
32901 HasContact:=false;
32902 ContactPoint:=Vector3Origin;
32903 ContactRadiusSqr:=sqr(RadiusWithThreshold);
32904 if IsInsideContactPlane then begin
32905 if PointInTriangle(v[0]^,v[1]^,v[2]^,Normal,SphereCenter) then begin
32906 HasContact:=true;
32907 ContactPoint:=Vector3Sub(SphereCenter,Vector3ScalarMul(Normal,DistanceFromPlane));
32908 end else begin
32909 for i:=0 to 2 do begin
32910 DistanceSqr:=SegmentSqrDistance(v[i]^,v[ModuloThree[i+1]]^,SphereCenter,NearestOnEdge);
32911 if DistanceSqr<ContactRadiusSqr then begin
32912 HasContact:=true;
32913 ContactPoint:=NearestOnEdge;
32914 end;
32915 end;
32916 end;
32917 end;
32918 if HasContact then begin
32919 ContactToCenter:=Vector3Sub(SphereCenter,ContactPoint);
32920 DistanceSqr:=Vector3LengthSquared(ContactToCenter);
32921 if DistanceSqr<ContactRadiusSqr then begin
32922 if DistanceSqr>EPSILON then begin
32923 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(Vector3TermMatrixMulBasis(ContactToCenter,Shape.fWorldTransform)),Radius-sqrt(DistanceSqr)));
32924 end else begin
32925 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(Vector3TermMatrixMulBasis(Normal,Shape.fWorldTransform)),Radius));
32926 end;
32927 inc(Count);
32928 Hit:=true;
32929 if assigned(OnPushSphereShapeContactHook) then begin
32930 OnPushSphereShapeContactHook(Shape);
32931 end;
32932 end;
32933 end;
32934 end;
32935 procedure CollideSphereWithMesh(Shape:TKraftShapeMesh); {$ifdef caninline}inline;{$endif}
32936 const ModuloThree:array[0..5] of longint=(0,1,2,0,1,2);
32937 var i,SkipListNodeIndex,TriangleIndex:longint;
32938 Radius,RadiusWithThreshold,DistanceFromPlane,ContactRadiusSqr,DistanceSqr:TKraftScalar;
32939 SphereCenter,Normal,P0ToCenter,ContactPoint,NearestOnEdge,ContactToCenter:TKraftVector3;
32940 IsInsideContactPlane,HasContact:boolean;
32941 SkipListNode:PKraftMeshSkipListNode;
32942 Triangle:PKraftMeshTriangle;
32943 AABB:TKraftAABB;
32944 Vertices:array[0..2] of PKraftVector3;
32945 WasHit:boolean;
32946 begin
32947 WasHit:=false;
32948 SphereCenter:=Vector3TermMatrixMulInverted(Sphere.Center,Shape.fWorldTransform);
32949 Radius:=Sphere.Radius;
32950 RadiusWithThreshold:=Radius+0.1;
32951 AABB.Min.x:=SphereCenter.x-RadiusWithThreshold;
32952 AABB.Min.y:=SphereCenter.y-RadiusWithThreshold;
32953 AABB.Min.z:=SphereCenter.z-RadiusWithThreshold;
32954 AABB.Max.x:=SphereCenter.x+RadiusWithThreshold;
32955 AABB.Max.y:=SphereCenter.y+RadiusWithThreshold;
32956 AABB.Max.z:=SphereCenter.z+RadiusWithThreshold;
32957 RadiusWithThreshold:=Radius+EPSILON;
32958 SkipListNodeIndex:=0;
32959 while SkipListNodeIndex<Shape.fMesh.fCountSkipListNodes do begin
32960 SkipListNode:[email protected][SkipListNodeIndex];
32961 if AABBIntersect(SkipListNode^.AABB,AABB) then begin
32962 TriangleIndex:=SkipListNode^.TriangleIndex;
32963 while TriangleIndex>=0 do begin
32964 Triangle:[email protected][TriangleIndex];
32965 Vertices[0]:[email protected][Triangle^.Vertices[0]];
32966 Vertices[1]:[email protected][Triangle^.Vertices[1]];
32967 Vertices[2]:[email protected][Triangle^.Vertices[2]];
32968 Normal:=Vector3SafeNorm(Vector3Cross(Vector3Sub(Vertices[1]^,Vertices[0]^),Vector3Sub(Vertices[2]^,Vertices[0]^)));
32969 P0ToCenter:=Vector3Sub(SphereCenter,Vertices[0]^);
32970 DistanceFromPlane:=Vector3Dot(P0ToCenter,Normal);
32971 if DistanceFromPlane<0.0 then begin
32972 DistanceFromPlane:=-DistanceFromPlane;
32973 Normal:=Vector3Neg(Normal);
32974 end;
32975 IsInsideContactPlane:=DistanceFromPlane<RadiusWithThreshold;
32976 HasContact:=false;
32977 ContactPoint:=Vector3Origin;
32978 ContactRadiusSqr:=sqr(RadiusWithThreshold);
32979 if IsInsideContactPlane then begin
32980 if PointInTriangle(Vertices[0]^,Vertices[1]^,Vertices[2]^,Normal,SphereCenter) then begin
32981 HasContact:=true;
32982 ContactPoint:=Vector3Sub(SphereCenter,Vector3ScalarMul(Normal,DistanceFromPlane));
32983 end else begin
32984 for i:=0 to 2 do begin
32985 DistanceSqr:=SegmentSqrDistance(Vertices[i]^,Vertices[ModuloThree[i+1]]^,SphereCenter,NearestOnEdge);
32986 if DistanceSqr<ContactRadiusSqr then begin
32987 HasContact:=true;
32988 ContactPoint:=NearestOnEdge;
32989 end;
32990 end;
32991 end;
32992 end;
32993 if HasContact then begin
32994 ContactToCenter:=Vector3Sub(SphereCenter,ContactPoint);
32995 DistanceSqr:=Vector3LengthSquared(ContactToCenter);
32996 if DistanceSqr<ContactRadiusSqr then begin
32997 if DistanceSqr>EPSILON then begin
32998 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(Vector3TermMatrixMulBasis(ContactToCenter,Shape.fWorldTransform)),Radius-sqrt(DistanceSqr)));
32999 end else begin
33000 SumMinimumTranslationVector:=Vector3Add(SumMinimumTranslationVector,Vector3ScalarMul(Vector3SafeNorm(Vector3TermMatrixMulBasis(Normal,Shape.fWorldTransform)),Radius));
33001 end;
33002 inc(Count);
33003 Hit:=true;
33004 WasHit:=true;
33005 end;
33006 end;
33007 TriangleIndex:=Triangle^.Next;
33008 end;
33009 inc(SkipListNodeIndex);
33010 end else begin
33011 SkipListNodeIndex:=SkipListNode^.SkipToNodeIndex;
33012 end;
33013 end;
33014 if WasHit then begin
33015 if assigned(OnPushSphereShapeContactHook) then begin
33016 OnPushSphereShapeContactHook(Shape);
33017 end;
33018 end;
33019 end;
33020 {$ifdef KraftSingleThreadedUsage}
33021 procedure QueryTree(AABBTree:TKraftDynamicAABBTree);
33022 var LocalStack:PKraftDynamicAABBTreeLongintArray;
33023 LocalStackPointer,NodeID:longint;
33024 Node:PKraftDynamicAABBTreeNode;
33025 CurrentShape:TKraftShape;
33026 begin
33027 if assigned(AABBTree) then begin
33028 if AABBTree.fRoot>=0 then begin
33029 LocalStack:=AABBTree.fStack;
33030 LocalStack^[0]:=AABBTree.fRoot;
33031 LocalStackPointer:=1;
33032 while LocalStackPointer>0 do begin
33033 dec(LocalStackPointer);
33034 NodeID:=LocalStack^[LocalStackPointer];
33035 if NodeID>=0 then begin
33036 Node:[email protected][NodeID];
33037 if AABBIntersect(Node^.AABB,AABB) then begin
33038 if Node^.Children[0]<0 then begin
33039 CurrentShape:=Node^.UserData;
33040 if assigned(CurrentShape) and (assigned(CurrentShape.fRigidBody) and ((CurrentShape.fRigidBody.fCollisionGroups*CollisionGroups)<>[])) then begin
33041 case CurrentShape.fShapeType of
33042 kstSphere:begin
33043 CollideSphereWithSphere(TKraftShapeSphere(CurrentShape));
33044 end;
33045 kstCapsule:begin
33046 CollideSphereWithCapsule(TKraftShapeCapsule(CurrentShape));
33047 end;
33048 kstConvexHull:begin
33049 CollideSphereWithConvexHull(TKraftShapeConvexHull(CurrentShape));
33050 end;
33051 kstBox:begin
33052 CollideSphereWithBox(TKraftShapeBox(CurrentShape));
33053 end;
33054 kstPlane:begin
33055 CollideSphereWithPlane(TKraftShapePlane(CurrentShape));
33056 end;
33057 kstTriangle:begin
33058 CollideSphereWithTriangle(TKraftShapeTriangle(CurrentShape));
33059 end;
33060 kstMesh:begin
33061 CollideSphereWithMesh(TKraftShapeMesh(CurrentShape));
33062 end;
33063 end;
33064 end;
33065 end else begin
33066 if AABBTree.fStackCapacity<=(LocalStackPointer+2) then begin
33067 AABBTree.fStackCapacity:=RoundUpToPowerOfTwo(LocalStackPointer+2);
33068 ReallocMem(AABBTree.fStack,AABBTree.fStackCapacity*SizeOf(longint));
33069 LocalStack:=AABBTree.fStack;
33070 end;
33071 LocalStack^[LocalStackPointer+0]:=Node^.Children[0];
33072 LocalStack^[LocalStackPointer+1]:=Node^.Children[1];
33073 inc(LocalStackPointer,2);
33074 end;
33075 end;
33076 end;
33077 end;
33078 end;
33079 end;
33080 end;
33081 {$else}
33082 procedure QueryTree(AABBTree:TKraftDynamicAABBTree);
33083 procedure ProcessNode(NodeID:longint);
33084 var Node:PKraftDynamicAABBTreeNode;
33085 CurrentShape:TKraftShape;
33086 begin
33087 if NodeID>=0 then begin
33088 Node:[email protected][NodeID];
33089 if AABBIntersect(Node^.AABB,AABB) then begin
33090 if Node^.Children[0]<0 then begin
33091 CurrentShape:=Node^.UserData;
33092 if assigned(CurrentShape) and (assigned(CurrentShape.fRigidBody) and ((CurrentShape.fRigidBody.fCollisionGroups*CollisionGroups)<>[])) then begin
33093 case CurrentShape.fShapeType of
33094 kstSphere:begin
33095 CollideSphereWithSphere(TKraftShapeSphere(CurrentShape));
33096 end;
33097 kstCapsule:begin
33098 CollideSphereWithCapsule(TKraftShapeCapsule(CurrentShape));
33099 end;
33100 kstConvexHull:begin
33101 CollideSphereWithConvexHull(TKraftShapeConvexHull(CurrentShape));
33102 end;
33103 kstBox:begin
33104 CollideSphereWithBox(TKraftShapeBox(CurrentShape));
33105 end;
33106 kstPlane:begin
33107 CollideSphereWithPlane(TKraftShapePlane(CurrentShape));
33108 end;
33109 kstTriangle:begin
33110 CollideSphereWithTriangle(TKraftShapeTriangle(CurrentShape));
33111 end;
33112 kstMesh:begin
33113 CollideSphereWithMesh(TKraftShapeMesh(CurrentShape));
33114 end;
33115 else ; // CGE: avoid "Warning: Case statement does not handle all possible cases" with new FPC, TODO: Submit to Kraft
33116 end;
33117 end;
33118 end else begin
33119 ProcessNode(Node^.Children[0]);
33120 ProcessNode(Node^.Children[1]);
33121 end;
33122 end;
33123 end;
33124 end;
33125 begin
33126 ProcessNode(AABBTree.fRoot);
33127 end;
33128 {$endif}
33129 var TryCounter:longint;
33130 begin
33131 result:=false;
33132 for TryCounter:=1 to TryIterations do begin
33133 Hit:=false;
33134 AABB.Min.x:=Center.x-Radius;
33135 AABB.Min.y:=Center.y-Radius;
33136 AABB.Min.z:=Center.z-Radius;
33137 AABB.Max.x:=Center.x+Radius;
33138 AABB.Max.y:=Center.y+Radius;
33139 AABB.Max.z:=Center.z+Radius;
33140 Sphere.Center:=Center;
33141 Sphere.Radius:=Radius;
33142 SumMinimumTranslationVector:=Vector3Origin;
33143 Count:=0;
33144 QueryTree(fStaticAABBTree);
33145 QueryTree(fSleepingAABBTree);
33146 QueryTree(fDynamicAABBTree);
33147 QueryTree(fKinematicAABBTree);
33148 result:=result or Hit;
33149 if (Count>0) and not IsZero(Vector3LengthSquared(SumMinimumTranslationVector)) then begin
33150 Center.x:=Center.x+(SumMinimumTranslationVector.x/Count);
33151 Center.y:=Center.y+(SumMinimumTranslationVector.y/Count);
33152 Center.z:=Center.z+(SumMinimumTranslationVector.z/Count);
33153 end else begin
33154 break;
33155 end;
33156 end;
33157 end;
33158
33159 function TKraft.GetDistance(const ShapeA,ShapeB:TKraftShape):TKraftScalar;
33160 var GJK:TKraftGJK;
33161 begin
33162 GJK.CachedSimplex:=nil;
33163 GJK.Simplex.Count:=0;
33164 GJK.Shapes[0]:=ShapeA;
33165 GJK.Shapes[1]:=ShapeB;
33166 GJK.Transforms[0]:[email protected];
33167 GJK.Transforms[1]:[email protected];
33168 GJK.UseRadii:=false;
33169 GJK.Run;
33170 result:=GJK.Distance;
33171 end;
33172
33173 initialization
33174 CheckCPU;
33175 end.