Debian Codegraph @

src/scene/x3d/x3dnodes_standard_interpolation_cubic_bezier.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2002-2022 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18 TAbstractCubicBezierInterpolatorNode = class(TAbstractInterpolatorNode)
19 strict private
20 type
21 TCalculatedCurve2D = array [0..10] of TVector2;
22 TCalculatedCurve2DRec = record
23 { Wrap this array in extra record, otherwise Delphi gets
24 confused what List.L[123] means, because
25 - it can mean to access 123th item of List, following pointer math
26 - it can mean to access 123th item of first element of List,
27 following Delphi "no need to dereferenece pointer to array or record"
28 idea.
29 }
30 Points: TCalculatedCurve2D;
31 end;
32 TCalculatedCurve2DList = {$ifdef FPC}specialize{$endif} TStructList<TCalculatedCurve2DRec>;
33 var
34 FCalculatedCurves: TCalculatedCurve2DList;
35 CubicBezierValueWarningDone: boolean;
36
37 { Like KeyRange, but looking at X coordinates of the points in Key array. }
38 class function KeyRangeArray2D(Key: array of TVector2;
39 const Fraction: Single; out T: Single): Integer; static;
40
41 class function CubicBezierPercent(const T: Single;
42 const ControlPoints: TVector4;
43 const Curve: TCalculatedCurve2D): Single; static;
44
45 { For a Bezier curve segment, expressed as 4D vector with the meaning
46 like in Spine "curve" specification (it specifies XY values of
47 2 middle cubic Bezier curve points), calculate the curve. }
48 class procedure CalculatedCurve2D(const KeyValue: TVector4;
49 out Curve: TCalculatedCurve2D); static;
50
51 strict protected
52 { Calculate curve value for the range inside
53 FdControlPoints[ControlPointsIndex]. }
54 function CubicBezierValue(
55 const T: Single; const ControlPointsIndex: Integer): Single;
56
57 protected
58 function DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode; override;
59
60 public
61 destructor Destroy; override;
62
63 { Once the FdControlPoints value is settled, call this to precalculate
64 curve parameters. This makes the following interpolation using this node
65 work fast.
66
67 You can pass CopyOptimizedDataFrom if you have a copy of this
68 node (with exactly equal FdControlPoints) from which we could copy optimized data. }
69 procedure OptimizeControlPoints(
70 const CopyOptimizedDataFrom: TAbstractCubicBezierInterpolatorNode = nil);
71
72 {$I auto_generated_node_helpers/x3dnodes_x3dcubicbezierinterpolator.inc}
73 end;
74
75 { Interpolate (animate) a set of 2D rotations,
76 using cubic Bezier curve instead of linear interpolation.
77 See https://castle-engine.io/x3d_implementation_interpolation_extensions.php . }
78 TCubicBezier2DOrientationInterpolatorNode = class(TAbstractCubicBezierInterpolatorNode)
79 strict private
80 procedure EventSet_FractionReceive(const Event: TX3DEvent; const Value: TX3DField;
81 const Time: TX3DTime);
82 public
83 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
84 {$I auto_generated_node_helpers/x3dnodes_cubicbezier2dorientationinterpolator.inc}
85 end;
86
87 { Interpolate (animate) a set of 3D positions,
88 using cubic Bezier curve instead of linear interpolation.
89 See https://castle-engine.io/x3d_implementation_interpolation_extensions.php . }
90 TCubicBezierPositionInterpolatorNode = class(TAbstractCubicBezierInterpolatorNode)
91 strict private
92 procedure EventSet_FractionReceive(const Event: TX3DEvent; const Value: TX3DField;
93 const Time: TX3DTime);
94 public
95 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
96 {$I auto_generated_node_helpers/x3dnodes_cubicbezierpositioninterpolator.inc}
97 end;
98
99 { Interpolate (animate) a set of 3D vertices,
100 using cubic Bezier curve instead of linear interpolation.
101 See https://castle-engine.io/x3d_implementation_interpolation_extensions.php . }
102 TCubicBezierCoordinateInterpolatorNode = class(TAbstractCubicBezierInterpolatorNode)
103 strict private
104 function KeyValue(const Index, KeyCount: Integer): TMFVec3f;
105 function KeyValueLerp(const T: Single; const Index1, Index2, KeyCount: Integer): TMFVec3f;
106 procedure EventSet_FractionReceive(const Event: TX3DEvent; const Value: TX3DField;
107 const Time: TX3DTime);
108 strict protected
109 procedure InterpolatorLerp(const Target: TMFVec3f;
110 const Fraction: Single; const F1, F2: TMFVec3f;
111 const Index1, Index2, ACount: Integer); virtual;
112 public
113 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
114 {$I auto_generated_node_helpers/x3dnodes_cubicbeziercoordinateinterpolator.inc}
115 end;
116 {$endif read_interface}
117
118 {$ifdef read_implementation}
119
120 { TAbstractCubicBezierInterpolatorNode --------------------------------------- }
121
122 class function TAbstractCubicBezierInterpolatorNode.KeyRangeArray2D(
123 Key: array of TVector2;
124 const Fraction: Single; out T: Single): Integer; {$ifdef FPC}static;{$endif}
125 var
126 KeyCount, A, B: Integer;
127 begin
128 KeyCount := High(Key) + 1;
129
130 Assert(KeyCount > 0);
131 Assert(not IsNan(Fraction));
132
133 if Fraction <= Key[0].X then
134 Result := 0 else
135 if Fraction >= Key[KeyCount - 1].X then
136 Result := KeyCount else
137 begin
138 { Then for sure we're between two Key values.
139 Note that we know that KeyCount > 1 (otherwise, Key.First = Key.Last
140 so one of <= or >= comparisons above would occur; we check
141 IsNan(Fraction) at the beginning to eliminate Fraction=NaN case). }
142 Assert(KeyCount > 1);
143
144 { Always A < B.
145 We're considering range from Key[A].X to Key[B].X.
146
147 Remember that we cannot actually depend on the fact that
148 Key values are non-decreasing. They should be non-decreasing,
149 and we have to output correct result only when they are non-decreasing,
150 but we also have to terminate (with any result) in any situation.
151 Reason: Key values are supplied in X3D file, so they may be broken
152 in every possible way. }
153
154 A := 0;
155 B := KeyCount - 1;
156 while B - A > 1 do
157 begin
158 Result := (A + B) div 2;
159 { A < B => (A + B) < 2B => (A + B) div 2 < B => Result < B.
160 Also, Result > A (the only way how Result could be = A
161 would be when B = A + 1, but we eliminated this case by "while"
162 condition".
163
164 This is good, it means A < Result < B, so Result is good candidate
165 for next A or B, it will for sure shorten the distance
166 between A and B. }
167 Assert(A < Result);
168 Assert(Result < B);
169 if Fraction <= Key[Result].X then
170 B := Result else
171 A := Result;
172 end;
173 Result := B;
174
175 if Key[B].X > Key[A].X then
176 T := (Fraction - Key[A].X) / (Key[B].X - Key[A].X)
177 else
178 T := 0;
179 end;
180 end;
181
182 class function TAbstractCubicBezierInterpolatorNode.CubicBezierPercent(
183 const T: Single;
184 const ControlPoints: TVector4;
185 const Curve: TCalculatedCurve2D): Single; {$ifdef FPC}static;{$endif}
186 var
187 Range: Integer;
188 FractionBetweenCurvePoints: Single;
189 begin
190 { use T as the X value, to search appropriate Y on the curve graph }
191 Range := KeyRangeArray2D(Curve, T, FractionBetweenCurvePoints);
192
193 if Range = 0 then
194 Result := Curve[0].Y
195 else
196 if Range = High(Curve) + 1 then
197 Result := Curve[High(Curve)].Y
198 else
199 Result := Lerp(FractionBetweenCurvePoints,
200 Curve[Range - 1].Y,
201 Curve[Range].Y);
202 end;
203
204 class procedure TAbstractCubicBezierInterpolatorNode.CalculatedCurve2D(
205 const KeyValue: TVector4;
206 out Curve: TCalculatedCurve2D); {$ifdef FPC}static;{$endif}
207 var
208 CurvePoints: TCubicBezier2DPoints;
209 I: Integer;
210 begin
211 CurvePoints[0] := Vector2(0, 0);
212 CurvePoints[1] := Vector2(KeyValue[0], KeyValue[1]);
213 CurvePoints[2] := Vector2(KeyValue[2], KeyValue[3]);
214 CurvePoints[3] := Vector2(1, 1);
215
216 { calculate Curve in 2D for curve parameter (T parameter of CubicBezier2D())
217 in 0..1 }
218 for I := 0 to High(Curve) do
219 Curve[I] := CubicBezier2D(I / High(Curve), CurvePoints);
220 end;
221
222 procedure TAbstractCubicBezierInterpolatorNode.OptimizeControlPoints(
223 const CopyOptimizedDataFrom: TAbstractCubicBezierInterpolatorNode);
224 var
225 I: Integer;
226 begin
227 FreeAndNil(FCalculatedCurves);
228 FCalculatedCurves := TCalculatedCurve2DList.Create;
229 if (CopyOptimizedDataFrom <> nil) and
230 (CopyOptimizedDataFrom.FCalculatedCurves <> nil) then
231 begin
232 FCalculatedCurves.AddRange(CopyOptimizedDataFrom.FCalculatedCurves);
233 end else
234 begin
235 FCalculatedCurves.Count := FdControlPoints.Items.Count;
236 for I := 0 to FdControlPoints.Items.Count - 1 do
237 CalculatedCurve2D(FdControlPoints.Items.L[I],
238 FCalculatedCurves.L[I].Points);
239 end;
240 end;
241
242 function TAbstractCubicBezierInterpolatorNode.CubicBezierValue(
243 const T: Single; const ControlPointsIndex: Integer): Single;
244 var
245 ControlPointPtr: PVector4;
246 Curve: TCalculatedCurve2D;
247 begin
248 { Call CubicBezierPercent, using ready FCalculatedCurves
249 if possible. }
250 ControlPointPtr := PVector4(FdControlPoints.Items.Ptr(ControlPointsIndex));
251 if (FCalculatedCurves <> nil) and
252 (FCalculatedCurves.Count = FdControlPoints.Count) then
253 begin
254 Result := CubicBezierPercent(T, ControlPointPtr^,
255 FCalculatedCurves.L[ControlPointsIndex].Points);
256 end else
257 begin
258 if not CubicBezierValueWarningDone then
259 begin
260 WritelnWarning('Using CubicBezierXxxInterpolator without calling OptimizeControlPoints beforehand, this is slow. Better call OptimizeControlPoints once the FdControlPoints is settled.');
261 // use CubicBezierValueWarningDone to avoid spamming with warnings
262 CubicBezierValueWarningDone := true;
263 end;
264 CalculatedCurve2D(ControlPointPtr^, Curve);
265 Result := CubicBezierPercent(T, ControlPointPtr^, Curve);
266 end;
267 end;
268
269 destructor TAbstractCubicBezierInterpolatorNode.Destroy;
270 begin
271 FreeAndNil(FCalculatedCurves);
272 inherited;
273 end;
274
275 function TAbstractCubicBezierInterpolatorNode.DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode;
276 var
277 Res: TAbstractCubicBezierInterpolatorNode;
278 begin
279 Result := inherited;
280 Res := Result as TAbstractCubicBezierInterpolatorNode;
281 Res.OptimizeControlPoints(Self);
282 end;
283
284 { TCubicBezier2DOrientationInterpolatorNode ---------------------------------- }
285
286 constructor TCubicBezier2DOrientationInterpolatorNode.Create(const AX3DName, ABaseUrl: String);
287 begin
288 inherited;
289 EventSet_Fraction.AddNotification(
290 {$ifdef FPC}@{$endif} EventSet_FractionReceive);
291 end;
292
293 procedure TCubicBezier2DOrientationInterpolatorNode.EventSet_FractionReceive(
294 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
295
296 function KeyValue(Index: Integer): Single;
297 begin
298 if Index < FdKeyValue.Items.Count then
299 Result := FdKeyValue.Items.L[Index] else
300 Result := 0;
301 end;
302
303 var
304 T: Single;
305 OutputValueAngle: Single;
306 KeyCount, Range: Integer;
307 begin
308 if not EventValue_Changed.SendNeeded then Exit;
309
310 KeyCount := FdKey.Items.Count;
311 if KeyCount = 0 then
312 begin
313 // Interpolator nodes containing no keys in the key field
314 // shall not produce any events.
315 Exit;
316 end else
317 begin
318 Range := KeyRange((Value as TSFFloat).Value, T);
319 if Range = 0 then
320 OutputValueAngle := KeyValue(0) else
321 if Range = KeyCount then
322 OutputValueAngle := KeyValue(KeyCount - 1) else
323 begin
324 if Range - 1 < FdControlPoints.Items.Count then
325 T := CubicBezierValue(T, Range - 1);
326 OutputValueAngle := AngleLerp(T, KeyValue(Range - 1), KeyValue(Range));
327 end;
328 end;
329 EventValue_Changed.Send(Vector4(FdAxis.Value, OutputValueAngle), Time, Value.InternalPartialSend);
330 end;
331
332 { TCubicBezierPositionInterpolatorNode --------------------------------------- }
333
334 constructor TCubicBezierPositionInterpolatorNode.Create(const AX3DName, ABaseUrl: String);
335 begin
336 inherited;
337 EventSet_Fraction.AddNotification(
338 {$ifdef FPC}@{$endif} EventSet_FractionReceive);
339 end;
340
341 procedure TCubicBezierPositionInterpolatorNode.EventSet_FractionReceive(
342 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
343
344 function KeyValue(Index: Integer): TVector3;
345 begin
346 if Index < FdKeyValue.Items.Count then
347 Result := FdKeyValue.Items.L[Index] else
348 Result := TVector3.Zero;
349 end;
350
351 var
352 T: Single;
353 OutputValue: TVector3;
354 KeyCount, Range: Integer;
355 begin
356 if not EventValue_Changed.SendNeeded then Exit;
357
358 KeyCount := FdKey.Items.Count;
359 if KeyCount = 0 then
360 begin
361 // Interpolator nodes containing no keys in the key field
362 // shall not produce any events.
363 Exit;
364 end else
365 begin
366 Range := KeyRange((Value as TSFFloat).Value, T);
367 if Range = 0 then
368 OutputValue := KeyValue(0) else
369 if Range = KeyCount then
370 OutputValue := KeyValue(KeyCount - 1) else
371 begin
372 if Range - 1 < FdControlPoints.Items.Count then
373 T := CubicBezierValue(T, Range - 1);
374 OutputValue := Lerp(T, KeyValue(Range - 1), KeyValue(Range));
375 end;
376 end;
377 EventValue_Changed.Send(OutputValue, Time, Value.InternalPartialSend);
378 end;
379
380 { TCubicBezierCoordinateInterpolatorNode ------------------------------------- }
381
382 constructor TCubicBezierCoordinateInterpolatorNode.Create(const AX3DName, ABaseUrl: String);
383 begin
384 inherited;
385 EventSet_Fraction.AddNotification({$ifdef FPC}@{$endif} EventSet_FractionReceive);
386 end;
387
388 function TCubicBezierCoordinateInterpolatorNode.KeyValue(const Index, KeyCount: Integer): TMFVec3f;
389 var
390 FrameValues: Integer;
391 begin
392 FrameValues := FdKeyValue.Items.Count div KeyCount;
393
394 // We pass Self as ParentNode to
395 // TMFVec3f.CreateUndefined.
396 // This is not required, ParentNode could be @nil and everything
397 // will work Ok, but setting ParentNode allows InstantReality Logger node
398 // to display "sending node" information, useful for debugging.
399 Result := TMFVec3f.CreateUndefined(Self, false, '');
400
401 if (Index + 1) * FrameValues <= FdKeyValue.Items.Count then
402 begin
403 Result.Items.AddSubRange(FdKeyValue.Items, Index * FrameValues, FrameValues);
404 end else
405 WritelnWarning('VRML/X3D', Format('Not enough keyValue items for %s interpolator',
406 [X3DType]));
407 end;
408
409 function TCubicBezierCoordinateInterpolatorNode.KeyValueLerp(const T: Single; const Index1, Index2, KeyCount: Integer): TMFVec3f;
410 var
411 FrameValues: Integer;
412 begin
413 // This actually knows that Index2 = Index1 + 1, but assumes only
414 // Index2 > Index1
415
416 FrameValues := FdKeyValue.Items.Count div KeyCount;
417 Result := TMFVec3f.CreateUndefined(Self, false, '');
418
419 if (Index2 + 1) * FrameValues <= FdKeyValue.Items.Count then
420 begin
421 InterpolatorLerp(Result, T, FdKeyValue, FdKeyValue,
422 Index1 * FrameValues, Index2 * FrameValues, FrameValues);
423 end else
424 WritelnWarning('VRML/X3D', Format('Not enough keyValue items for %s interpolator',
425 [X3DType]));
426 end;
427
428 procedure TCubicBezierCoordinateInterpolatorNode.EventSet_FractionReceive(
429 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
430 var
431 KeyCount: Integer;
432 T: Single;
433 OutputValue: TMFVec3f;
434 Range: Integer;
435 begin
436 if not EventValue_Changed.SendNeeded then Exit;
437
438 KeyCount := FdKey.Items.Count;
439 if KeyCount = 0 then
440 begin
441 // Interpolator nodes containing no keys in the key field
442 // shall not produce any events.
443 // Moreover, "div KeyCount" would cause errors if we would try
444 // to get some KeyValue or KeyValueLerp.
445 Exit;
446 end;
447
448 Assert(Value is TSFFloat, 'EventSet_FractionReceive (for multiple-value field) can only process SFFloat input events');
449 Assert(not IsNan((Value as TSFFloat).Value), 'EventSet_FractionReceive (for multiple-value field) cannot handle fraction = NaN');
450 Range := KeyRange((Value as TSFFloat).Value, T);
451 if Range = 0 then
452 OutputValue := KeyValue(0, KeyCount)
453 else
454 if Range = KeyCount then
455 OutputValue := KeyValue(KeyCount - 1, KeyCount)
456 else
457 begin
458 if Range - 1 < FdControlPoints.Items.Count then
459 T := CubicBezierValue(T, Range - 1);
460 OutputValue := KeyValueLerp(T, Range - 1, Range, KeyCount);
461 end;
462 OutputValue.InternalPartialSend := Value.InternalPartialSend;
463 try
464 EventValue_Changed.Send(OutputValue, Time);
465 finally
466 FreeAndNil(OutputValue);
467 end;
468 end;
469
470 procedure TCubicBezierCoordinateInterpolatorNode.InterpolatorLerp(const Target: TMFVec3f;
471 const Fraction: Single; const F1, F2: TMFVec3f;
472 const Index1, Index2, ACount: Integer);
473 begin
474 Target.Items.AssignLerpRange(Fraction, F1.Items, F2.Items, Index1, Index2, ACount);
475 end;
476
477 { registration --------------------------------------------------------------- }
478
479 procedure RegisterInterpolationCubicBezierNodes;
480 begin
481 NodesManager.RegisterNodeClasses([
482 TCubicBezier2DOrientationInterpolatorNode,
483 TCubicBezierPositionInterpolatorNode,
484 TCubicBezierCoordinateInterpolatorNode
485 ]);
486 end;
487
488 {$endif read_implementation}