Debian Codegraph @

src/scene/x3d/castlefields_x3dfield.inc

raw
1 {%MainUnit x3dfields.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
19 TX3DField = class;
20 TX3DFieldList = class;
21
22 TX3DFieldClass = class of TX3DField;
23
24 { Called when @link(TX3DEvent) is received,
25 see @link(TX3DEvent.AddNotification). }
26 TX3DEventReceive = procedure (const Event: TX3DEvent; const Value: TX3DField;
27 const Time: TX3DTime) of object;
28
29 { Send along with the animation that should be applied only partially
30 (because it fades-out or fades-in). }
31 TPartialSend = class
32 { Strength of the fading-in/out animation, in 0..1. }
33 Partial: Single;
34
35 { All fields affected by sending of this TPartialSend should
36 add themselves to this list. }
37 AffectedFields: TX3DFieldList;
38
39 { Ignore the send on fields that do not support lerp
40 (e.g. integer and boolean fields). }
41 IgnoreIfCannotLerp: Boolean;
42
43 constructor Create;
44 destructor Destroy; override;
45 end;
46
47 TInputIgnoreEvent = function (
48 const Field: TX3DField; const Event: TX3DEvent;
49 const Value: TX3DField; const Time: TX3DTime): Boolean of object;
50
51 { Base class for all VRML/X3D fields.
52
53 Common notes for all descendants: most of them expose a field or property
54 "Value", which specifies the current value of the field.
55 Many of them also expose DefaultValue and DefaultValueExists
56 fields/properties, these should be the default X3D value for this field.
57 You can even change DefaultValue after the object is created.
58
59 Most of descendants include constructor that initializes
60 both DefaultValue and Value to the same thing, as this is what
61 you usually want.
62
63 Some notes about @code(Assign) method (inherited from TPersistent and
64 overridied appropriately in TX3DField descendants):
65
66 @orderedList(
67 @item(There are some exceptions, but usually
68 assignment is possible only when source and destination field classes
69 are equal.)
70
71 @item(Assignment (by @code(Assign), inherited from TPersistent)
72 tries to copy everything: name (with alternative names), default value,
73 IsClauseNames, ValueFromIsClause, Exposed, and of course current value.
74
75 Exceptions are things related to hierarchy of containers:
76 ParentNode, ParentInterfaceDeclaration. Also ExposedEventsLinked.
77
78 If you want to copy only the current value, use AssignValue
79 (or AssignLerp, where available).))
80 }
81 TX3DField = class(TX3DFieldOrEvent)
82 strict private
83 FExposedEvents: array [boolean] of TX3DEvent;
84 FChangeAlways: TX3DChange;
85
86 // keep booleans together, to pack them together in memory
87 FExposed: boolean;
88 FValueFromIsClause: boolean;
89 FExposedEventsLinked: boolean;
90 FResetValue: TX3DField;
91
92 procedure SetExposed(Value: boolean);
93 function GetExposedEvents(InEvent: boolean): TX3DEvent;
94 procedure SetExposedEventsLinked(const Value: boolean);
95 function AbortAssignValue(const Source: TX3DField): Boolean;
96
97 { Handle exposed input event. Checks OnInputIgnore,
98 assigns value, sends an output event, notifies @link(Changed). }
99 procedure ExposedEventReceive(const Event: TX3DEvent; const Value: TX3DField;
100 const Time: TX3DTime);
101 private
102 type
103 { Tracking of fading-in/out animation state on this particular field. }
104 TPartialReceived = class
105 { Strength of the fading-in/out value accumulated inside PartialValue.
106 Reset each frame.
107
108 Sending value with TPartialSend.Partial = X always adds X to this
109 TPartialReceived.Partial, when send in the same frame.
110 So e.g. sending two values, one with TPartialSend.Partial = 0.3,
111 one with TPartialSend.Partial = 0.7, sets TPartialReceived.Partial = 1.0.
112
113 At the end, PartialValue will be mixed (lerp) with FResetValue,
114 to produce final Value.
115 This way animation blending works in various cases:
116 - New animations fades-in, old animation fades-out
117 (at the end, Partial = 1.0).
118 - New animations fades-in, no old animation fades-out
119 (maybe fading-out animation does not affect this field,
120 or maybe there is no fading-out animation)
121 (at the end, Partial <= 1.0).
122 }
123 Partial: Single;
124
125 { Accumulated (this frame) partial values. }
126 PartialValue: TX3DField;
127
128 { Should the PartialValue, FResetValue be used to determine
129 field value this frame.
130
131 Why do we need this?
132
133 Checking this in InternalAffectedPartial avoids processing the field
134 twice, in case it was added twice to PartialSend.AffectedFields
135 (easily possible if it was under the influence of both old and new
136 animations).
137
138 Why not using Partial <> 0 for this?
139
140 Because sometimes Partial may be 0.
141
142 When starting a 1st animation, and it has TransitionDuration <> 0,
143 then the SetTime in HandleChangeTimeStopStart
144 activates the sensor, and the next SetTime (from Update)
145 may produce PartialReceived instance with PartialReceived.Partial = 0.
146
147 We *want* to apply this PartialReceived.Partial with 0.
148 Otherwise, the field value would be set immediately to the 1st pose
149 of new animation, disregarding smooth animation blending.
150
151 Testcase: examples/animations/play_animation/ , switch to sample 3D,
152 increase transition = max, play "idle".
153 When "Partial <> 0" is used instead of ToBeApplied,
154 the 1st frame of "idle" quickly blinks at the beginning.
155
156 We could hack it by not doing SetTime in HandleChangeTimeStopStart,
157 but it's better to behave reliably in this case (Partial = 0) alwatys.
158
159 This is now just a shortcut for "PartialValue <> nil", as this satisfies
160 our needs.
161 }
162 function ToBeApplied: boolean;
163
164 destructor Destroy; override;
165 end;
166
167 var
168 { Internally set to non-nil only on fields representing event value
169 (Value parameter in TX3DEventReceive callback),
170 in case they correspond to a fading-in or fading-out animation. }
171 FPartialSend: TPartialSend;
172
173 {$ifndef FPC}
174 function GetInternalPartialSend: TPartialSend;
175 procedure SetInternalPartialSend(const Value: TPartialSend);
176 {$endif}
177 class var
178 FPartialSendIgnore: Cardinal;
179
180 var
181 { Used by fields that have their value affected by the fading-in/fading-out
182 animation. }
183 PartialReceived: TPartialReceived;
184 strict protected
185 function SendsByEvent: boolean;
186
187 { Save field value to a stream. Must be overriden for each specific
188 field.
189
190 For classic encoding, FieldSaveToStream and SaveToStream write
191 Indent, Name, ' ', then call SaveToStreamValue, then write @link(NL).
192
193 IS clauses are not saved by FieldSaveToStream or SaveToStream.
194 (They must be saved specially, by SaveToStreamClassicIsClauses
195 or special XML output.)
196 SaveToStream still checks ValueFromIsClause, if ValueFromIsClause
197 we will not call SaveToStreamValue. So when overriding
198 SaveToStreamValue, you can safely assume that ValueFromIsClause
199 is @false. }
200 procedure SaveToStreamValue(Writer: TX3DWriter); virtual; abstract;
201
202 { Save method of SaveToStreamValue. May assume things that
203 SaveToStreamValue may issume, for example: if this is used at all,
204 then at least field value is not default (so there is a need to write
205 this field) and such. }
206 function SaveToXmlValue: TSaveToXmlMethod; virtual;
207
208 { Call this inside overriden Assign methods.
209 I don't want to place this inside TX3DField.Assign, since I want
210 "inherited" in Assign methods to cause exception. }
211 procedure VRMLFieldAssignCommon(Source: TX3DField);
212
213 procedure AssignValueRaiseInvalidClass(Source: TX3DField);
214
215 { Class of the fields allowed in the exposed events of this field.
216 This should usually be using ClassType of this object,
217 and this is the default implementation of this method in TX3DField.
218
219 You can override this to return some ancestor (from which, and to which,
220 you can assign) if your TX3DField descendant
221 doesn't change how the @code(Assign) method works.
222 E.g. TSFTextureUpdate class, that wants to be fully compatible with normal
223 TSFString. }
224 class function ExposedEventsFieldClass: TX3DFieldClass; virtual;
225 public
226 OnInputIgnore: TInputIgnoreEvent;
227
228 { Main constructor that initializes field when default value is not known.
229
230 It is virtual, so you can use it to construct field instance when
231 field class is known only at runtime.
232 For example you can have variable like "FieldClass: TX3DFieldClass"
233 and use it to construct the field instance.
234 Such field can be later initialized e.g. using @link(Parse).
235
236 Note: Two exceptional VRML 1.0 fields simply cannot work when initialized
237 by this constructor: TSFEnum and TSFBitMask .
238 They simply need to know their TSFEnum.EnumNames, or
239 TSFBitMask.FlagNames + TSFBitMask.NoneString + TSFBitMask.AllString
240 before they can be parsed.
241 Luckily these fields have been removed in VRML 2.0 and X3D so we don't need
242 to support them e.g. in VRML 2.0 and X3D prototypes.
243
244 Descendants implementors:
245
246 1. Descendants should override this virtual constructor, CreateUndefined,
247 to do all obligatory initialization work (e.g. create some internal
248 TStringList).
249
250 Call "inherited" at the beginning of the implementation
251 of this overridden "CreateUndefined".
252
253 2. Can Create also a convenience non-virtual constructor Create,
254 that takes as parameter initial value (with type specific to given
255 field, e.g. Integer for TSFInt32).
256
257 This convenience constructor
258 should call "CreateUndefined" (not "inherited Create" or "inherited CreateUndefined"!)
259 at the beginning.
260
261 TODO: Rename this to just Create, to obscure parent Create.
262 After everything migrated to calling CreateUndefined.
263 }
264 constructor CreateUndefined(const AParentNode: TX3DFileItem;
265 const AExposed: boolean; const AName: String); virtual;
266
267 destructor Destroy; override;
268
269 { Parse inits properties from Lexer.
270
271 In this class, Parse only appends to IsClauseNames:
272 if we stand on "IS" clause (see VRML 2.0 spec about "IS" clause)
273 and IsClauseAllowed then we append specified identifier to
274 IsClauseNames.
275
276 If "IS" clause not found, we call ParseValue which should
277 actually parse field's value.
278 Descendants should override ParseValue. }
279 procedure Parse(Lexer: TX3DLexer; Reader: TX3DReader; IsClauseAllowed: boolean);
280
281 procedure ParseValue(Lexer: TX3DLexer; Reader: TX3DReader); virtual; abstract;
282
283 { Parse field value from X3D XML encoded attribute using a Lexer.
284 Attributes in X3D are generally encoded such that normal
285 @code(ParseValue(Lexer, nil)) call is appropriate,
286 so this is done in this class. }
287 procedure ParseXMLAttributeLexer(Lexer: TX3DLexer; Reader: TX3DReader); virtual;
288
289 { Parse field value from X3D XML encoded attribute.
290
291 Implementation in this class creates a Lexer to parse the string,
292 and calls ParseXMLAttributeLexer. }
293 procedure ParseXMLAttribute(const AttributeValue: String; Reader: TX3DReader); virtual;
294
295 { Parse field's value from XML Element children.
296 This is used to read SFNode / MFNode field value inside <field>
297 (for interface declaration default field value) and <fieldValue>
298 inside <ProtoInstance>. }
299 procedure ParseXMLElement(Element: TDOMElement; Reader: TX3DReader); virtual;
300
301 { Save the field to the stream.
302 Field name (if set, omitted if empty) and value are saved.
303 Unless the current field value equals default value and
304 FieldSaveWhenDefault is @false (default), then nothing is saved.
305
306 IS clauses are not saved here (because they often have to be treated
307 specially anyway, for XML encoding, for prototype declarations etc.). }
308 procedure FieldSaveToStream(Writer: TX3DWriter;
309 FieldSaveWhenDefault: boolean = false;
310 XmlAvoidSavingNameBeforeValue: boolean = false);
311
312 { Save the field to the stream.
313
314 This simply calls FieldSaveToStream(Writer).
315 See FieldSaveToStream for more comments and when you need control over
316 FieldSaveWhenDefault behavior.
317
318 It doesn't actually save anything if field value is defined
319 and equals default value. }
320 procedure SaveToStream(Writer: TX3DWriter); override;
321 function SaveToXml: TSaveToXmlMethod; override;
322
323 { Does current field value came from expanding "IS" clause.
324 If yes, then saving this field to stream will only save it's "IS" clauses,
325 never saving actual value. }
326 property ValueFromIsClause: boolean
327 read FValueFromIsClause write FValueFromIsClause;
328
329 { Whether the value is equal to default.
330 Returns always @false in TX3DField, descendants should override it.
331 It is used when writing the field value to X3D file (values that are default
332 do not have to be written, ever). }
333 function EqualsDefaultValue: boolean; virtual;
334
335 { @true if the SecondValue object has exactly the same type and properties.
336 For this class, this returns just (SecondValue.Name = Name).
337
338 All descendants (that add some property that should be compared)
339 should override this like
340
341 @longCode(#
342 Result := (inherited Equals(SecondValue)) and
343 (SecondValue is TMyType) and
344 (TMyType(SecondValue).MyProperty = MyProperty);
345 #)
346
347 The floating-point fields may be compared with a small epsilon
348 tolerance by this method.
349
350 Note that this *doesn't* compare the default values of two fields
351 instances. This compares only the current values of two fields
352 instances, and eventually some other properties that affect
353 parsing (like names for TSFEnum and TSFBitMask) or allowed
354 future values (like TSFFloat.MustBeNonnegative).
355 }
356 function Equals(SecondValue: TX3DField): boolean; reintroduce; virtual;
357
358 { Compare value of this field, with other field, fast.
359
360 This compares only the values of the fields, not other properties
361 (it doesn't care about names of the fields or such, or default values;
362 only current values). In other words, it compares only the things
363 copied by AssignValue.
364
365 This tries to compare very fast, which means that for large
366 (multi-valued) fields it may give up and answer @false even
367 when they are in fact equal. So this is usable only for optimization
368 purposes: when it answers @true, it is @true. When it answers @false,
369 it actually doesn't know.
370
371 Default implementation in this class (@classname) just returns @false. }
372 function FastEqualsValue(SecondValue: TX3DField): boolean; virtual;
373
374 { Does this field generate/accept events, that is
375 an "exposedField" (in VRML 2.0) or "inputOutput" (in X3D). }
376 property Exposed: boolean read FExposed write SetExposed default false;
377
378 { These are the set_xxx and xxx_changed events exposed by this field.
379 @nil if Exposed is @false. }
380 property ExposedEvents [InEvent: boolean]: TX3DEvent
381 read GetExposedEvents;
382
383 { Exposed events of this field. @nil if this field is not exposed.
384 EventIn is always equivalent to ExposedEvents[true],
385 EventOut is always equivalent to ExposedEvents[false].
386 @groupBegin }
387 function EventIn: TX3DEvent;
388 function EventOut: TX3DEvent;
389 { @groupEnd }
390
391 { When @true (default) we will automatically handle exposed events
392 behavior. This means that we will listen on EventIn,
393 and when something will be received we will set current field's value
394 and produce appropriate EventOut.
395
396 You almost certainly want to leave this as @true in all typical
397 situations, as it takes care of implementing required exposed events
398 behavior.
399
400 That said, in special cases you may decide to break this. }
401 property ExposedEventsLinked: boolean
402 read FExposedEventsLinked write SetExposedEventsLinked
403 default true;
404
405 { Field type in X3D, like @code('SFString') or @code('MFInt32').
406 As for VRML/X3D interface declaration statements.
407 In base TX3DField class, this returns @code(XFAny)
408 (name indicating any type, used by instantreality and us). }
409 class function X3DType: String; virtual;
410 class function TypeName: String; deprecated 'use X3DType';
411
412 { Create TX3DEvent descendant suitable as exposed event for this field. }
413 class function CreateEvent(const AParentNode: TX3DFileItem; const AName: String; const AInEvent: boolean): TX3DEvent; virtual;
414
415 { Copies the current field value. Contrary to TPersistent.Assign, this
416 doesn't copy the rest of properties.
417
418 After setting, our ValueFromIsClause is always changed to @false.
419 You can manually change it to @true, if this copy indeed was done
420 following "IS" clause.
421
422 @raises(EX3DFieldAssignInvalidClass
423 Usually it's required the Source class to be equal to our class,
424 if Source classes cannot be assigned we raise EX3DFieldCannotAssignClass.)
425
426 @raises(EX3DFieldAssign
427 Raised in case of any field assignment problem. It's guaranteed that
428 in case of such problem, our value will not be modified before
429 raising the exception.
430
431 EX3DFieldAssignInvalidClass inherits from EX3DFieldAssign,
432 so actually EX3DFieldAssignInvalidClass is just a special case of this
433 exceptiion.)
434
435 @italic(Descendants implementors notes):
436
437 In this class, implementation takes care of
438 setting our ValueFromIsClause to @false. In descendants,
439 you should do like
440
441 @longCode(#
442 if Source is <appropriate class> then
443 begin
444 inherited;
445 Value := Source.value;
446 end else
447 AssignValueRaiseInvalidClass(Source);
448 #)
449 }
450 procedure AssignValue(Source: TX3DField); virtual;
451
452 { Set field's default value from the current value.
453
454 Note that for now this doesn't guarantee that every possible field's value
455 can be stored as default value. In case of trouble, it will silently
456 record "no default is known" information, so e.g. EqualsDefaultValue
457 will always return @false.
458 Our default value mechanisms are sometimes
459 limited, not every value can be a default value. For example,
460 for multiple-valued nodes, we usually cannot save arrays longer than
461 one as default value. This is not a problem, since X3D specification
462 doesn't specify too long default values. But it may be a problem
463 for prototypes, since then user can assign any value as default value.
464 May be corrected in the future. }
465 procedure AssignDefaultValueFromValue; virtual;
466
467 { Remove default value, recording that "no default is known".
468 In effect EqualsDefaultValue will always return @false. }
469 procedure UnassignDefaultValue; virtual;
470
471 { Assigns value to this node calculated from linear interpolation
472 between two given nodes Value1, Value2. Just like other lerp
473 functions in our units (like @link(CastleVectors.Lerp)).
474
475 Like AssignValue, this copies only the current value.
476 All other properties (like Name, IsClauseNames, ValueFromIsClause,
477 default value) are untouched.
478
479 There are some special precautions for this:
480
481 @unorderedList(
482 @item(First of all, AssignLerp is defined only for fields where
483 CanAssignLerp returns @true, so always check CanAssignLerp first.
484 All float-based fields should have this implemented.)
485
486 @item(Use this only if Value1 and Value2
487 are equal or descendant of target (Self) class.)
488
489 @item(For multiple-value fields, counts of Value1 and Value2
490 must be equal, or EListsDifferentCount will be raised.)
491 )
492
493 @raises(EListsDifferentCount When field is multiple-value
494 field and Value1.Count <> Value2.Count.)
495 }
496 procedure AssignLerp(const A: Double; Value1, Value2: TX3DField); virtual;
497
498 { @abstract(Is AssignLerp usable on this field type?)
499
500 @italic(Descendants implementors notes):
501 In this class, this always returns @false. }
502 function CanAssignLerp: boolean; virtual;
503
504 procedure AddAlternativeName(const AlternativeName: String;
505 const X3DMajorVersion: Integer); override;
506
507 { Notify ParentNode.Scene that the value of this field changed. }
508 procedure Changed;
509
510 { What always happens when the value of this field changes.
511
512 This is included in the @link(ExecuteChange) method result. So instead of
513 using this property, you could always override @link(ExecuteChange)
514 method. But often it's easier to use the property.
515
516 By default this is chNone.
517 See TX3DChange for possible values. }
518 property ChangeAlways: TX3DChange read FChangeAlways write FChangeAlways default chNone;
519
520 { What happens when the value of this field changes.
521 This is called, exactly once, by TCastleSceneCore.InternalChangedField
522 to determine what must be done when we know that value of this field changed.
523
524 In overridden descendants, this can also do something immediately.
525 Overriding this is similar to registering your callback by
526 @link(TX3DEvent.AddNotification EventOut.AddNotification), with two additional benefits:
527
528 @orderedList(
529 @item(This method may be not called (although no guarantees)
530 when the actual field value did not change.
531 In contrast, the event notification is always fired,
532 even when you send the same value to an exposed field,
533 because VRML/X3D events and routes must be fired anyway.)
534
535 @item(This is useful also for fields that are not exposed,
536 and can be changed only by ObjectPascal code.)
537 )
538
539 So overridding this is closer to "do something when field value changes"
540 than registering notification by @link(TX3DEvent.AddNotification EventOut.AddNotification). }
541 function ExecuteChange: TX3DChange; virtual;
542
543 { Set the value of the field, notifying the scenes and events engine.
544 This sets the value of this field in the nicest possible way for
545 any possible TCastleSceneCore (with events on or off) containing the node
546 with this field.
547
548 Precise specification:
549
550 @unorderedList(
551 @item(If this is an exposed field and we have events engine working:
552
553 We will send this value through
554 it's input event. In this case, this is equivalent to doing
555 @code(EventIn.Send(Value, Scene.Time)).
556 The scenes (including events engine) will be notified correctly
557 by exposed events handler already.)
558
559 @item(Otherwise, we will just set the fields value.
560 And then notify the scenes (including events engine).)
561 ) }
562 procedure Send(Value: TX3DField); overload;
563
564 { Notifications when exposed field received new value through VRML/X3D event.
565 Use only for exposed fields.
566 This is simply a shortcut for @code(EventOut.AddNotification),
567 @code(EventOut.RemoveNotification),
568 see @link(TX3DEvent.AddNotification) for details how does this work.
569
570 Note that this observes the "out" event (not the "in" event).
571 This way you know inside the handler that the field value is already
572 changed as appropriate. Inside "in" event handlers, you would not
573 know this (it would depend on the order in which handlers are run,
574 one "in" handler sets the field value).
575
576 Note that "out" event handlers are executed before Scene is notified
577 about the field value change (before TCastleSceneCore.InternalChangedField is called).
578 This is also usually exactly what you want --- you can change the scene
579 graph inside the event handler (for example, load something on
580 Inline.load or Inline.url changes), and let the TX3DField.ChangeAlways
581 cause appropriate action on this change. }
582 procedure AddNotification(const Notification: TX3DEventReceive);
583 procedure RemoveNotification(const Notification: TX3DEventReceive);
584
585 { @exclude Internal routine, needed by animation blending. }
586 procedure InternalAffectedPartial;
587 { @exclude Internal routine, needed by animation blending. }
588 procedure InternalRemovePartial;
589 { @exclude Internal property, needed by animation blending. }
590 property InternalPartialSend: TPartialSend {$ifdef FPC} read FPartialSend
591 write FPartialSend {$else} read GetInternalPartialSend write SetInternalPartialSend {$endif};
592 { @exclude Internal property, needed by animation code.
593 Saves the current field value,
594 to be used as "value when this field is not animated". }
595 procedure InternalSaveResetValue;
596 { @exclude Internal property, needed by animation code.
597 Restore the field value last saved by InternalSaveResetValue.
598 Call it only if you previously called InternalSaveResetValue on this instance. }
599 procedure InternalRestoreSaveValue;
600 end;
601
602 TX3DFieldList = class({$ifdef FPC}specialize{$endif} TObjectList<TX3DField>)
603 strict private
604 function GetByName(const AName: String): TX3DField;
605 public
606 { Access field by name.
607 Raises EX3DNotFound if the given Name doesn't exist. }
608 property ByName[const AName: String]: TX3DField read GetByName;
609
610 { Searches for a field with given Name, returns it's index or -1 if not found. }
611 function IndexOfName(const AName: String): integer;
612
613 { Returns if EventName is an event implicitly exposed by one of our
614 exposed fields (i.e. set_xxx or xxx_changed). If yes, then
615 returns index of event, and the event reference itself
616 (so always @code(Fields[ReturnedIndex].ExposedEvent[ReturnedEvent.InEvent]
617 = ReturnedEvent)). Otherwise, returns -1. }
618 function IndexOfExposedEvent(const EventName: String;
619 out Event: TX3DEvent): Integer;
620 end;
621
622 {$endif read_interface}
623
624 {$ifdef read_implementation}
625
626 { TPartialSend --------------------------------------------------------------- }
627
628 constructor TPartialSend.Create;
629 begin
630 AffectedFields := TX3DFieldList.Create(false);
631 inherited;
632 end;
633
634 destructor TPartialSend.Destroy;
635 begin
636 FreeAndNil(AffectedFields);
637 inherited;
638 end;
639
640 { TX3DField.TPartialReceived --------------------------------------------------------------- }
641
642 function TX3DField.TPartialReceived.ToBeApplied: boolean;
643 begin
644 Result := PartialValue <> nil;
645 end;
646
647 destructor TX3DField.TPartialReceived.Destroy;
648 begin
649 FreeAndNil(PartialValue);
650 inherited;
651 end;
652
653 { TX3DField ------------------------------------------------------------- }
654
655 constructor TX3DField.CreateUndefined(const AParentNode: TX3DFileItem;
656 const AExposed: boolean; const AName: String);
657 begin
658 inherited Create(AParentNode, AName);
659 FExposedEventsLinked := true;
660
661 { Set Exposed by the property, to force FExposedEvents initialization }
662 FExposed := false;
663 Exposed := AExposed;
664 end;
665
666 destructor TX3DField.Destroy;
667 begin
668 FreeAndNil(FExposedEvents[false]);
669 FreeAndNil(FExposedEvents[true]);
670 // FreeAndNil(FPartialSend); // do not free this, TCastleSceneCore frees it
671 FreeAndNil(PartialReceived);
672 FreeAndNil(FResetValue);
673 inherited;
674 end;
675
676 function TX3DField.GetExposedEvents(InEvent: boolean): TX3DEvent;
677 begin
678 Result := FExposedEvents[InEvent];
679 end;
680
681 function TX3DField.EventIn: TX3DEvent;
682 begin
683 Result := FExposedEvents[true];
684 end;
685
686 function TX3DField.EventOut: TX3DEvent;
687 begin
688 Result := FExposedEvents[false];
689 end;
690
691 function TX3DField.AbortAssignValue(const Source: TX3DField): Boolean;
692 begin
693 Result :=
694 (Source.InternalPartialSend <> nil) and
695 Source.InternalPartialSend.IgnoreIfCannotLerp and
696 (not CanAssignLerp);
697 end;
698
699 procedure TX3DField.ExposedEventReceive(const Event: TX3DEvent; const Value: TX3DField;
700 const Time: TX3DTime);
701 var
702 ValuePossiblyChanged: boolean;
703 begin
704 Assert(Exposed);
705 Assert(Event = FExposedEvents[true]);
706 Assert(Value is ExposedEventsFieldClass);
707
708 if Assigned(OnInputIgnore) and OnInputIgnore(Self, Event, Value, Time) then
709 Exit;
710
711 if AbortAssignValue(Value) then
712 Exit;
713
714 { When not ValuePossiblyChanged, we don't have to call InternalChangedField.
715 (Although we still have to call FExposedEvents[false].Send,
716 to push the change through the routes.)
717 This may be an important optimization when simple field's change
718 causes large time-consuming work in InternalChangedField. }
719 ValuePossiblyChanged := not FastEqualsValue(Value);
720
721 { This is trivial handling of exposed events: just set our value,
722 and call out event. }
723
724 AssignValue(Value);
725
726 FExposedEvents[false].Send(Value, Time);
727
728 { Tests:
729 if not ValuePossiblyChanged then
730 writeln('ignored field ', Name, ' change, since values the same'); }
731 if ValuePossiblyChanged and
732 // do not send Changed if it will be send later by InternalAffectedPartial
733 not ((PartialReceived <> nil) and PartialReceived.ToBeApplied) then
734 Changed;
735 end;
736
737 procedure TX3DField.Changed;
738 var
739 Parent: TX3DNode;
740 begin
741 if ParentNode <> nil then
742 begin
743 Parent := ParentNode as TX3DNode;
744 if Parent.Scene <> nil then
745 Parent.Scene.InternalChangedField(Self);
746 end;
747 end;
748
749 function TX3DField.ExecuteChange: TX3DChange;
750 begin
751 Result := ChangeAlways;
752 end;
753
754 function TX3DField.SendsByEvent: boolean;
755 begin
756 Result :=
757 Exposed and
758 (ParentNode <> nil) and
759 ((ParentNode as TX3DNode).Scene <> nil);
760 end;
761
762 procedure TX3DField.Send(Value: TX3DField);
763 var
764 ValuePossiblyChanged: boolean;
765 begin
766 if SendsByEvent then
767 begin
768 EventIn.Send(Value, TX3DNode(ParentNode).Scene.NextEventTime);
769 end else
770 begin
771 if AbortAssignValue(Value) then Exit;
772
773 ValuePossiblyChanged := not FastEqualsValue(Value);
774 { Call AssignValue regardless of ValuePossiblyChanged.
775 Reason: AssignValue also removes "IS" clause.
776 Also it applies partial result info (in case of animation blending). }
777 AssignValue(Value);
778 if ValuePossiblyChanged then Changed;
779 end;
780 end;
781
782 const
783 SetPrefix = 'set_';
784 ChangedSuffix = '_changed';
785
786 procedure TX3DField.SetExposedEventsLinked(const Value: boolean);
787 begin
788 if FExposedEventsLinked <> Value then
789 begin
790 FExposedEventsLinked := Value;
791 if Exposed then
792 begin
793 if ExposedEventsLinked then
794 FExposedEvents[true].AddNotification(
795 {$ifdef FPC}@{$endif} ExposedEventReceive)
796 else
797 FExposedEvents[true].RemoveNotification(
798 {$ifdef FPC}@{$endif} ExposedEventReceive);
799 end;
800 end;
801 end;
802
803 class function TX3DField.ExposedEventsFieldClass: TX3DFieldClass;
804 begin
805 Result := {$ifdef FPC} TX3DFieldClass(ClassType) {$else} Self {$endif};
806 end;
807
808 class function TX3DField.CreateEvent(const AParentNode: TX3DFileItem; const AName: String; const AInEvent: boolean): TX3DEvent;
809 begin
810 Result := TX3DEvent.Create(AParentNode, AName, ExposedEventsFieldClass, AInEvent);
811 end;
812
813 procedure TX3DField.SetExposed(Value: boolean);
814 var
815 I: Integer;
816 begin
817 if Value <> Exposed then
818 begin
819 FExposed := Value;
820 if Exposed then
821 begin
822 FExposedEvents[false] := CreateEvent(ParentNode, X3DName + ChangedSuffix, false);
823 FExposedEvents[false].ParentExposedField := Self;
824 FExposedEvents[true] := CreateEvent(ParentNode, SetPrefix + X3DName, true);
825 FExposedEvents[true].ParentExposedField := Self;
826
827 for I := Low(FAlternativeNames) to High(FAlternativeNames) do
828 if FAlternativeNames[I] <> '' then
829 begin
830 FExposedEvents[false].AddAlternativeName(
831 FAlternativeNames[I] + ChangedSuffix, I);
832 FExposedEvents[true].AddAlternativeName(
833 SetPrefix + FAlternativeNames[I], I);
834 end;
835
836 if ExposedEventsLinked then
837 FExposedEvents[true].AddNotification(
838 {$ifdef FPC}@{$endif} ExposedEventReceive);
839 end else
840 begin
841 if ExposedEventsLinked then
842 FExposedEvents[true].RemoveNotification(
843 {$ifdef FPC}@{$endif} ExposedEventReceive);
844
845 FreeAndNil(FExposedEvents[false]);
846 FreeAndNil(FExposedEvents[true]);
847 end;
848 end;
849 end;
850
851 procedure TX3DField.FieldSaveToStream(Writer: TX3DWriter;
852 FieldSaveWhenDefault, XmlAvoidSavingNameBeforeValue: boolean);
853 var
854 N: String;
855 begin
856 N := NameForVersion(Writer);
857
858 if (not ValueFromIsClause) and
859 (FieldSaveWhenDefault or (not EqualsDefaultValue)) then
860 case Writer.Encoding of
861 xeClassic:
862 begin
863 if N <> '' then
864 Writer.WriteIndent(N + ' ');
865 SaveToStreamValue(Writer);
866 Writer.Writeln;
867 end;
868 xeXML:
869 { for xml encoding, field must be named, unless explicitly not wanted by XmlAvoidSavingNameBeforeValue }
870 if (N <> '') or XmlAvoidSavingNameBeforeValue then
871 begin
872 if (SaveToXml in [sxAttribute, sxAttributeCustomQuotes]) and
873 (not XmlAvoidSavingNameBeforeValue) then
874 begin
875 Writer.Writeln;
876 Writer.WriteIndent(N + '=');
877 end;
878 if SaveToXml = sxAttribute then
879 Writer.Write('"');
880 SaveToStreamValue(Writer);
881 if SaveToXml = sxAttribute then
882 Writer.Write('"');
883 end;
884 {$ifndef COMPILER_CASE_ANALYSIS}
885 else raise EInternalError.Create('TX3DField.FieldSaveToStream Encoding?');
886 {$endif}
887 end;
888 end;
889
890 procedure TX3DField.SaveToStream(Writer: TX3DWriter);
891 begin
892 FieldSaveToStream(Writer);
893 end;
894
895 function TX3DField.SaveToXmlValue: TSaveToXmlMethod;
896 begin
897 Result := sxAttribute;
898 end;
899
900 function TX3DField.SaveToXml: TSaveToXmlMethod;
901 begin
902 { Detect sxNone for XML encoding, this allows better output in many cases,
903 also avoids <fieldValue> inside <ProtoInstance> when the field value actually
904 doesn't have to be specified.
905 When FieldSaveToStream saves field value? FieldSaveToStream checks
906
907 (not ValueFromIsClause) and
908 (FieldSaveWhenDefault or (not EqualsDefaultValue))
909
910 SaveToStream calls FieldSaveToStream with default FieldSaveWhenDefault = false. }
911
912 if (not ValueFromIsClause) and (not EqualsDefaultValue) then
913 Result := SaveToXmlValue else
914 Result := sxNone;
915 end;
916
917 function TX3DField.EqualsDefaultValue: boolean;
918 begin
919 Result := false;
920 end;
921
922 function TX3DField.Equals(SecondValue: TX3DField): boolean;
923 begin
924 Result := SecondValue.X3DName = X3DName;
925 end;
926
927 function TX3DField.FastEqualsValue(SecondValue: TX3DField): boolean;
928 begin
929 Result := false;
930 end;
931
932 procedure TX3DField.Parse(Lexer: TX3DLexer; Reader: TX3DReader; IsClauseAllowed: boolean);
933 begin
934 if IsClauseAllowed and Lexer.TokenIsKeyword(vkIS) then
935 ParseIsClause(Lexer) else
936 ParseValue(Lexer, Reader);
937 end;
938
939 procedure TX3DField.ParseXMLAttributeLexer(Lexer: TX3DLexer; Reader: TX3DReader);
940 begin
941 ParseValue(Lexer, Reader);
942 end;
943
944 procedure TX3DField.ParseXMLAttribute(const AttributeValue: String; Reader: TX3DReader);
945 var
946 Lexer: TX3DLexer;
947 begin
948 Lexer := TX3DLexer.CreateForPartialStream(AttributeValue, Reader.Version);
949 try
950 try
951 ParseXMLAttributeLexer(Lexer, Reader);
952 except
953 on E: EX3DClassicReadError do
954 WritelnWarning('VRML/X3D', 'Error when reading field "' + X3DName + '" value: ' + E.Message);
955 end;
956 finally FreeAndNil(Lexer) end;
957 end;
958
959 procedure TX3DField.ParseXMLElement(Element: TDOMElement; Reader: TX3DReader);
960 var
961 I: TXMLElementIterator;
962 begin
963 I := Element.ChildrenIterator;
964 try
965 if I.GetNext then
966 WritelnWarning('VRML/X3D', FormatDot('X3D field "%s" is not SFNode or MFNode, but a node value (XML element "%s") is specified',
967 [X3DName, I.Current.TagName]));
968 finally FreeAndNil(I) end;
969 end;
970
971 procedure TX3DField.VRMLFieldAssignCommon(Source: TX3DField);
972 var
973 NameChanges, ExposedChanges: boolean;
974 I: Integer;
975 begin
976 NameChanges := X3DName <> Source.X3DName;
977 ExposedChanges := Exposed <> Source.Exposed;
978
979 FieldOrEventAssignCommon(Source);
980
981 ValueFromIsClause := Source.ValueFromIsClause;
982
983 Exposed := Source.Exposed;
984 Assert(Exposed = (ExposedEvents[false] <> nil));
985 Assert(Exposed = (ExposedEvents[true] <> nil));
986
987 { This is a little tricky: we copied Exposed value by SetExposed,
988 to actually create or destroy exposed events.
989
990 But note that events in
991 ExposedEvents have names dependent on our name. So we have to eventually
992 change their names too. This is not needed if exposed
993 changes from true->false (then events will be destroyed),
994 changes from false->true (then events will be created with already new names),
995 stays as false->false (then events don't exist).
996 So it's needed only when exposed was true, and stays true, but name changed.
997 }
998 if NameChanges and Exposed and (not ExposedChanges) then
999 begin
1000 FExposedEvents[false].FX3DName := X3DName + ChangedSuffix;
1001 FExposedEvents[true].FX3DName := SetPrefix + X3DName;
1002 end;
1003
1004 Assert((not Exposed) or (FExposedEvents[false].FX3DName = X3DName + ChangedSuffix));
1005 Assert((not Exposed) or (FExposedEvents[true].FX3DName = SetPrefix + X3DName));
1006
1007 { Once again an issue with dependency of ExposedEvents on our name:
1008 potentially alternative names changed,
1009 so we have to redo this in exposed events. }
1010 if Exposed then
1011 begin
1012 for I := Low(FAlternativeNames) to High(FAlternativeNames) do
1013 if FAlternativeNames[I] <> '' then
1014 begin
1015 FExposedEvents[false].AddAlternativeName(FAlternativeNames[I] + ChangedSuffix, I);
1016 FExposedEvents[true].AddAlternativeName(SetPrefix + FAlternativeNames[I], I);
1017 end else
1018 begin
1019 FExposedEvents[false].RemoveAlternativeName(I);
1020 FExposedEvents[true].RemoveAlternativeName(I);
1021 end;
1022 end;
1023 end;
1024
1025 procedure TX3DField.AssignValueRaiseInvalidClass(Source: TX3DField);
1026 begin
1027 raise EX3DFieldAssignInvalidClass.CreateFmt('Cannot assign VRML/X3D field ' +
1028 '%s (%s) from %s (%s)',
1029 [ X3DName, X3DType,
1030 Source.X3DName, Source.X3DType]);
1031 end;
1032
1033 procedure TX3DField.AssignValue(Source: TX3DField);
1034
1035 procedure UpdatePartialReceived(const PartialSend: TPartialSend);
1036 begin
1037 if PartialReceived = nil then
1038 begin
1039 PartialReceived := TPartialReceived.Create;
1040 if FResetValue = nil then
1041 begin
1042 WritelnWarning('Initializing field "%s" reset value when the animation starts. It is more reliable to set TimeSensor.detectAffectedFields to TRUE to have animation blending (cross-fading) working perfectly.', [NiceName]);
1043 { The reason why this is not advised:
1044 - The 1st frame of new animation is possibly already applied when this is called.
1045 That's because TCastleSceneCore may call HandleChangeTimeStopStart
1046 (cause by TTimeSensorNode.Start) before this is called (from Update, between
1047 PartialSendBegin and PartialSendEnd).
1048 - Also it's not optimal, since we do it in the middle of the game, instead of at loading.
1049 }
1050 InternalSaveResetValue;
1051 end;
1052 end;
1053
1054 { update PartialReceived.PartialValue, by lerp with weights
1055 PartialReceived.Partial, PartialSend.Partial
1056 between these two values:
1057 PartialReceived.PartialValue, new Source value. }
1058 if PartialReceived.PartialValue = nil then
1059 begin
1060 PartialReceived.PartialValue := TX3DFieldClass(ClassType).CreateUndefined(nil, false, '');
1061 { For the first assignment, it's faster to use AssignValue than AssignLerp.
1062 Also, AssignLerp expects MF fields to have correct counts. }
1063 PartialReceived.PartialValue.AssignValue(Source);
1064 end else
1065 begin
1066 PartialReceived.PartialValue.AssignLerp(
1067 1 - PartialReceived.Partial / (PartialReceived.Partial + PartialSend.Partial),
1068 PartialReceived.PartialValue, Source);
1069 end;
1070 Assert(PartialReceived.ToBeApplied); // we have initialized PartialReceived.PartialValue
1071 PartialReceived.Partial := PartialReceived.Partial + PartialSend.Partial;
1072 // note that we can add duplicates to PartialSend.AffectedFields, that's OK
1073 PartialSend.AffectedFields.Add(Self);
1074 end;
1075
1076 begin
1077 ValueFromIsClause := false;
1078
1079 if (Source.InternalPartialSend <> nil) and
1080 (FPartialSendIgnore = 0) and
1081 CanAssignLerp then
1082 begin
1083 { using FPartialSendIgnore, to ignore Source.InternalPartialSend
1084 in recursive AssignValue inside UpdatePartialReceived. }
1085 Inc(FPartialSendIgnore);
1086 UpdatePartialReceived(Source.InternalPartialSend);
1087 Dec(FPartialSendIgnore);
1088 end;
1089
1090 { fade-in/out overridden by another animation that is not fading-in/out }
1091 if (PartialReceived <> nil) and (Source.InternalPartialSend = nil) then
1092 FreeAndNil(PartialReceived);
1093 end;
1094
1095 procedure TX3DField.InternalAffectedPartial;
1096 begin
1097 { About PartialReceived <> nil: usually PartialReceived <> nil now,
1098 but in some corner-cases it may be nil: if it was freed by
1099 "fade-in/out overridden by another animation that is not fading-in/out".. }
1100
1101 if (PartialReceived <> nil) and PartialReceived.ToBeApplied then
1102 begin
1103 if PartialReceived.Partial > 1.01 then
1104 WritelnWarning('During animation blending, the partials sum in > 1: %f on field %s', [
1105 PartialReceived.Partial,
1106 NiceName
1107 ]);
1108 Assert(FResetValue <> nil);
1109 AssignLerp(PartialReceived.Partial, FResetValue, PartialReceived.PartialValue);
1110 PartialReceived.Partial := 0;
1111 FreeAndNil(PartialReceived.PartialValue);
1112 Assert(not PartialReceived.ToBeApplied); // we have destroyed PartialReceived.PartialValue
1113
1114 Changed;
1115 end;
1116 end;
1117
1118 procedure TX3DField.InternalRemovePartial;
1119 begin
1120 { Field is no longer affected by faded-in/out animation.
1121 Next time it *will* become affected,
1122 PartialReceived will be initialized again. }
1123 FreeAndNil(PartialReceived);
1124 end;
1125
1126 procedure TX3DField.InternalSaveResetValue;
1127 begin
1128 FreeAndNil(FResetValue);
1129
1130 FResetValue := TX3DFieldClass(ClassType).CreateUndefined(nil, false, '');
1131 FResetValue.AssignValue(Self);
1132 end;
1133
1134 procedure TX3DField.InternalRestoreSaveValue;
1135 begin
1136 Assert(FResetValue <> nil);
1137 // TODO: maybe this should be Send(FResetValue);
1138 AssignValue(FResetValue);
1139 Changed;
1140 end;
1141
1142 procedure TX3DField.AssignDefaultValueFromValue;
1143 begin
1144 { do nothing in this class }
1145 end;
1146
1147 procedure TX3DField.UnassignDefaultValue;
1148 begin
1149 { do nothing in this class }
1150 end;
1151
1152 procedure TX3DField.AssignLerp(const A: Double; Value1, Value2: TX3DField);
1153 begin
1154 { do nothing, CanAssignLerp is false }
1155 end;
1156
1157 function TX3DField.CanAssignLerp: boolean;
1158 begin
1159 Result := false;
1160 end;
1161
1162 procedure TX3DField.AddAlternativeName(const AlternativeName: String;
1163 const X3DMajorVersion: Integer);
1164 begin
1165 inherited;
1166
1167 if Exposed then
1168 begin
1169 Assert(FExposedEvents[false] <> nil);
1170 Assert(FExposedEvents[true] <> nil);
1171
1172 FExposedEvents[false].AddAlternativeName(
1173 AlternativeName + ChangedSuffix, X3DMajorVersion);
1174 FExposedEvents[true].AddAlternativeName(
1175 SetPrefix + AlternativeName, X3DMajorVersion);
1176 end;
1177 end;
1178
1179 { Note that TX3DField.X3DType cannot be abstract:
1180 it may be used if source event is of XFAny type in warning message
1181 in TX3DRoute.SetEndingInternal }
1182 class function TX3DField.X3DType: String;
1183 begin
1184 Result := 'XFAny';
1185 end;
1186
1187 class function TX3DField.TypeName: String;
1188 begin
1189 Result := X3DType;
1190 end;
1191
1192 procedure TX3DField.AddNotification(const Notification: TX3DEventReceive);
1193 begin
1194 Assert(Exposed, 'Use TX3DField.AddNotification only on Exposed fields');
1195 FExposedEvents[false].AddNotification(Notification);
1196 end;
1197
1198 procedure TX3DField.RemoveNotification(const Notification: TX3DEventReceive);
1199 begin
1200 Assert(Exposed, 'Use TX3DField.RemoveNotification only on Exposed fields');
1201 FExposedEvents[false].RemoveNotification(Notification);
1202 end;
1203
1204 {$ifndef FPC}
1205 function TX3DField.GetInternalPartialSend: TPartialSend;
1206 begin
1207 Result := FPartialSend;
1208 end;
1209
1210 procedure TX3DField.SetInternalPartialSend(const Value: TPartialSend);
1211 begin
1212 FPartialSend := Value;
1213 end;
1214 {$endif}
1215
1216 { TX3DFieldList ------------------------------------------------------------- }
1217
1218 function TX3DFieldList.IndexOfName(const AName: String): integer;
1219 begin
1220 for Result := 0 to Count-1 do
1221 if Items[Result].IsName(AName) then
1222 Exit;
1223 Result := -1;
1224 end;
1225
1226 function TX3DFieldList.GetByName(const AName: String): TX3DField;
1227 var
1228 I: integer;
1229 begin
1230 I := IndexOfName(AName);
1231 if I <> -1 then
1232 Result := Items[I] else
1233 raise EX3DNotFound.CreateFmt('Field name "%s" not found', [AName]);
1234 end;
1235
1236 function TX3DFieldList.IndexOfExposedEvent(const EventName: String;
1237 out Event: TX3DEvent): Integer;
1238 var
1239 InEvent: boolean;
1240 begin
1241 { This implementation is quite optimized.
1242 Instead of browsing all fields and their ExposedEvents,
1243 looking for EventName event, instead we examine EventName
1244 to look whether this has any chance of being set_xxx or xxx_changed
1245 event. So we utilize the fact that exposed events have consistent
1246 naming. }
1247
1248 if IsPrefix(SetPrefix, EventName, false) then
1249 begin
1250 InEvent := true;
1251 Result := IndexOfName(SEnding(EventName, Length(SetPrefix) + 1));
1252 end else
1253 if IsSuffix(ChangedSuffix, EventName, false) then
1254 begin
1255 InEvent := false;
1256 Result := IndexOfName(Copy(EventName, 1,
1257 Length(EventName) - Length(ChangedSuffix)));
1258 end else
1259 begin
1260 Result := -1;
1261 InEvent := false; // unused, silence Delphi warning
1262 end;
1263
1264 { check is field really exposed now }
1265 if (Result <> -1) and (not Items[Result].Exposed) then
1266 begin
1267 Result := -1;
1268 end;
1269
1270 if Result <> -1 then
1271 begin
1272 Event := Items[Result].ExposedEvents[InEvent];
1273 end;
1274 end;
1275
1276 {$endif read_implementation}