Debian Codegraph @

src/castlescript/castlecurves.pas

raw
1 {
2 Copyright 2004-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { 3D curves (TCurve and basic descendants). }
17 unit CastleCurves;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, Generics.Collections, DOM,
24 CastleVectors, CastleBoxes, CastleUtils, CastleScript,
25 CastleClassUtils, CastleFrustum, X3DNodes;
26
27 type
28 ECurveFileInvalid = class(Exception);
29
30 { 3D curve, a set of points defined by a continuous function @link(Point)
31 for arguments within [TBegin, TEnd]. }
32 TCurve = class
33 private
34 FTBegin, FTEnd: Single;
35 protected
36 procedure LoadFromElement(const E: TDOMElement); virtual;
37 procedure SaveToStream(const Stream: TStream); virtual;
38 public
39 const
40 DefaultSegments = 32;
41
42 constructor Create;
43
44 { The valid range of curve function argument. Must be TBegin <= TEnd.
45 @groupBegin }
46 property TBegin: Single read FTBegin write FTBegin {$ifdef FPC}default 0{$endif};
47 property TEnd: Single read FTEnd write FTEnd {$ifdef FPC}default 1{$endif};
48 { @groupEnd }
49
50 { Curve function, for each parameter value determine the 3D point.
51 This determines the actual shape of the curve.
52 This is the simplest approach to calculate points on a curve. }
53 function Point(const t: Float): TVector3; virtual; abstract;
54 function Point2D(const t: Float): TVector2;
55
56 { Curve function to work with rendered line segments begin/end points.
57 This is simply a more specialized version of @link(Point),
58 it scales the argument such that you get Point(TBegin) for I = 0
59 and you get Point(TEnd) for I = Segments. }
60 function PointOfSegment(const i, Segments: Cardinal): TVector3;
61
62 { Load the first curve defined in given XML file.
63 Hint: use https://castle-engine.io/curves_tool to design curves
64 visually. }
65 class function LoadFromFile(const Url: String): TCurve;
66
67 function BoundingBox: TBox3D; virtual; abstract;
68
69 { Represent this curve as an X3D geometry node,
70 that you can use to visualize this. }
71 function GeometryNode(const Segments: Cardinal = DefaultSegments): TAbstractGeometryNode;
72 end;
73
74 TCurveList = class({$ifdef FPC}specialize{$endif} TObjectList<TCurve>)
75 protected
76 { Override this function to add other classes inherited from
77 @link(TCurve) to a list. }
78 function GetCurveByType(const CurveTypeStr: string): TCurve; virtual;
79 public
80 { Load curves definitions from a simple XML file.
81 Hint: use https://castle-engine.io/curves_tool to design curves
82 visually. }
83 procedure LoadFromFile(const Url: String); virtual;
84
85 { Save curve definitions to a simple XML file.
86 Hint: use https://castle-engine.io/curves_tool to design curves
87 visually. }
88 procedure SaveToFile(const Url: String); virtual;
89 end;
90
91 { Curve defined by explicitly giving functions for
92 Point(t) = x(t), y(t), z(t) as CastleScript expressions. }
93 TCasScriptCurve = class(TCurve)
94 private
95 FSegmentsForBoundingBox: Cardinal;
96 FTVariable: TCasScriptFloat;
97 FFunction: array [0..2] of TCasScriptExpression;
98 FBoundingBox: TBox3D;
99 procedure SetSegmentsForBoundingBox(AValue: Cardinal);
100 procedure SetTVariable(AValue: TCasScriptFloat);
101 function GetFunction(const Index: Integer): TCasScriptExpression;
102 procedure SetFunction(const Index: Integer; const Value: TCasScriptExpression);
103 procedure UpdateBoundingBox;
104 protected
105 procedure LoadFromElement(const E: TDOMElement); override;
106 procedure SaveToStream(const Stream: TStream); override;
107 public
108 function Point(const t: Float): TVector3; override;
109
110 { XFunction, YFunction, ZFunction are functions based on variable 't'.
111 Once set, these instances become owned by this class, do not free
112 them yourself!
113 @groupBegin }
114 property XFunction: TCasScriptExpression index 0 read GetFunction write SetFunction;
115 property YFunction: TCasScriptExpression index 1 read GetFunction write SetFunction;
116 property ZFunction: TCasScriptExpression index 2 read GetFunction write SetFunction;
117 { @groupEnd }
118
119 { This is the variable controlling 't' value, embedded also in
120 XFunction, YFunction, ZFunction. This is NOT owned by this class,
121 make sure to free it yourself! }
122 property TVariable: TCasScriptFloat read FTVariable write SetTVariable;
123
124 property SegmentsForBoundingBox: Cardinal
125 read FSegmentsForBoundingBox write SetSegmentsForBoundingBox default 100;
126
127 { Simple bounding box. It is simply
128 a BoundingBox of Point(i, SegmentsForBoundingBox)
129 for i in [0 .. SegmentsForBoundingBox].
130 Subclasses may override this to calculate something more accurate. }
131 function BoundingBox: TBox3D; override;
132
133 constructor Create;
134
135 destructor Destroy; override;
136 end;
137
138 { A basic abstract class for curves determined my some set of ControlPoints.
139 Note: it is @italic(not) defined in this class any correspondence between
140 values of T (argument for Point function) and ControlPoints. }
141 TControlPointsCurve = class(TCurve)
142 strict private
143 FBoundingBox: TBox3D;
144 strict protected
145 { Using these function you can control how Convex Hull (for RenderConvexHull)
146 is calculated: CreateConvexHullPoints should return points that must be
147 in convex hull (we will run ConvexHull function on those points),
148 DestroyConvexHullPoints should finalize them.
149
150 This way you can create new object in CreateConvexHullPoints and free it in
151 DestroyConvexHullPoints, but you can also give in CreateConvexHullPoints
152 reference to some already existing object and do nothing in
153 DestroyConvexHullPoints. (we will not modify object given as
154 CreateConvexHullPoints in any way)
155
156 Default implementation in this class returns ControlPoints as
157 CreateConvexHullPoints. (and does nothing in DestroyConvexHullPoints) }
158 function CreateConvexHullPoints: TVector3List; virtual;
159 procedure DestroyConvexHullPoints(Points: TVector3List); virtual;
160 protected
161 procedure LoadFromElement(const E: TDOMElement); override;
162 procedure SaveToStream(const Stream: TStream); override;
163 public
164 ControlPoints: TVector3List;
165
166 { Bounding box of the curve.
167 In this class, it is simply a BoundingBox of ControlPoints. }
168 function BoundingBox: TBox3D; override;
169
170 { Always after changing ControlPoints or TBegin or TEnd and before calling
171 @link(Point) (or anything that uses @link(Point), like @link(BoundingBox))
172 call this method. It recalculates necessary things.
173 ControlPoints.Count must be >= 2.
174
175 When overriding: always call inherited first. }
176 procedure UpdateControlPoints; virtual;
177
178 { Constructor. }
179 constructor Create;
180
181 { Calculate initial control points by sampling given TCasScriptCurve,
182 with analytical curve equation.
183 TBegin and TEnd are copied from CasScriptCurve. }
184 constructor CreateFromEquation(CasScriptCurve: TCasScriptCurve;
185 ControlPointsCount: Cardinal);
186
187 destructor Destroy; override;
188
189 { Calculate the convex hull. Caller is responsible for freeing the result. }
190 function ConvexHull: TVector3List;
191 end;
192
193 TControlPointsCurveClass = class of TControlPointsCurve;
194
195 TControlPointsCurveList = {$ifdef FPC}specialize{$endif} TObjectList<TControlPointsCurve>;
196
197 TCubicBezier2DPoints = array [0..3] of TVector2;
198 TCubicBezier3DPoints = array [0..3] of TVector3;
199 TCubicBezier3DPointsArray = array of TCubicBezier3DPoints;
200 { Piecewise (composite) cubic Bezier curve.
201 Each segment (ControlPoints[i]..ControlPoints[i+1])
202 is a cubic Bezier curve (Bezier with 4 control points,
203 2 points in the middle are auto-calculated for max smoothness).
204
205 This is a cubic B-spline. Which is equivalent to C2 continuous
206 composite Bézier curves. See
207 https://en.wikipedia.org/wiki/Spline_%28mathematics%29 .
208 Aka Cubic B-Spline (piecewise C2-Smooth Cubic Bezier).
209
210 ControlPoints.Count may be 1 (in general,
211 for TControlPointsCurve, it must be >= 2).
212 }
213 TPiecewiseCubicBezier = class(TControlPointsCurve)
214 strict private
215 BezierCurves: TCubicBezier3DPointsArray;
216 ConvexHullPoints: TVector3List;
217 FBoundingBox: TBox3D;
218 strict protected
219 function CreateConvexHullPoints: TVector3List; override;
220 procedure DestroyConvexHullPoints(Points: TVector3List); override;
221 { Calculating additional points. }
222 procedure UpdateBezierCurves(var ABezierCurves: TCubicBezier3DPointsArray); virtual;
223 public
224 constructor Create;
225 destructor Destroy; override;
226 procedure UpdateControlPoints; override;
227 function Point(const t: Float): TVector3; override;
228 function BoundingBox: TBox3D; override;
229 end;
230
231 { Cubic (4 control points) Bezier curve (with all weights equal) in 1D. }
232 function CubicBezier1D(T: Single; const Points: TVector4): Single;
233
234 { Cubic (4 control points) Bezier curve (with all weights equal) in 2D. }
235 function CubicBezier2D(T: Single; const Points: TCubicBezier2DPoints): TVector2;
236
237 { Cubic (4 control points) Bezier curve (with all weights equal) in 3D. }
238 function CubicBezier3D(T: Single; const Points: TCubicBezier3DPoints): TVector3;
239
240 { Catmull-Rom spline. Nice way to have a function that for certain arguments
241 reaches certain values, and between interpolates smoothly.
242
243 Catmull-Rom splines are a special case of cubic Hermite splines, see
244 https://en.wikipedia.org/wiki/Cubic_Hermite_spline . }
245 function CatmullRomSpline(const X: Single; const Loop: boolean;
246 const Arguments: TSingleList;
247 const Values: TSingleList): Single;
248
249 { Catmull-Rom spline low-level function.
250 For X in [0..1], the curve values change from V1 to V2.
251 V0 and V3 are curve values outside the [0..1] range, used to calculate tangents.
252
253 See http://www.mvps.org/directx/articles/catmull/.
254
255 @seealso CatmullRomSpline }
256 function CatmullRom(const V0, V1, V2, V3, X: Single): Single;
257
258 { Hermite spline. Nice way to have a function that for certain arguments
259 reaches certain values, and between interpolates smoothly.
260 Requires specifying tangent values (use @link(CatmullRomSpline)
261 or @link(HermiteTenseSpline) to use automatic tangents). }
262 function HermiteSpline(const X: Single; const Loop: boolean;
263 const Arguments, Values, Tangents: TSingleList): Single;
264
265 { Hermite spline with tangents zero (it will be horizontal at control points).
266 Nice way to have a function that for certain arguments
267 reaches certain values, and between interpolates smoothly.
268
269 This is equivalent (for faster) to using @link(HermiteSpline) with all
270 tangents equal to zero.
271
272 This is called a "cardinal spline", a special case of
273 Hermite spline, with all tangents calculated with "tension" parameter equal
274 to 1 (maximum), which means that all tangents are simply zero (horizontal).
275 See https://en.wikipedia.org/wiki/Cubic_Hermite_spline for math behind this. }
276 function HermiteTenseSpline(const X: Single; const Loop: boolean;
277 const Arguments, Values: TSingleList): Single;
278
279 implementation
280
281 uses Math,
282 CastleXmlUtils, CastleDownload;
283
284 function ConvexHullIndexes(Points: TVector3List): TIntegerList; forward;
285
286 { TCurve ------------------------------------------------------------ }
287
288 function TCurve.PointOfSegment(const i, Segments: Cardinal): TVector3;
289 begin
290 Result := Point(TBegin + (i/Segments) * (TEnd-TBegin));
291 end;
292
293 constructor TCurve.Create;
294 begin
295 inherited;
296 FTBegin := 0;
297 FTEnd := 1;
298 end;
299
300 procedure TCurve.LoadFromElement(const E: TDOMElement);
301 var
302 ETime: TDOMElement;
303 begin
304 ETime := E.ChildElement('time');
305 TBegin := ETime.AttributeSingle('begin');
306 TEnd := ETime.AttributeSingle('end');
307 end;
308
309 procedure TCurve.SaveToStream(const Stream: TStream);
310 begin
311 WritelnStr(Stream, Format(' <time begin="%f" end="%f" />', [TBegin, TEnd]));
312 end;
313
314 function TCurve.Point2D(const T: Float): TVector2;
315 var
316 V: TVector3;
317 begin
318 V := Point(T);
319 Result.X := V.X;
320 Result.Y := V.Y;
321 end;
322
323 class function TCurve.LoadFromFile(const Url: String): TCurve;
324 var
325 List: TCurveList;
326 begin
327 List := TCurveList.Create(true);
328 try
329 List.LoadFromFile(Url);
330 if List.Count = 0 then
331 raise ECurveFileInvalid.Create('Empty curve XML file, cannot get first curve');
332 Result := List.Extract(List.First);
333 finally FreeAndNil(List) end;
334 end;
335
336 function TCurve.GeometryNode(const Segments: Cardinal = DefaultSegments): TAbstractGeometryNode;
337 var
338 Coord: TCoordinateNode;
339 LineSet: TLineSetNode;
340 I: Integer;
341 begin
342 Coord := TCoordinateNode.Create;
343 Coord.FdPoint.Items.Clear;
344 for I := 0 to Segments do
345 Coord.FdPoint.Items.Add(Point(I / Segments));
346
347 LineSet := TLineSetNode.Create;
348 LineSet.SetVertexCount([Segments + 1]);
349 LineSet.Coord := Coord;
350
351 Result := LineSet;
352 end;
353
354 { TCurveList ---------------------------------------------------- }
355
356 procedure TCurveList.LoadFromFile(const Url: String);
357 var
358 Document: TXMLDocument;
359 I: TXMLElementIterator;
360 CurveTypeStr: string;
361 Curve: TCurve;
362 begin
363 Clear;
364
365 Document := UrlReadXML(Url);
366 try
367 Check(Document.DocumentElement.TagName = 'curves',
368 'Root node of curves file must be <curves>');
369
370 I := Document.DocumentElement.ChildrenIterator('curve');
371 try
372 while I.GetNext do
373 begin
374 CurveTypeStr := I.Current.AttributeString('type');
375 Curve:=GetCurveByType(CurveTypeStr);
376 Curve.LoadFromElement(I.Current);
377 if Curve is TControlPointsCurve then
378 TControlPointsCurve(Curve).UpdateControlPoints;
379 Add(Curve);
380 end;
381 finally FreeAndNil(I); end;
382 finally FreeAndNil(Document) end;
383 end;
384
385 function TCurveList.GetCurveByType(const CurveTypeStr: string): TCurve;
386 begin
387 if SameText(CurveTypeStr, TPiecewiseCubicBezier.ClassName) then
388 Result := TPiecewiseCubicBezier.Create
389 else
390 if SameText(CurveTypeStr, TCasScriptCurve.ClassName) then
391 Result := TCasScriptCurve.Create
392 else
393 raise ECurveFileInvalid.CreateFmt('Curve type "%s" unknown', [CurveTypeStr]);
394 end;
395
396 procedure TCurveList.SaveToFile(const Url: String);
397 var
398 Stream: TStream;
399 I: Integer;
400 begin
401 Stream := UrlSaveStream(Url);
402 try
403 WritelnStr(Stream, '<?xml version="1.0"?>');
404 WritelnStr(Stream, '<curves>');
405 for I := 0 to Count - 1 do
406 begin
407 WritelnStr(Stream, ' <curve type="' + Items[I].ClassName + '">');
408 Items[I].SaveToStream(Stream);
409 WritelnStr(Stream, ' </curve>');
410 end;
411 WritelnStr(Stream, '</curves>');
412 finally FreeAndNil(Stream) end;
413 end;
414
415 { TCasScriptCurve ------------------------------------------------------------ }
416
417 procedure TCasScriptCurve.SetTVariable(AValue: TCasScriptFloat);
418 begin
419 if FTVariable = AValue then Exit;
420 FTVariable := AValue;
421 UpdateBoundingBox;
422 end;
423
424 procedure TCasScriptCurve.SetSegmentsForBoundingBox(AValue: Cardinal);
425 begin
426 if FSegmentsForBoundingBox = AValue then Exit;
427 FSegmentsForBoundingBox := AValue;
428 UpdateBoundingBox;
429 end;
430
431 function TCasScriptCurve.GetFunction(const Index: Integer): TCasScriptExpression;
432 begin
433 Result := FFunction[Index];
434 end;
435
436 procedure TCasScriptCurve.SetFunction(const Index: Integer;
437 const Value: TCasScriptExpression);
438 begin
439 if FFunction[Index] = Value then Exit;
440
441 if FFunction[Index] <> nil then
442 FFunction[Index].FreeByParentExpression;
443
444 FFunction[Index] := Value;
445 UpdateBoundingBox;
446 end;
447
448 procedure TCasScriptCurve.UpdateBoundingBox;
449 var
450 i, k: Integer;
451 P: TVector3;
452 begin
453 if (XFunction = nil) or
454 (YFunction = nil) or
455 (ZFunction = nil) or
456 (TVariable = nil) then
457 FBoundingBox := TBox3D.Empty else
458 begin
459 { calculate FBoundingBox }
460 P := PointOfSegment(0, SegmentsForBoundingBox); { = Point(TBegin) }
461 FBoundingBox.Data[0] := P;
462 FBoundingBox.Data[1] := P;
463 for i := 1 to SegmentsForBoundingBox do
464 begin
465 P := PointOfSegment(i, SegmentsForBoundingBox);
466 for k := 0 to 2 do
467 begin
468 FBoundingBox.Data[0].Data[k] := Min(FBoundingBox.Data[0].Data[k], P[k]);
469 FBoundingBox.Data[1].Data[k] := Max(FBoundingBox.Data[1].Data[k], P[k]);
470 end;
471 end;
472 end;
473 end;
474
475 function TCasScriptCurve.Point(const t: Float): TVector3;
476 var
477 I: Integer;
478 begin
479 TVariable.Value := T;
480 for I := 0 to 2 do
481 Result.Data[I] := (FFunction[I].Execute as TCasScriptFloat).Value;
482
483 {test: Writeln('Point at t = ',FloatToNiceStr(Single(t)), ' is (',
484 Result.ToString, ')');}
485 end;
486
487 function TCasScriptCurve.BoundingBox: TBox3D;
488 begin
489 Result := FBoundingBox;
490 end;
491
492 constructor TCasScriptCurve.Create;
493 begin
494 inherited;
495 FSegmentsForBoundingBox := 100;
496 FBoundingBox := TBox3D.Empty;
497 end;
498
499 destructor TCasScriptCurve.Destroy;
500 var
501 I: Integer;
502 begin
503 for I := 0 to 2 do
504 if FFunction[I] <> nil then
505 begin
506 FFunction[I].FreeByParentExpression;
507 FFunction[I] := nil;
508 end;
509 inherited;
510 end;
511
512 procedure TCasScriptCurve.LoadFromElement(const E: TDOMElement);
513 begin
514 inherited LoadFromElement(E);
515 // TODO: load TCasScriptCurve specifics
516 end;
517
518 procedure TCasScriptCurve.SaveToStream(const Stream: TStream);
519 begin
520 inherited SaveToStream(Stream);
521 // TODO: save TCasScriptCurve specifics
522 end;
523
524 { TControlPointsCurve ------------------------------------------------ }
525
526 function TControlPointsCurve.BoundingBox: TBox3D;
527 begin
528 Result := FBoundingBox;
529 end;
530
531 procedure TControlPointsCurve.UpdateControlPoints;
532 begin
533 FBoundingBox := CalculateBoundingBox(PVector3(ControlPoints.L),
534 ControlPoints.Count, 0);
535 end;
536
537 function TControlPointsCurve.CreateConvexHullPoints: TVector3List;
538 begin
539 Result := ControlPoints;
540 end;
541
542 procedure TControlPointsCurve.DestroyConvexHullPoints(Points: TVector3List);
543 begin
544 end;
545
546 function TControlPointsCurve.ConvexHull: TVector3List;
547 var
548 PotentialConvexHullPoints: TVector3List;
549 Indexes: TIntegerList;
550 I: Integer;
551 begin
552 Result := TVector3List.Create;
553
554 PotentialConvexHullPoints := CreateConvexHullPoints;
555 try
556 if PotentialConvexHullPoints.Count <> 0 then
557 begin
558 Indexes := ConvexHullIndexes(PotentialConvexHullPoints);
559 try
560 for I := 0 to Indexes.Count - 1 do
561 Result.Add(PotentialConvexHullPoints.L[Indexes.L[I]]);
562 finally FreeAndNil(Indexes) end;
563 end;
564 finally DestroyConvexHullPoints(PotentialConvexHullPoints) end;
565 end;
566
567 constructor TControlPointsCurve.Create;
568 begin
569 inherited;
570 ControlPoints := TVector3List.Create;
571 { DON'T call UpdateControlPoints from here - UpdateControlPoints is virtual !
572 So we set FBoundingBox by hand. }
573 FBoundingBox := TBox3D.Empty;
574 end;
575
576 constructor TControlPointsCurve.CreateFromEquation(
577 CasScriptCurve: TCasScriptCurve; ControlPointsCount: Cardinal);
578 var
579 i: Integer;
580 begin
581 Create;
582 TBegin := CasScriptCurve.TBegin;
583 TEnd := CasScriptCurve.TEnd;
584 ControlPoints.Count := ControlPointsCount;
585 for i := 0 to ControlPointsCount-1 do
586 ControlPoints.L[i] := CasScriptCurve.PointOfSegment(i, ControlPointsCount-1);
587 UpdateControlPoints;
588 end;
589
590 destructor TControlPointsCurve.Destroy;
591 begin
592 FreeAndNil(ControlPoints);
593 inherited;
594 end;
595
596 procedure TControlPointsCurve.LoadFromElement(const E: TDOMElement);
597 var
598 I: TXMLElementIterator;
599 EControlPoints: TDOMElement;
600 begin
601 inherited LoadFromElement(E);
602
603 EControlPoints := E.ChildElement('control_points');
604 I := EControlPoints.ChildrenIterator('control_point');
605 try
606 while I.GetNext do
607 ControlPoints.Add(I.Current.AttributeVector3('value'));
608 finally FreeAndNil(I); end;
609 end;
610
611 procedure TControlPointsCurve.SaveToStream(const Stream: TStream);
612 var
613 I: Integer;
614 VectorStr: string;
615 begin
616 inherited SaveToStream(Stream);
617
618 WritelnStr(Stream, ' <control_points>');
619 for I := 0 to ControlPoints.Count - 1 do
620 begin
621 VectorStr := ControlPoints[I].ToRawString;
622 WritelnStr(Stream, ' <control_point value="' + VectorStr + '"/>');
623 end;
624 WritelnStr(Stream, ' </control_points>');
625 end;
626
627 { TPiecewiseCubicBezier --------------------------------------------------- }
628
629 function TPiecewiseCubicBezier.CreateConvexHullPoints: TVector3List;
630 begin
631 Result := ConvexHullPoints;
632 end;
633
634 procedure TPiecewiseCubicBezier.DestroyConvexHullPoints(Points: TVector3List);
635 begin
636 end;
637
638 function TPiecewiseCubicBezier.Point(const t: Float): TVector3;
639 var
640 T01: Single;
641 TInsidePiece: Double;
642 IndexBefore: Int64;
643 IndexBeforeChange: Integer;
644 begin
645 Assert(ControlPoints.Count >= 1);
646 if ControlPoints.Count = 1 then
647 Exit(ControlPoints.Items[0]);
648
649 T01 := MapRange(T, TBegin, TEnd, 0, 1);
650 if ControlPoints.Count = 2 then
651 // super-fast case
652 Exit(Lerp(T01, ControlPoints.Items[0], ControlPoints.Items[1]));
653
654 FloatDivMod(T01, 1 / (ControlPoints.Count - 1), IndexBefore, TInsidePiece);
655 TInsidePiece := TInsidePiece * (ControlPoints.Count - 1); // make TInsidePiece in 0..1 range
656
657 { fix IndexBefore (together with TInsidePiece, synchronized)
658 to be within [0, ControlPoints.Count - 2] range.
659 Necessary so that both IndexBefore and IndexAfter are later in valid
660 control points [0, ControlPoints.Count - 1] range. }
661 IndexBeforeChange := 0;
662 if IndexBefore > ControlPoints.Count - 2 then
663 IndexBeforeChange := -(IndexBefore - (ControlPoints.Count - 2)) else
664 if IndexBefore < 0 then
665 IndexBeforeChange := -IndexBefore;
666 if IndexBeforeChange <> 0 then
667 begin
668 IndexBefore := IndexBefore + IndexBeforeChange;
669 TInsidePiece := TInsidePiece - IndexBeforeChange;
670 end;
671 Assert(IndexBefore >= 0);
672 Assert(IndexBefore <= ControlPoints.Count - 2);
673
674 // writeln('TPiecewiseCubicBezier got ', IndexBefore, ' ', TInsidePiece:1:2);
675
676 if IndexBefore >= Length(BezierCurves) then
677 raise Exception.Create('Curves data inside PiecewiseCubicBezier not initialized, probably you forgot to call UpdateControlPoints after changing the ControlPoints');
678 Result := CubicBezier3D(TInsidePiece, BezierCurves[IndexBefore]);
679 end;
680
681 procedure TPiecewiseCubicBezier.UpdateBezierCurves(var ABezierCurves: TCubicBezier3DPointsArray);
682 var
683 S: TVector3List;
684 C: TVector3List;
685 I: Integer;
686 PointBegin, PointEnd: TVector3;
687 begin
688 { Normal calculations cannot be done when
689 ControlPoints.Count = 2:
690 C.Count would be 1, S.Count would be 2,
691 S[0] would be calculated based on C[0] and S[1],
692 S[1] would be calculated based on C[0] and S[0].
693 So we can't calculate S[0] and S[1] using given equations when
694 ControlPoints.Count = 2.
695
696 Point() method implements a special case for ControlPoints.Count = 2,
697 it just does Lerp then. }
698 if ControlPoints.Count <= 2 then
699 Exit;
700
701 { based on SLE mmgk notes, "Krzywe Beziera" page 4 }
702 C := nil;
703 S := nil;
704 try
705 C := TVector3List.Create;
706 C.Count := ControlPoints.Count - 1;
707 { calculate C values }
708 for I := 0 to C.Count - 1 do
709 C[I] := ControlPoints[I + 1] - ControlPoints[I];
710
711 S := TVector3List.Create;
712 S.Count := ControlPoints.Count;
713 { calculate S values }
714 for I := 1 to S.Count - 2 do
715 S[I] := (C[I-1] + C[I]) / 2;
716 S[0 ] := C[0 ] * 2 - S[1 ];
717 S[S.Count-1] := C[S.Count-2] * 2 - S[S.Count-2];
718
719 SetLength(ABezierCurves, ControlPoints.Count - 1);
720
721 for I := 1 to ControlPoints.Count - 1 do
722 begin
723 PointBegin := ControlPoints.L[I - 1];
724 PointEnd := ControlPoints.L[I];
725 ABezierCurves[I - 1][0] := PointBegin;
726 ABezierCurves[I - 1][1] := PointBegin + S[I -1] / 3;
727 ABezierCurves[I - 1][2] := PointEnd - S[I ] / 3;
728 ABezierCurves[I - 1][3] := PointEnd;
729 end;
730 finally
731 C.Free;
732 S.Free;
733 end;
734 end;
735
736 procedure TPiecewiseCubicBezier.UpdateControlPoints;
737
738 procedure UpdateConvexHullPoints;
739 var
740 I: Integer;
741 begin
742 ConvexHullPoints.Clear;
743 ConvexHullPoints.AddRange(ControlPoints);
744 for I := 0 to Length(BezierCurves) - 1 do
745 begin
746 { add also intermediate control points }
747 ConvexHullPoints.Add(BezierCurves[I][1]);
748 ConvexHullPoints.Add(BezierCurves[I][2]);
749 end;
750 end;
751
752 procedure UpdateBoundingBox;
753 begin
754 FBoundingBox := CalculateBoundingBox(PVector3(ConvexHullPoints.L),
755 ConvexHullPoints.Count, 0);
756 end;
757
758 begin
759 inherited;
760 UpdateBezierCurves(BezierCurves);
761 UpdateConvexHullPoints;
762 UpdateBoundingBox;
763 end;
764
765 constructor TPiecewiseCubicBezier.Create;
766 begin
767 inherited;
768 ConvexHullPoints := TVector3List.Create;
769 FBoundingBox := TBox3D.Empty;
770 end;
771
772 destructor TPiecewiseCubicBezier.Destroy;
773 begin
774 FreeAndNil(ConvexHullPoints);
775 inherited;
776 end;
777
778 function TPiecewiseCubicBezier.BoundingBox: TBox3D;
779 begin
780 Result := FBoundingBox;
781 end;
782
783 { global routines ------------------------------------------------------------ }
784
785 function CubicBezier1D(T: Single; const Points: TVector4): Single;
786 var
787 T1: Single;
788 begin
789 T := Clamped(T, 0, 1);
790 T1 := 1 - T;
791 Result := Points[0] * Sqr(T1) * T1 +
792 Points[1] * 3 * Sqr(T1) * T +
793 Points[2] * 3 * Sqr(T) * T1 +
794 Points[3] * Sqr(T) * T;
795 end;
796
797 function CubicBezier2D(T: Single; const Points: TCubicBezier2DPoints): TVector2;
798 var
799 T1: Single;
800 begin
801 T := Clamped(T, 0, 1);
802 T1 := 1 - T;
803 Result := Points[0] * ( Sqr(T1) * T1) +
804 Points[1] * (3 * Sqr(T1) * T) +
805 Points[2] * (3 * Sqr(T) * T1) +
806 Points[3] * ( Sqr(T) * T);
807 end;
808
809 function CubicBezier3D(T: Single; const Points: TCubicBezier3DPoints): TVector3;
810 var
811 T1: Single;
812 begin
813 T := Clamped(T, 0, 1);
814 T1 := 1 - T;
815 Result := Points[0] * ( Sqr(T1) * T1) +
816 Points[1] * (3 * Sqr(T1) * T) +
817 Points[2] * (3 * Sqr(T) * T1) +
818 Points[3] * ( Sqr(T) * T);
819 end;
820
821 { General spline calculation.
822
823 Sets Inside to @true if the point is between 2 arguments on Arguments list,
824 and sets IndexOfRightValue, XInSegment in this case.
825 It guarantees that X is between
826 Arguments[IndexOfRightValue - 1] and
827 Arguments[IndexOfRightValue] and that count > 1 and IndexOfRightValue > 0.
828 XInSegment is X already transformed from
829 Arguments[IndexOfRightValue - 1] and
830 Arguments[IndexOfRightValue] to the [0..1] range.
831 It is expected the caller will calculate
832 CurveResult using IndexOfRightValue, XInSegment, and curve-specific equation.
833
834 Sets Inside to @false if the point is outside of Arguments,
835 and sets CurveResult in this case. }
836 procedure CalculateSpline(const X: Single; const Loop: boolean;
837 const Arguments, Values: TSingleList;
838 out Inside: Boolean; out CurveResult: Single;
839 out IndexOfRightValue: Integer; out XInSegment: Single);
840
841 { Calculate assuming that X is between [First..Last], and Count > 1. }
842 procedure CalculateInRange(const X: Single);
843 var
844 I, C: Integer;
845 begin
846 Assert(Inside);
847
848 C := Arguments.Count;
849
850 // TODO: make binary search
851 I := 1;
852 while (I + 1 < C) and (X > Arguments.L[I]) do Inc(I);
853
854 IndexOfRightValue := I;
855 XInSegment := (X - Arguments.L[I - 1]) / (Arguments.L[I] - Arguments.L[I - 1]);
856 end;
857
858 var
859 C: Integer;
860 FirstArg, LastArg, Len: Single;
861 begin
862 C := Arguments.Count;
863
864 if C = 0 then
865 begin
866 Inside := false;
867 CurveResult := 0;
868 end else
869 begin
870 FirstArg := Arguments.L[0];
871 if C = 1 then
872 begin
873 Inside := false;
874 CurveResult := FirstArg;
875 end else
876 begin
877 LastArg := Arguments.L[C - 1];
878 Len := LastArg - FirstArg;
879 if X < FirstArg then
880 begin
881 if Loop then
882 begin
883 Inside := true;
884 CalculateInRange(X + Ceil((FirstArg - X) / Len) * Len)
885 end else
886 begin
887 Inside := false;
888 CurveResult := Values.L[0];
889 end;
890 end else
891 if X > LastArg then
892 begin
893 if Loop then
894 begin
895 Inside := true;
896 CalculateInRange(X - Ceil((X - LastArg) / Len) * Len);
897 end else
898 begin
899 Inside := false;
900 CurveResult := Values.L[C - 1];
901 end;
902 end else
903 begin
904 Inside := true;
905 CalculateInRange(X);
906 end;
907 end;
908 end;
909 end;
910
911 function CatmullRom(const V0, V1, V2, V3, X: Single): Single;
912 var
913 X2, X3: Single;
914 begin
915 X2 := Sqr(X);
916 X3 := X2 * X;
917 Result := 0.5 * (
918 (2 * V1) +
919 (-V0 + V2) * X +
920 (2*V0 - 5*V1 + 4*V2 - V3) * X2 +
921 (-V0 + 3*V1- 3*V2 + V3) * X3
922 );
923 end;
924
925 function CatmullRomSpline(const X: Single; const Loop: boolean;
926 const Arguments: TSingleList;
927 const Values: TSingleList): Single;
928
929 function CatmullRomSegment(const I: Integer; const XInSegment: Single): Single;
930 var
931 C: Integer;
932 V0, V1, V2, V3: Single;
933 begin
934 C := Arguments.Count;
935
936 V1 := Values.L[I - 1];
937 V2 := Values.L[I];
938
939 if I - 2 = -1 then
940 begin
941 if Loop then
942 V0 := Values.L[C - 2] else // not Values.L[C - 1], as first and last values are usually equal
943 V0 := Values.L[0];
944 end else
945 V0 := Values.L[I - 2];
946
947 if I + 1 = C then
948 begin
949 if Loop then
950 V3 := Values.L[1] else // not Values.L[C - 1], as first and last values are usually equal
951 V3 := Values.L[C - 1];
952 end else
953 V3 := Values.L[I + 1];
954
955 Result := CatmullRom(V0, V1, V2, V3, XInSegment);
956 end;
957
958 var
959 Inside: Boolean;
960 IndexOfRightValue: Integer;
961 XInSegment: Single;
962 begin
963 if Arguments.Count <> Values.Count then
964 raise Exception.Create('CatmullRomSpline: Arguments and Values lists must have equal count');
965 CalculateSpline(X, Loop, Arguments, Values, Inside, Result, IndexOfRightValue, XInSegment);
966 if Inside then
967 Result := CatmullRomSegment(IndexOfRightValue, XInSegment);
968 end;
969
970 function Hermite(const V0, V1, Tangent0, Tangent1, X: Single): Single;
971 var
972 X2, X3: Single;
973 begin
974 X2 := Sqr(X);
975 X3 := X2 * X;
976 { equation from https://en.wikipedia.org/wiki/Cubic_Hermite_spline }
977 Result :=
978 (2 * X3 - 3 * X2 + 1) * V0 +
979 (X3 - 2 * X2 + X) * Tangent0 +
980 (-2 * X3 + 3 *X2) * V1 +
981 (X3 - X2) * Tangent1;
982 end;
983
984 function HermiteSpline(const X: Single; const Loop: boolean;
985 const Arguments, Values, Tangents: TSingleList): Single;
986
987 function HermiteSegment(const I: Integer; const XInSegment: Single): Single;
988 begin
989 Result := Hermite(
990 Values .L[I - 1], Values .L[I],
991 Tangents.L[I - 1], Tangents.L[I], XInSegment);
992 end;
993
994 var
995 Inside: Boolean;
996 IndexOfRightValue: Integer;
997 XInSegment: Single;
998 begin
999 if (Arguments.Count <> Values.Count) or
1000 (Arguments.Count <> Tangents.Count) then
1001 raise Exception.Create('HermiteSpline: Arguments and Values and Tangents lists must have equal count');
1002
1003 CalculateSpline(X, Loop, Arguments, Values, Inside, Result, IndexOfRightValue, XInSegment);
1004 if Inside then
1005 Result := HermiteSegment(IndexOfRightValue, XInSegment);
1006 end;
1007
1008 function HermiteTense(const V0, V1, X: Single): Single;
1009 var
1010 X2, X3: Single;
1011 begin
1012 X2 := Sqr(X);
1013 X3 := X2 * X;
1014 Result :=
1015 (2 * X3 - 3 * X2 + 1) * V0 +
1016 (-2 * X3 + 3 *X2) * V1;
1017 end;
1018
1019 function HermiteTenseSpline(const X: Single; const Loop: boolean;
1020 const Arguments, Values: TSingleList): Single;
1021
1022 function HermiteTenseSegment(const I: Integer; const XInSegment: Single): Single;
1023 begin
1024 Result := HermiteTense(
1025 Values.L[I - 1], Values.L[I], XInSegment);
1026 end;
1027
1028 var
1029 Inside: Boolean;
1030 IndexOfRightValue: Integer;
1031 XInSegment: Single;
1032 begin
1033 if Arguments.Count <> Values.Count then
1034 raise Exception.Create('HermiteTenseSpline: Arguments and Values lists must have equal count');
1035 CalculateSpline(X, Loop, Arguments, Values, Inside, Result, IndexOfRightValue, XInSegment);
1036 if Inside then
1037 Result := HermiteTenseSegment(IndexOfRightValue, XInSegment);
1038 end;
1039
1040 { Calculate the convex hull ignoring Z coordinates of pixels.
1041 That is, all Points[*][2] are ignored.
1042 Returns newly created array with the indices to Points.
1043 If you want to draw an edge of convex hull,
1044 you want to iterate over these points like (for each i) Points[Result[i]]).
1045
1046 Points.Count must be >= 1. }
1047 function ConvexHullIndexes(Points: TVector3List): TIntegerList;
1048
1049 { this is the Jarvis algorithm, based on description in Cormen's
1050 "Introduction to alg." }
1051
1052 var InResult: TBooleanList;
1053
1054 function FindNext(Start: Integer; var NextI: Integer; RightSide: boolean): boolean;
1055 { Starting from Points[Start], knowing that InResult[Start],
1056 find next vertex on convex hull. If RightSide then we're moving from
1057 lowest vertex to highest, walking over the right edge of the convex hull.
1058 Else we're moving from highest to lowest, walking over the left edge
1059 of hull.
1060
1061 Return false if RightSide and Start is the highest vertex,
1062 or (not RightSide) and Start is the lowest vertex.
1063 Else sets Next as appropriate and returns true.
1064
1065 Returned Next for SURE has InResult[Next] = false. }
1066 var MaxCotanAngle, ThisCotan: Single;
1067 MaxCotanAngleI, i: Integer;
1068 begin
1069 MaxCotanAngle := -MaxSingle;
1070 MaxCotanAngleI := -1;
1071 for i := 0 to Points.Count-1 do
1072 if not InResult[i] then
1073 begin
1074 if SameValue(Points.L[i][1], Points.L[Start][1]) then
1075 begin
1076 if RightSide = (Points.L[i][0] > Points.L[Start][0]) then
1077 begin
1078 MaxCotanAngle := MaxSingle;
1079 MaxCotanAngleI := i;
1080 end;
1081 end else
1082 if RightSide = (Points.L[i][1] > Points.L[Start][1]) then
1083 begin
1084 ThisCotan:=(Points.L[i][0] - Points.L[Start][0]) /
1085 (Points.L[i][1] - Points.L[Start][1]);
1086 if ThisCotan > MaxCotanAngle then
1087 begin
1088 MaxCotanAngle := ThisCotan;
1089 MaxCotanAngleI := i;
1090 end;
1091 end;
1092 end;
1093
1094 Result := MaxCotanAngleI <> -1;
1095 if Result then NextI := MaxCotanAngleI;
1096 end;
1097
1098 procedure MarkNext(i: Integer);
1099 begin
1100 InResult[i] := true;
1101 Result.Add(i);
1102 end;
1103
1104 var MinY: Single;
1105 i0, i, NextI: Integer;
1106 begin
1107 Assert(Points.Count >= 1);
1108
1109 { find i0, index of lowest point in Points }
1110 MinY := Points.L[0][1];
1111 i0 := 0;
1112 for i := 1 to Points.Count-1 do
1113 if Points.L[i][1] < MinY then
1114 begin
1115 MinY := Points.L[i][1];
1116 i0 := i;
1117 end;
1118
1119 InResult := TBooleanList.Create;
1120 try
1121 InResult.Count := Points.Count; { TFPGList already initializes all to false }
1122 Result := TIntegerList.Create;
1123 try
1124 MarkNext(i0);
1125
1126 i := i0;
1127 while FindNext(i, NextI, true ) do begin i := NextI; MarkNext(i); end;
1128 while FindNext(i, NextI, false) do begin i := NextI; MarkNext(i); end;
1129
1130 except Result.Free; raise end;
1131 finally InResult.Free end;
1132 end;
1133
1134 end.