Debian Codegraph @

src/scene/x3d/x3dnodes_standard_time.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2008-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 TTimeFunction = function: TFloatTime of object;
19
20 { Functionality of all time-dependent nodes. }
21 TTimeDependentFunctionality = class(TNodeFunctionality)
22 strict private
23 FIsActive: boolean;
24 FIsPaused: boolean;
25 FElapsedTime: TFloatTime;
26 FElapsedTimeInCycle: TFloatTime;
27 StartTimeUsed, NonLoopedStopped: Double; //< same type as TSFTime.Value
28 procedure SetIsActive(const Value: boolean);
29 procedure SetIsPaused(const Value: boolean);
30 procedure SetElapsedTime(const Value: TFloatTime);
31 private
32 { These should be set by node classes instantiating TTimeDependentFunctionality.
33 TODO: Should be solved cleaner, by abstract methods and then
34 TTimeDependentFunctionality descendants. }
35
36 FdLoop: TSFBool;
37 FdPauseTime: TSFTime;
38 FdResumeTime: TSFTime;
39 FdStartTime: TSFTime;
40 FdStopTime: TSFTime;
41 { May be @nil if node doesn't have an "enabled" field. }
42 FdEnabled: TSFBool;
43
44 EventElapsedTime: TSFTimeEvent;
45 EventIsActive: TSFBoolEvent;
46 EventIsPaused: TSFBoolEvent;
47 { May be @nil if node doesn't have a "cycleTime" event. }
48 EventCycleTime: TSFTimeEvent;
49
50 OnCycleInterval: TTimeFunction;
51 public
52 { Propagate this to all send events, to make animation fade-in/out. }
53 PartialSend: TPartialSend;
54
55 { Final duration (in seconds) of this animation.
56 For a looping animation, this is the time it takes to make a single cycle.
57 Should always be > 0.
58
59 The final length, returned here, is
60
61 @unorderedList(
62 @item(In case of TAudioClipNode: sound duration divided by @link(TAbstractSoundSourceNode.Pitch).)
63
64 @item(In case of TMovieTextureNode: movie duration divided by @link(TMovieTextureNode.Speed).)
65
66 @item(In case of TTimeSensorNode: just @link(TTimeSensorNode.CycleInterval).)
67 ) }
68 function CycleInterval: TFloatTime;
69
70 { Is the sensor enabled and running (ignoring whether it is paused).
71
72 For a precise specification of how this behaves,
73 see the X3D TimeSensor.isActive specification at
74 http://www.web3d.org/documents/specifications/19775-1/V3.3/Part01/components/time.html#TimeSensor
75
76 Changing this automatically causes appropriate events to be generated. }
77 property IsActive: boolean read FIsActive write SetIsActive;
78
79 { Is the sensor paused.
80
81 For a precise specification of how this behaves,
82 see the X3D TimeSensor.isPaused specification at
83 http://www.web3d.org/documents/specifications/19775-1/V3.3/Part01/components/time.html#TimeSensor
84
85 Changing this automatically causes appropriate events to be generated. }
86 property IsPaused: boolean read FIsPaused write SetIsPaused;
87
88 { Time in seconds since the sensor was activated and running,
89 not counting any time while in pause state.
90
91 For non-looping animations, note that the sensor automatically stops
92 when the animation finishes, so ElapsedTime will not grow beyond
93 the @link(CycleInterval). If you want to observe when the animation ended,
94 you probably do not want to use this property. Instead
95 observe when @link(IsActive) changed to @false, by registering
96 a callback on @code(EventIsActive.AddNotification).
97 See the CGE examples/viewport_and_scenes/listen_on_x3d_events/ .
98 Or, even better (simpler and more reliable) register a stop
99 notification using @link(TPlayAnimationParameters.StopNotification) with
100 @link(TCastleSceneCore.PlayAnimation).
101
102 For a precise specification of how this behaves,
103 see the X3D TimeSensor.elapsedTime specification at
104 http://www.web3d.org/documents/specifications/19775-1/V3.3/Part01/components/time.html#TimeSensor
105
106 Changing this automatically causes appropriate events to be generated. }
107 property ElapsedTime: TFloatTime read FElapsedTime write SetElapsedTime;
108
109 { Time in seconds since the sensor was activated and running,
110 in this cycle,
111 not counting any time while in pause state.
112
113 This is like @link(ElapsedTime), but counting only the current cycle.
114 When @link(CycleInterval) = 0, this is always 0.
115 When @link(CycleInterval) <> 0, this is always >= 0 and < CycleInterval . }
116 property ElapsedTimeInCycle: TFloatTime read FElapsedTimeInCycle;
117
118 { Call this when world time increases.
119 This is the most important method of this class, that basically
120 implements time-dependent nodes operations.
121
122 NewTime and TimeIncrease are produced
123 by TCastleSceneCore.SetTime and friends.
124
125 When ResetTime = true, this means that "TimeIncrease value is unknown"
126 (you @italic(must) pass TimeIncrease = 0 in this case).
127 This can happen only when were called by ResetTime.
128
129 In other circumstances, TimeIncrease must be >= 0.
130 (It's allowed to pass TimeIncrease = 0 and ResetTime = false, this doesn't
131 advance the clock, but is a useful trick to force some update,
132 see HandleChangeTimeStopStart in TCastleSceneCore.InternalChangedField implementation.)
133
134 References: see X3D specification "Time" component,
135 8.2 ("concepts") for logic behind all those start/stop/pause/resumeTime,
136 cycleInterval, loop properties.
137
138 @returns(If some state of time-dependent node changed.) }
139 function SetTime(const NewTime: TFloatTime;
140 const TimeIncrease: TFloatTime; const ResetTime: boolean): boolean;
141 end;
142
143 { Abstract node from which most (but not all) time-dependent nodes are derived. }
144 TAbstractTimeDependentNode = class(TAbstractChildNode)
145 private
146 FTimeFunctionality: TTimeDependentFunctionality;
147 { X3D rules state that sometimes input of StartTime, StopTime, CycleInterval
148 should be ignored when animation is already running.
149 As it is sometimes more bothersome than helpful, you can temporarily
150 disable this mechanism (that is, @italic(never ignore)) by increasing this field.
151 @exclude }
152 InternalNeverIgnore: Cardinal;
153 function IgnoreWhenActive(const ChangingField: TX3DField; const Event: TX3DEvent;
154 const Value: TX3DField; const Time: TX3DTime): Boolean;
155 function IgnoreStopTime(const ChangingField: TX3DField; const Event: TX3DEvent;
156 const Value: TX3DField; const Time: TX3DTime): Boolean;
157 public
158 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
159
160 { Is the sensor enabled and running (ignoring whether it is paused).
161
162 See @link(TTimeDependentFunctionality.IsActive). }
163 function IsActive: Boolean;
164
165 { Is the sensor paused.
166
167 See @link(TTimeDependentFunctionality.IsPaused). }
168 function IsPaused: Boolean;
169
170 { Time in seconds since the sensor was activated and running,
171 not counting any time while in pause state.
172
173 See @link(TTimeDependentFunctionality.ElapsedTime). }
174 function ElapsedTime: TFloatTime;
175
176 { Time in seconds since the sensor was activated and running,
177 in this cycle,
178 not counting any time while in pause state.
179
180 See @link(TTimeDependentFunctionality.ElapsedTimeInCycle). }
181 function ElapsedTimeInCycle: TFloatTime;
182
183 {$I auto_generated_node_helpers/x3dnodes_x3dtimedependentnode.inc}
184 end;
185
186 { Generate events as time passes. }
187 TTimeSensorNode = class(TAbstractTimeDependentNode)
188 strict private
189 FakingTime: Integer;
190 procedure EventElapsedTimeReceive(
191 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
192 { CycleInterval that is always > 0. }
193 function SafeCycleInterval: TFloatTime;
194 public
195 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
196
197 { Send TimeSensor output events, without actually activating the TimeSensor.
198
199 This is useful in situations when you want the X3D scene state to reflect
200 given time, but you do not want to activate sensor and generally you do
201 not want to initialize anything that would continue animating on it's own.
202
203 Note: We ignore TimeSensor.loop (FdLoop) field,
204 instead we follow our own ALoop parameter.
205 We also ignore TimeSensor.fractionIncreasing field,
206 instead we follow our own AFractionIncreasing parameter.
207 We also ignore TimeSensor.enabled field,
208 assuming that you always want to behave like it's enabled
209 (in particular, this makes @link(TCastleSceneCore.ForceAnimationPose)
210 always working, even if @link(TCastleSceneCore.PlayAnimation)
211 set enabled = false on previously-stopped animation).
212
213 We take into account TimeSensor.cycleInterval (FdCycleInterval),
214 just like during normal TimeSensor behavior.
215 We send out isActive:=true, fraction_changed, elapsedTime and time X3D
216 output events, and they should drive the rest of animation.
217
218 @italic(About the TimeOfEvents parameter):
219
220 In X3D, if you send a message (which is what happens when various X3D nodes communicate,
221 e.g. TimeSensors send messages to interpolators) the message will be ignored
222 if it already passed through the same route (@link(TX3DRoute))
223 with the timestamp >= than current.
224 This is a simple mechanism to avoid route loops in X3D.
225
226 It means you need to use increasing time each time you initiate an X3D event.
227
228 The implementation of FakeTime without @code(TimeOfEvents) parameter
229 solves it by using an internal, always increasing, time value.
230 It will work, but only if you don't process events in your X3D graphs
231 by any other means than this FakeTime time call.
232
233 In general case, when using FakeTime together with @link(TCastleScene)
234 that has active events (@link(TCastleSceneCore.ProcessEvents) = @true),
235 you should call overloaded TTimeSensorNode.FakeTime with @code(TimeOfEvents) parameter.
236 Use @link(TCastleSceneCore.NextEventTime MyScene.NextEventTime)
237 as the value of @code(TimeOfEvents). NextEventTime internally returns current time,
238 and also increases it by some special epsilon used only for comparison.
239
240 @groupBegin }
241 procedure FakeTime(const TimeInAnimation: TFloatTime;
242 const ALoop, AFractionIncreasing: boolean;
243 const PartialSend: TPartialSend = nil); overload;
244 procedure FakeTime(const TimeInAnimation: TFloatTime;
245 const ALoop, AFractionIncreasing: boolean;
246 const TimeOfEvents: TX3DTime;
247 const PartialSend: TPartialSend = nil); overload;
248 { @groupEnd }
249
250 { Start or stop the time sensor @italic(right now),
251 by setting the fields of this time sensor.
252
253 Usually you should prefer using the @link(TCastleSceneCore.PlayAnimation)
254 or @link(TCastleSceneCore.StopAnimation) instead of these methods.
255 The scene methods allow to play the animation with lots of features,
256 and are more comfortable to use (e.g. you do not need to find
257 the TTimeSensorNode reference).
258
259 Using these methods directly is useful to play multiple animations
260 simultaneously.
261
262 @groupBegin }
263 procedure Start(const ALoop: Boolean;
264 const AFractionIncreasing: Boolean = true;
265 const InitialTime: TFloatTime = 0);
266 procedure Stop;
267 { @groupEnd }
268
269 {$I auto_generated_node_helpers/x3dnodes_timesensor.inc}
270 end;
271
272 {$endif read_interface}
273
274 {$ifdef read_implementation}
275
276 { TTimeDependentFunctionality -------------------------------------------------- }
277
278 procedure TTimeDependentFunctionality.SetIsActive(const Value: boolean);
279 begin
280 if Value <> FIsActive then
281 begin
282 FIsActive := Value;
283 EventIsActive.Send(Value, Parent.Scene.NextEventTime, PartialSend);
284 end;
285 end;
286
287 procedure TTimeDependentFunctionality.SetIsPaused(const Value: boolean);
288 begin
289 if Value <> FIsPaused then
290 begin
291 FIsPaused := Value;
292 EventIsPaused.Send(Value, Parent.Scene.NextEventTime, PartialSend);
293 end;
294 end;
295
296 procedure TTimeDependentFunctionality.SetElapsedTime(const Value: TFloatTime);
297 begin
298 if Value <> FElapsedTime then
299 begin
300 FElapsedTime := Value;
301
302 { NextEventTime below will automatically increase time tick
303 of current time, and that's a good thing.
304
305 Otherwise there was a bug when TCastleSceneCore.ResetTime
306 (caused by ResetTimeAtLoad) was calling all time handlers
307 and in effect changing elapsedTime on all TimeSensors to 0
308 (see TTimeDependentFunctionality.SetTime implementation). This was
309 (and still is) causing elapsedTime and fraction_changed outputs
310 generated even for inactive TimeSensors.
311
312 So it must avoid routes loop warnings by increasing PlusTicks
313 for next elapsedTime send
314 (reproduction: escape_universe game restart.) }
315
316 EventElapsedTime.Send(Value, Parent.Scene.NextEventTime, PartialSend);
317 end;
318 end;
319
320 function TTimeDependentFunctionality.CycleInterval: TFloatTime;
321 begin
322 Assert(Assigned(OnCycleInterval));
323 Result := OnCycleInterval();
324 end;
325
326 function TTimeDependentFunctionality.SetTime(
327 const NewTime: TFloatTime;
328 const TimeIncrease: TFloatTime; const ResetTime: boolean): boolean;
329
330 var
331 NewIsActive: boolean;
332 NewIsPaused: boolean;
333 NewElapsedTime: TFloatTime;
334 CycleTimeSend: boolean;
335 CycleTime: TFloatTime;
336
337 { $define LOG_TIME_DEPENDENT_NODES_OFTEN}
338 { $define LOG_TIME_DEPENDENT_NODES}
339
340 { Increase NewElapsedTime and ElapsedTimeInCycle, taking care of
341 CycleInterval and looping.
342 StopOnNonLoopedEnd says what to do if NewElapsedTime passed
343 CycleInterval and not looping.
344
345 May indicate that CycleTime should be send (by setting CycleTimeSend to true
346 and CycleTime value) if the *new* cycle started. This means
347 that new ElapsedTime reached the non-zero CycleInterval
348 and loop = TRUE. }
349 procedure IncreaseElapsedTime(Increase: TFloatTime; StopOnNonLoopedEnd: boolean);
350 begin
351 { In case of time resetting, we can have wild differences
352 between stopTime and NewTime, and Increase could get < 0.
353 Consider for example trick with startTime := 0, stopTime := 1
354 in UpdateNewPlayingAnimation in TCastleSceneCore.InternalSetTime.
355 So make sure Increase here is always >= 0. }
356 MaxVar(Increase, 0);
357
358 NewElapsedTime := NewElapsedTime + Increase;
359 FElapsedTimeInCycle := FElapsedTimeInCycle + Increase;
360
361 if FElapsedTimeInCycle > CycleInterval then
362 begin
363 if CycleInterval <> 0 then
364 begin
365 if FdLoop.Value then
366 begin
367 FElapsedTimeInCycle := FloatModulo(FElapsedTimeInCycle, CycleInterval);
368 { Send the time value when the cycle started, which was
369 a little earlier than NewTime: earlier by ElapsedTimeInCycle. }
370 CycleTimeSend := true;
371 CycleTime := NewTime - ElapsedTimeInCycle;
372
373 {$ifdef LOG_TIME_DEPENDENT_NODES}
374 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Next cycle (of a looping sensor)');
375 {$endif}
376 end;
377 end else
378 begin
379 { for cycleInterval = 0 this always remains 0 }
380 FElapsedTimeInCycle := 0;
381 end;
382
383 if (not FdLoop.Value) and StopOnNonLoopedEnd then
384 begin
385 {$ifdef LOG_TIME_DEPENDENT_NODES}
386 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Stopping (because end of cycle of non-looping sensor)');
387 {$endif}
388
389 NewIsActive := false;
390 // save NonLoopedStopped to avoid restarting the sensor,
391 // see NonLoopedStopped usage below
392 NonLoopedStopped := StartTimeUsed;
393 end;
394 end;
395 end;
396
397 begin
398 { if ResetTime, then TimeIncrease must be always exactly 0 }
399 Assert((not ResetTime) or (TimeIncrease = 0));
400
401 {$ifdef LOG_TIME_DEPENDENT_NODES_OFTEN}
402 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), Format('Time changes by +%f to %f. Cycle interval: %f, loop %s. Before: active %s, paused %s, elapsedTimeInCycle %f',
403 [ TimeIncrease, NewTime,
404 CycleInterval,
405 BoolToStr(FdLoop.Value, true),
406 BoolToStr(IsActive, true),
407 BoolToStr(IsPaused, true),
408 FElapsedTimeInCycle
409 ]));
410 {$endif}
411
412 Result := false;
413
414 if (FdEnabled <> nil) and (not FdEnabled.Value) then
415 begin
416 {$ifdef LOG_TIME_DEPENDENT_NODES}
417 if IsActive and Log then
418 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Stopping (because disabled)',
419 [NewTime, FdStartTime.Value, CycleInterval]);
420 {$endif}
421
422 IsActive := false;
423 Exit;
424 end;
425
426 { Note that each set of IsActive, IsPaused, ElapsedTime may generate
427 an X3D event. So we should not carelessly set them many times in this method,
428 as it would waste time (why send an event that something changes,
429 when right after it you send another event that is changes?).
430
431 Solution: below we will operate on local copies of these variables,
432 like NewIsActive, NewIsPaused etc.
433 Only at the end of this method we will actually set the properties,
434 causing events (if their values changed). }
435
436 { For ResetTime, set time-dependent node properties to default
437 (like after TTimeDependentFunctionality creation) at the beginning. }
438 if ResetTime then
439 begin
440 NewIsActive := false;
441 NewIsPaused := false;
442 NewElapsedTime := 0;
443 FElapsedTimeInCycle := 0;
444 end else
445 begin
446 NewIsActive := IsActive;
447 NewIsPaused := IsPaused;
448 NewElapsedTime := ElapsedTime;
449 { Leave ElapsedTimeInCycle as it was }
450 end;
451
452 CycleTimeSend := false;
453
454 if not NewIsActive then
455 begin
456 if (NewTime >= FdStartTime.Value) and
457 ( (NewTime < FdStopTime.Value) or
458 { stopTime is ignored if it's <= startTime }
459 (FdStopTime.Value <= FdStartTime.Value) ) and
460 { Avoid restarting the animation if it's non-looping animation
461 that should remain stopped.
462
463 One would think that equation "NewTime - FdStartTime.Value > CycleInterval"
464 is enough to do it reliably, but it's not:
465 - Testcase: Escape with ship_upgrades.json
466 - In case the animation is started at the end of some time-consuming
467 OnUpdate (like when TCastleView starts), and the next OnUpdate may get large
468 SecondsPassed (like 0.2 of second). This means that in initial SetTime
469 call we get "NewTime - FdStartTime.Value" close to zero,
470 but FElapsedTimeInCycle is set to something significant like 0.2.
471 - This 0.2 difference will be preserved, since we only increase
472 FElapsedTimeInCycle in each SetTime call. So eventually the cycle will
473 end once FElapsedTimeInCycle > CycleInterval, but at this point
474 "NewTime - FdStartTime.Value" will be around CycleInterval - 0.2,
475 and so the check "NewTime - FdStartTime.Value > CycleInterval"
476 will fail.
477 - To workaround this, we use NonLoopedStopped, to clearly mark
478 "this run of TimeSensor was already stopped, do not restart it".
479 }
480 not ( ( (NewTime - FdStartTime.Value > CycleInterval) or
481 ( { does NonLoopedStopped indicate we shouldn't restart }
482 (NonLoopedStopped <> 0) and
483 (NonLoopedStopped = FdStartTime.Value)
484 )
485 ) and
486 (not FdLoop.Value)
487 ) then
488 begin
489 {$ifdef LOG_TIME_DEPENDENT_NODES}
490 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Starting. Time now %f, start time %f, cycle interval %f',
491 [NewTime, FdStartTime.Value, CycleInterval]);
492 {$endif}
493
494 StartTimeUsed := FdStartTime.Value; // save, to later used for NonLoopedStopped
495 NewIsActive := true;
496 NewIsPaused := false;
497 NewElapsedTime := 0;
498 FElapsedTimeInCycle := 0;
499
500 { Do not advance by TimeIncrease (time from last Time),
501 advance only by the time passed since startTime. }
502 IncreaseElapsedTime(NewTime - FdStartTime.Value, true);
503
504 if not CycleTimeSend then
505 begin
506 { Then we still have the initial cycleTime event to generate
507 (IncreaseElapsedTime didn't do it for us).
508 This should be the "time at the beginning of the current cycle".
509
510 Since IncreaseElapsedTime didn't detect a new cycle,
511 so NewElapsedTime = NewTime - FdStartTime.Value fits
512 (is < ) within the CycleInterval. So startTime is the beginning
513 of our cycle.
514
515 Or StartedNewCycle = false may mean that CycleInterval is zero
516 or loop = FALSE. We will check later (before actually sending
517 cycleTime) that sensor is active, and if it's active ->
518 we still should make the initial cycleTime.
519
520 So in both cases, proper cycleTime is startTime. }
521 CycleTimeSend := true;
522 CycleTime := FdStartTime.Value;
523 end;
524
525 Result := true;
526 end;
527 end else
528 if NewIsPaused then
529 begin
530 if (NewTime >= FdResumeTime.Value) and
531 (FdResumeTime.Value > FdPauseTime.Value) then
532 begin
533 {$ifdef LOG_TIME_DEPENDENT_NODES}
534 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Resuming');
535 {$endif}
536
537 NewIsPaused := false;
538 { Advance only by the time passed since resumeTime. }
539 IncreaseElapsedTime(NewTime - FdResumeTime.Value, true);
540 Result := true;
541 end;
542 end else
543 begin
544 Result := true;
545
546 if (NewTime >= FdStopTime.Value) and
547 { stopTime is ignored if it's <= startTime }
548 (FdStopTime.Value > FdStartTime.Value) then
549 begin
550 NewIsActive := false;
551 { advance only to the stopTime }
552 if TimeIncrease <> 0 then
553 IncreaseElapsedTime(TimeIncrease - (NewTime - FdStopTime.Value), false);
554
555 {$ifdef LOG_TIME_DEPENDENT_NODES}
556 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Stopped (because stopTime reached)');
557 {$endif}
558 end else
559 if (NewTime >= FdPauseTime.Value) and
560 (FdPauseTime.Value > FdResumeTime.Value) then
561 begin
562 NewIsPaused := true;
563 { advance only to the pauseTime }
564 if TimeIncrease <> 0 then
565 IncreaseElapsedTime(TimeIncrease - (NewTime - FdPauseTime.Value), false);
566
567 {$ifdef LOG_TIME_DEPENDENT_NODES}
568 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), 'Paused');
569 {$endif}
570 end else
571 begin
572 { active and not paused time-dependent node }
573 if ResetTime then
574 begin
575 NewElapsedTime := 0;
576 FElapsedTimeInCycle := 0;
577 end else
578 IncreaseElapsedTime(TimeIncrease, true);
579 end;
580 end;
581
582 { now set actual IsActive, IsPaused, ElapsedTime properties from
583 their NewXxx counterparts. We take care to set them in proper
584 order, to send events in proper order:
585 if you just activated the movie, then isActive should be sent first,
586 before elapsedTime.
587 If the movie was deactivated, then last elapsedTime should be sent last.
588
589 Send cycleTime only if NewIsActive, and after sending isActive = TRUE. }
590 if NewIsActive then
591 begin
592 IsActive := NewIsActive;
593 if not NewIsPaused then
594 begin
595 IsPaused := NewIsPaused;
596 ElapsedTime := NewElapsedTime;
597 end else
598 begin
599 ElapsedTime := NewElapsedTime;
600 IsPaused := NewIsPaused;
601 end;
602
603 if CycleTimeSend and (EventCycleTime <> nil) then
604 EventCycleTime.Send(CycleTime, Parent.Scene.NextEventTime, PartialSend);
605 end else
606 begin
607 if not NewIsPaused then
608 begin
609 IsPaused := NewIsPaused;
610 ElapsedTime := NewElapsedTime;
611 end else
612 begin
613 ElapsedTime := NewElapsedTime;
614 IsPaused := NewIsPaused;
615 end;
616 IsActive := NewIsActive;
617 end;
618
619 { This will be true in most usual situations, but in some complicated
620 setups sending isActive/isPaused/elapsedTime (and sending elapsedTime
621 causes sending other events for TimeSensor) may cause sending another
622 event to the same node, thus calling SetTime recursively,
623 and changing values at the end. Example: rrtankticks when often
624 clicking on firing the cannon. So these assertions do not have to be
625 true in complicated scenes.
626
627 Assert(IsActive = NewIsActive);
628 Assert(IsPaused = NewIsPaused);
629 Assert(ElapsedTime = NewElapsedTime);
630 }
631
632 {$ifdef LOG_TIME_DEPENDENT_NODES_OFTEN}
633 WritelnLog(Format('Time-dependent node %s', [Node.NiceName]), Format('SetTime finished. Active %s, paused %s, elapsedTimeInCycle %f',
634 [ BoolToStr(IsActive, true),
635 BoolToStr(IsPaused, true),
636 FElapsedTimeInCycle
637 ]));
638 {$endif}
639 end;
640
641 { TAbstractTimeDependentNode ------------------------------------------------------------- }
642
643 constructor TAbstractTimeDependentNode.Create(const AX3DName, ABaseUrl: String);
644 begin
645 inherited;
646
647 FTimeFunctionality := TTimeDependentFunctionality.Create(Self);
648 FTimeFunctionality.FdLoop := FdLoop;
649 FTimeFunctionality.FdPauseTime := FdPauseTime;
650 FTimeFunctionality.FdResumeTime := FdResumeTime;
651 FTimeFunctionality.FdStartTime := FdStartTime;
652 FTimeFunctionality.FdStopTime := FdStopTime;
653 { descendants should set FTimeFunctionality.FdEnabled }
654 FTimeFunctionality.EventIsActive := EventIsActive;
655 FTimeFunctionality.EventIsPaused := EventIsPaused;
656 FTimeFunctionality.EventElapsedTime := EventElapsedTime;
657 { descendants should set FTimeFunctionality.EventCycleTime }
658
659 AddFunctionality(FTimeFunctionality);
660
661 FdStartTime.OnInputIgnore := {$ifdef FPC}@{$endif} IgnoreWhenActive;
662 FdStopTime.OnInputIgnore := {$ifdef FPC}@{$endif} IgnoreStopTime;
663 end;
664
665 function TAbstractTimeDependentNode.IgnoreWhenActive(
666 const ChangingField: TX3DField; const Event: TX3DEvent;
667 const Value: TX3DField; const Time: TX3DTime): Boolean;
668 begin
669 Result := (InternalNeverIgnore = 0) and FTimeFunctionality.IsActive;
670 end;
671
672 function TAbstractTimeDependentNode.IgnoreStopTime(
673 const ChangingField: TX3DField; const Event: TX3DEvent;
674 const Value: TX3DField; const Time: TX3DTime): Boolean;
675 begin
676 Result := (InternalNeverIgnore = 0) and
677 FTimeFunctionality.IsActive and
678 ( (Value as TSFTime).Value <= FdStartTime.Value );
679 end;
680
681 function TAbstractTimeDependentNode.IsActive: Boolean;
682 begin
683 Result := FTimeFunctionality.IsActive;
684 end;
685
686 function TAbstractTimeDependentNode.IsPaused: Boolean;
687 begin
688 Result := FTimeFunctionality.IsPaused;
689 end;
690
691 function TAbstractTimeDependentNode.ElapsedTime: TFloatTime;
692 begin
693 Result := FTimeFunctionality.ElapsedTime;
694 end;
695
696 function TAbstractTimeDependentNode.ElapsedTimeInCycle: TFloatTime;
697 begin
698 Result := FTimeFunctionality.ElapsedTimeInCycle;
699 end;
700
701 { TTimeSensorNode ------------------------------------------------------------ }
702
703 constructor TTimeSensorNode.Create(const AX3DName, ABaseUrl: String);
704 begin
705 inherited;
706
707 { set FTimeFunctionality properties }
708 FTimeFunctionality.FdEnabled := FdEnabled;
709 FTimeFunctionality.EventCycleTime := EventCycleTime;
710 FTimeFunctionality.OnCycleInterval := {$ifdef FPC}@{$endif} GetCycleInterval;
711
712 { On receiving new elapsedTime, we send other continuous events. }
713 EventElapsedTime.AddNotification({$ifdef FPC}@{$endif} EventElapsedTimeReceive);
714
715 FdCycleInterval.OnInputIgnore := {$ifdef FPC}@{$endif} IgnoreWhenActive;
716
717 { cycleTime_changed name is used e.g. by
718 www.web3d.org/x3d/content/examples/Basic/StudentProjects/WallClock.x3d }
719 FEventCycleTime.AddAlternativeName('cycleTime_changed', 0);
720 end;
721
722 function TTimeSensorNode.SafeCycleInterval: TFloatTime;
723 begin
724 Result := CycleInterval;
725 if Result <= 0 then
726 Result := 1;
727 end;
728
729 procedure TTimeSensorNode.EventElapsedTimeReceive(
730 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
731 var
732 Fraction: Single;
733 begin
734 if (FakingTime = 0) and FdEnabled.Value then
735 begin
736 Fraction := FTimeFunctionality.ElapsedTimeInCycle / SafeCycleInterval;
737 if (Fraction = 0) and (Time.Seconds > FdStartTime.Value) then Fraction := 1;
738 if not FdFractionIncreasing.Value then
739 Fraction := 1 - Fraction;
740 Eventfraction_changed.Send(Fraction, Time, Value.InternalPartialSend);
741
742 EventTime.Send(Time.Seconds, Time, Value.InternalPartialSend);
743 end;
744 end;
745
746 var
747 FakeX3DTime: TX3DTime;
748
749 procedure TTimeSensorNode.FakeTime(const TimeInAnimation: TFloatTime;
750 const ALoop, AFractionIncreasing: boolean;
751 const PartialSend: TPartialSend);
752 begin
753 { This method may be called with any TimeInAnimation values sequence,
754 e.g. decreasing.
755
756 So we have to calculate TimeOfEvents independent from Time,
757 and always growing (to avoid the normal VRML/X3D mechanism that prevents
758 passing ROUTEs with an older timestamp (see TX3DRoute.EventReceive).
759 We do this by simply using a fake timestamp that is always growing. }
760 if FakeX3DTime.PlusTicks <> High(FakeX3DTime.PlusTicks) then
761 Inc(FakeX3DTime.PlusTicks) else
762 begin
763 FakeX3DTime.Seconds := FakeX3DTime.Seconds + 1;
764 FakeX3DTime.PlusTicks := 0;
765 end;
766
767 FakeTime(TimeInAnimation, ALoop, AFractionIncreasing, FakeX3DTime, PartialSend);
768 end;
769
770 procedure TTimeSensorNode.FakeTime(const TimeInAnimation: TFloatTime;
771 const ALoop, AFractionIncreasing: boolean;
772 const TimeOfEvents: TX3DTime;
773 const PartialSend: TPartialSend);
774 var
775 Fraction: Single;
776 begin
777 Inc(FakingTime);
778 EventIsActive.Send(true, TimeOfEvents, PartialSend);
779
780 if ALoop then
781 Fraction := Frac(TimeInAnimation / SafeCycleInterval)
782 else
783 Fraction := Clamped(TimeInAnimation / SafeCycleInterval, 0, 1);
784 if not AFractionIncreasing then
785 Fraction := 1 - Fraction;
786 EventFraction_changed.Send(Fraction, TimeOfEvents, PartialSend);
787
788 EventElapsedTime.Send(TimeInAnimation, TimeOfEvents, PartialSend);
789 EventTime.Send(TimeInAnimation, TimeOfEvents, PartialSend);
790 Dec(FakingTime);
791 end;
792
793 procedure TTimeSensorNode.Stop;
794 begin
795 { We want to stop time sensor from sending any further
796 elapsedTime events (elapsedTime causes also fraction_changed).
797 Sending of further elapsedTime means that two animations try to play
798 at the same time, and modify the same transforms.
799
800 One way to stop animation is to set
801
802 PlayingAnimationNode.StopTime := Time;
803
804 While it works in practice (no reproducible bug with it found),
805 it has 2 problems:
806
807 - There will be 1 additional frame when TimeSensor "finishes of"
808 the animation, by remaining "TimeIncrease - (NewTime - FdStopTime.Value)"
809 duration. This isn't a problem in practice, since it only happens for 1 frame
810 (then the old TimeSensor becomes inactive), but it stil feels dirty/wasteful.
811
812 - In case you will move time backwards, e.g. by ResetTime or ResetTimeAtLoad,
813 you may get into trouble.
814 You may accidentally activate a time sensor that is
815 inactive now, but was active long time ago.
816
817 To overcome the 2nd problem, we tried the trick below.
818 It will work assuming you never reset time to something < 1.
819 (If you do reset time to something very small, then typical TimeSensors will
820 have problems anyway,
821 see https://castle-engine.io/x3d_time_origin_considered_uncomfortable.php ).
822
823 PlayingAnimationNode.StartTime := 0;
824 PlayingAnimationNode.StopTime := 1;
825 PlayingAnimationNode.Loop := false;
826
827 But this:
828 - Still has the "1 additional frame when TimeSensor finishes of" dirtyness.
829 - Also, setting startTime while time-dependent node is active is ignored,
830 X3D spec requires this, see our TSFTimeIgnoreWhenActive implementation.
831 (bug reproduction: escape_universe, meteorite_1 dying).
832 Although we remove this problem by InternalNeverIgnore hack.
833 - (Obsolete argument:) Also, it's bad to unconditionally set "Loop" value.
834 If user is using paDefault for animation, (s)he expects
835 that PlayAnimation doesn't change it ever.
836
837 So it's simpest and reliable to just set enabled=false on old TimeSensor.
838 TTimeDependentFunctionality.SetTime then guarantees it will immediately stop
839 sending elapsedTime events. }
840
841 Enabled := false;
842 end;
843
844 procedure TTimeSensorNode.Start(const ALoop, AFractionIncreasing: Boolean;
845 const InitialTime: TFloatTime);
846 begin
847 Check(Scene <> nil, 'TTimeSensorNode.Start can only be called when node is part of scene');
848
849 Loop := ALoop;
850 FractionIncreasing := AFractionIncreasing;
851 Enabled := true; // since Stop changes Enabled to false
852
853 { Disable the "ignore" mechanism, otherwise
854 setting startTime on a running TimeSensor would be ignored.
855 Testcase: e.g. mana animation on dark_dragon and dragon_squash. }
856 Inc(InternalNeverIgnore);
857
858 { Assign StopTime and StartTime. }
859 StopTime := 0;
860 StartTime := Scene.Time - InitialTime;
861
862 { Enable the "ignore" mechanism again, to follow X3D spec. }
863 Dec(InternalNeverIgnore);
864 end;
865
866 procedure RegisterTimeNodes;
867 begin
868 NodesManager.RegisterNodeClasses([
869 TTimeSensorNode
870 ]);
871 end;
872
873 {$endif read_implementation}