{ Copyright 2004-2023 Michalis Kamburelis. This file is part of "Castle Game Engine". "Castle Game Engine" is free software; see the file COPYING.txt, included in this distribution, for details about the copyright. "Castle Game Engine" is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ---------------------------------------------------------------------------- } { 3D curves (TCurve and basic descendants). } unit CastleCurves; {$I castleconf.inc} interface uses SysUtils, Classes, Generics.Collections, DOM, CastleVectors, CastleBoxes, CastleUtils, CastleScript, CastleClassUtils, CastleFrustum, X3DNodes; type ECurveFileInvalid = class(Exception); { 3D curve, a set of points defined by a continuous function @link(Point) for arguments within [TBegin, TEnd]. } TCurve = class private FTBegin, FTEnd: Single; protected procedure LoadFromElement(const E: TDOMElement); virtual; procedure SaveToStream(const Stream: TStream); virtual; public const DefaultSegments = 32; constructor Create; { The valid range of curve function argument. Must be TBegin <= TEnd. @groupBegin } property TBegin: Single read FTBegin write FTBegin {$ifdef FPC}default 0{$endif}; property TEnd: Single read FTEnd write FTEnd {$ifdef FPC}default 1{$endif}; { @groupEnd } { Curve function, for each parameter value determine the 3D point. This determines the actual shape of the curve. This is the simplest approach to calculate points on a curve. } function Point(const t: Float): TVector3; virtual; abstract; function Point2D(const t: Float): TVector2; { Curve function to work with rendered line segments begin/end points. This is simply a more specialized version of @link(Point), it scales the argument such that you get Point(TBegin) for I = 0 and you get Point(TEnd) for I = Segments. } function PointOfSegment(const i, Segments: Cardinal): TVector3; { Load the first curve defined in given XML file. Hint: use https://castle-engine.io/curves_tool to design curves visually. } class function LoadFromFile(const Url: String): TCurve; function BoundingBox: TBox3D; virtual; abstract; { Represent this curve as an X3D geometry node, that you can use to visualize this. } function GeometryNode(const Segments: Cardinal = DefaultSegments): TAbstractGeometryNode; end; TCurveList = class({$ifdef FPC}specialize{$endif} TObjectList) protected { Override this function to add other classes inherited from @link(TCurve) to a list. } function GetCurveByType(const CurveTypeStr: string): TCurve; virtual; public { Load curves definitions from a simple XML file. Hint: use https://castle-engine.io/curves_tool to design curves visually. } procedure LoadFromFile(const Url: String); virtual; { Save curve definitions to a simple XML file. Hint: use https://castle-engine.io/curves_tool to design curves visually. } procedure SaveToFile(const Url: String); virtual; end; { Curve defined by explicitly giving functions for Point(t) = x(t), y(t), z(t) as CastleScript expressions. } TCasScriptCurve = class(TCurve) private FSegmentsForBoundingBox: Cardinal; FTVariable: TCasScriptFloat; FFunction: array [0..2] of TCasScriptExpression; FBoundingBox: TBox3D; procedure SetSegmentsForBoundingBox(AValue: Cardinal); procedure SetTVariable(AValue: TCasScriptFloat); function GetFunction(const Index: Integer): TCasScriptExpression; procedure SetFunction(const Index: Integer; const Value: TCasScriptExpression); procedure UpdateBoundingBox; protected procedure LoadFromElement(const E: TDOMElement); override; procedure SaveToStream(const Stream: TStream); override; public function Point(const t: Float): TVector3; override; { XFunction, YFunction, ZFunction are functions based on variable 't'. Once set, these instances become owned by this class, do not free them yourself! @groupBegin } property XFunction: TCasScriptExpression index 0 read GetFunction write SetFunction; property YFunction: TCasScriptExpression index 1 read GetFunction write SetFunction; property ZFunction: TCasScriptExpression index 2 read GetFunction write SetFunction; { @groupEnd } { This is the variable controlling 't' value, embedded also in XFunction, YFunction, ZFunction. This is NOT owned by this class, make sure to free it yourself! } property TVariable: TCasScriptFloat read FTVariable write SetTVariable; property SegmentsForBoundingBox: Cardinal read FSegmentsForBoundingBox write SetSegmentsForBoundingBox default 100; { Simple bounding box. It is simply a BoundingBox of Point(i, SegmentsForBoundingBox) for i in [0 .. SegmentsForBoundingBox]. Subclasses may override this to calculate something more accurate. } function BoundingBox: TBox3D; override; constructor Create; destructor Destroy; override; end; { A basic abstract class for curves determined my some set of ControlPoints. Note: it is @italic(not) defined in this class any correspondence between values of T (argument for Point function) and ControlPoints. } TControlPointsCurve = class(TCurve) strict private FBoundingBox: TBox3D; strict protected { Using these function you can control how Convex Hull (for RenderConvexHull) is calculated: CreateConvexHullPoints should return points that must be in convex hull (we will run ConvexHull function on those points), DestroyConvexHullPoints should finalize them. This way you can create new object in CreateConvexHullPoints and free it in DestroyConvexHullPoints, but you can also give in CreateConvexHullPoints reference to some already existing object and do nothing in DestroyConvexHullPoints. (we will not modify object given as CreateConvexHullPoints in any way) Default implementation in this class returns ControlPoints as CreateConvexHullPoints. (and does nothing in DestroyConvexHullPoints) } function CreateConvexHullPoints: TVector3List; virtual; procedure DestroyConvexHullPoints(Points: TVector3List); virtual; protected procedure LoadFromElement(const E: TDOMElement); override; procedure SaveToStream(const Stream: TStream); override; public ControlPoints: TVector3List; { Bounding box of the curve. In this class, it is simply a BoundingBox of ControlPoints. } function BoundingBox: TBox3D; override; { Always after changing ControlPoints or TBegin or TEnd and before calling @link(Point) (or anything that uses @link(Point), like @link(BoundingBox)) call this method. It recalculates necessary things. ControlPoints.Count must be >= 2. When overriding: always call inherited first. } procedure UpdateControlPoints; virtual; { Constructor. } constructor Create; { Calculate initial control points by sampling given TCasScriptCurve, with analytical curve equation. TBegin and TEnd are copied from CasScriptCurve. } constructor CreateFromEquation(CasScriptCurve: TCasScriptCurve; ControlPointsCount: Cardinal); destructor Destroy; override; { Calculate the convex hull. Caller is responsible for freeing the result. } function ConvexHull: TVector3List; end; TControlPointsCurveClass = class of TControlPointsCurve; TControlPointsCurveList = {$ifdef FPC}specialize{$endif} TObjectList; TCubicBezier2DPoints = array [0..3] of TVector2; TCubicBezier3DPoints = array [0..3] of TVector3; TCubicBezier3DPointsArray = array of TCubicBezier3DPoints; { Piecewise (composite) cubic Bezier curve. Each segment (ControlPoints[i]..ControlPoints[i+1]) is a cubic Bezier curve (Bezier with 4 control points, 2 points in the middle are auto-calculated for max smoothness). This is a cubic B-spline. Which is equivalent to C2 continuous composite Bézier curves. See https://en.wikipedia.org/wiki/Spline_%28mathematics%29 . Aka Cubic B-Spline (piecewise C2-Smooth Cubic Bezier). ControlPoints.Count may be 1 (in general, for TControlPointsCurve, it must be >= 2). } TPiecewiseCubicBezier = class(TControlPointsCurve) strict private BezierCurves: TCubicBezier3DPointsArray; ConvexHullPoints: TVector3List; FBoundingBox: TBox3D; strict protected function CreateConvexHullPoints: TVector3List; override; procedure DestroyConvexHullPoints(Points: TVector3List); override; { Calculating additional points. } procedure UpdateBezierCurves(var ABezierCurves: TCubicBezier3DPointsArray); virtual; public constructor Create; destructor Destroy; override; procedure UpdateControlPoints; override; function Point(const t: Float): TVector3; override; function BoundingBox: TBox3D; override; end; { Cubic (4 control points) Bezier curve (with all weights equal) in 1D. } function CubicBezier1D(T: Single; const Points: TVector4): Single; { Cubic (4 control points) Bezier curve (with all weights equal) in 2D. } function CubicBezier2D(T: Single; const Points: TCubicBezier2DPoints): TVector2; { Cubic (4 control points) Bezier curve (with all weights equal) in 3D. } function CubicBezier3D(T: Single; const Points: TCubicBezier3DPoints): TVector3; { Catmull-Rom spline. Nice way to have a function that for certain arguments reaches certain values, and between interpolates smoothly. Catmull-Rom splines are a special case of cubic Hermite splines, see https://en.wikipedia.org/wiki/Cubic_Hermite_spline . } function CatmullRomSpline(const X: Single; const Loop: boolean; const Arguments: TSingleList; const Values: TSingleList): Single; { Catmull-Rom spline low-level function. For X in [0..1], the curve values change from V1 to V2. V0 and V3 are curve values outside the [0..1] range, used to calculate tangents. See http://www.mvps.org/directx/articles/catmull/. @seealso CatmullRomSpline } function CatmullRom(const V0, V1, V2, V3, X: Single): Single; { Hermite spline. Nice way to have a function that for certain arguments reaches certain values, and between interpolates smoothly. Requires specifying tangent values (use @link(CatmullRomSpline) or @link(HermiteTenseSpline) to use automatic tangents). } function HermiteSpline(const X: Single; const Loop: boolean; const Arguments, Values, Tangents: TSingleList): Single; { Hermite spline with tangents zero (it will be horizontal at control points). Nice way to have a function that for certain arguments reaches certain values, and between interpolates smoothly. This is equivalent (for faster) to using @link(HermiteSpline) with all tangents equal to zero. This is called a "cardinal spline", a special case of Hermite spline, with all tangents calculated with "tension" parameter equal to 1 (maximum), which means that all tangents are simply zero (horizontal). See https://en.wikipedia.org/wiki/Cubic_Hermite_spline for math behind this. } function HermiteTenseSpline(const X: Single; const Loop: boolean; const Arguments, Values: TSingleList): Single; implementation uses Math, CastleXmlUtils, CastleDownload; function ConvexHullIndexes(Points: TVector3List): TIntegerList; forward; { TCurve ------------------------------------------------------------ } function TCurve.PointOfSegment(const i, Segments: Cardinal): TVector3; begin Result := Point(TBegin + (i/Segments) * (TEnd-TBegin)); end; constructor TCurve.Create; begin inherited; FTBegin := 0; FTEnd := 1; end; procedure TCurve.LoadFromElement(const E: TDOMElement); var ETime: TDOMElement; begin ETime := E.ChildElement('time'); TBegin := ETime.AttributeSingle('begin'); TEnd := ETime.AttributeSingle('end'); end; procedure TCurve.SaveToStream(const Stream: TStream); begin WritelnStr(Stream, Format('