Debian Codegraph @

src/scene/x3d/x3dnodes_x3dinterfacedeclaration.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
19 { Interface declaration, used in VRML/X3D (exposed) prototypes and
20 for nodes with dynamic fields (Script, ComposedShader).
21 See VRML 2.0 and X3D specs.
22
23 Each interface specification is a field or an event, stored
24 in FieldOrEvent. FieldOrEvent is @nil before parsing.
25
26 Field value is not initialized if you passed FieldValue = @false
27 to @link(Parse) (although IsClauseNames will
28 always be initialized). FieldValue = @true is used for prototype
29 (not external) declarations and nodes with interface declarations
30 (Script, ComposedShader etc.).
31 In the future maybe some property like
32 FieldValueInitialized will be exposed here, if needed at some point.
33
34 Interface declaration doesn't have much properties, since all
35 the information is contained within FieldOrEvent
36 instance, like Name, field class type, out or in (in case of event),
37 exposed or not (in case of field), IsClauseNames. }
38 TX3DInterfaceDeclaration = class(TX3DFileItem)
39 strict private
40 FParentNode: TX3DNode;
41 FFieldOrEvent: TX3DFieldOrEvent;
42
43 { kept in synch with FFieldOrEvent by SetFieldOrEvent }
44 FField: TX3DField;
45 FEvent: TX3DEvent;
46
47 procedure SetFieldOrEvent(const Value: TX3DFieldOrEvent);
48 private
49 { Create a copy of current FieldOrEvent.
50 Sets NewParentNode as Result.ParentNode.
51 Note the new copy will not have ParentIntefaceDeclaration set
52 (as the idea is that you own created copy, not this TX3DInterfaceDeclaration
53 instance).
54
55 If CopyState is non-nil, then any nodes referenced inside SFNode / MFNode
56 fields and events are copied using DeepCopy (not by simply copying references). }
57 function CopyFieldOrEvent(const NewParentNode: TX3DNode;
58 const CopyState: TX3DNodeDeepCopyState): TX3DFieldOrEvent;
59
60 { Create a copy of current FieldOrEvent, and add it to Node.Fields
61 or Node.Events. }
62 procedure CopyAndAddFieldOrEvent(const Node: TX3DNode);
63 public
64 constructor Create(AParentNode: TX3DNode);
65 destructor Destroy; override;
66
67 { Containing node, if any, for this VRML interface declaration.
68 This must also be set to FieldOrEvent.ParentNode created for this
69 interface declaration. }
70 property ParentNode: TX3DNode read FParentNode;
71
72 { Field or event of this interface declaration.
73 Is non-nil after parsing.
74
75 You can assign to this property, to constructs interface
76 declarations (and so also prototypes) in your own code
77 (e.g. this is used X3D XML reader). Just be careful, and remember
78 that this object owns FieldOrEvent (that is, will free it
79 at destruction). }
80 property FieldOrEvent: TX3DFieldOrEvent
81 read FFieldOrEvent write SetFieldOrEvent;
82
83 { Copies only reference to FieldOrEvent, adding it to Node.Fields
84 or Node.Events. }
85 procedure AddFieldOrEvent(Node: TX3DNode);
86
87 { Return FieldOrEvent casted as appropriate class.
88 @nil if such cast is not possible, for example when
89 FieldOrEvent is an event and you try to use Field method.
90 @groupBegin }
91 property Field: TX3DField read FField;
92 property Event: TX3DEvent read FEvent;
93 { @groupEnd }
94
95 procedure Parse(Lexer: TX3DLexer; Reader: TX3DReaderNames;
96 FieldValue, IsClauseAllowed: boolean);
97
98 { Parse interface declaration encoded in XML.
99
100 Note that classic VRML parser has here IsClauseAllowed: boolean
101 parameter, this was set to @true when parsing InterfaceDeclarations
102 of special nodes (Script, ComposedShader etc.), since they could
103 have IS clause (at least, as far as I understood the spec).
104 But for X3D XML encoding, it's not available, since (AFAI understand
105 the X3D XML encoding spec) the <IS> element inside node body may
106 point from nodeField to any interface field of this node, including
107 InterfaceDeclarations. So ParseISStatement handles this. }
108 procedure ParseXML(Element: TDOMElement; Reader: TX3DReaderNames;
109 FieldValue: boolean);
110
111 { Save this interface declaration to stream.
112 This assumes that it starts at the beginning of the line,
113 and at the end always writes NL, so at the end it's also
114 at the beginning of some line.
115
116 For XML encoding, IS clauses are not saved here.
117 They must be saved by containing node.
118
119 @param(FieldValue If @true then we will always save
120 Field value or (if classic encoding) IS clauses to stream,
121 along with this interface
122 declaration (if this interface declaration has the Field set).
123 Otherwise, field's value will not be saved, only IS clauses
124 if present.)
125 }
126 procedure IDeclSaveToStream(Writer: TX3DWriter; FieldValue: boolean);
127
128 { Save this interface declaration to stream.
129 @seealso IDeclSaveToStream }
130 procedure SaveToStream(Writer: TX3DWriter); override;
131
132 { Returns access type, corresponding to current @link(Event)
133 and @link(Field) values.
134
135 Result is undefined if both Event
136 and Field are @nil (which may happen when it's not initialized
137 (e.g. parsed) yet) or when both are non-nil (which should never
138 happen). }
139 function AccessType: TX3DAccessType;
140
141 function DeepCopy(const NewParentNode: TX3DNode;
142 const CopyState: TX3DNodeDeepCopyState): TX3DInterfaceDeclaration;
143 end;
144
145 TX3DInterfaceDeclarationList = class({$ifdef FPC}specialize{$endif}
146 TObjectList<TX3DInterfaceDeclaration>)
147 public
148 { Find field or event with given Name.
149 @nil if not found. }
150 function TryFindName(const Name: String): TX3DFieldOrEvent;
151
152 { Find field with given Name.
153 @nil if not found. }
154 function TryFindFieldName(const Name: String): TX3DField;
155
156 { Find event with given Name.
157 @nil if not found. }
158 function TryFindEventName(const Name: String): TX3DEvent;
159 end;
160
161 {$endif read_interface}
162
163 {$ifdef read_implementation}
164
165 { TX3DInterfaceDeclaration -------------------------------------------------- }
166
167 constructor TX3DInterfaceDeclaration.Create(AParentNode: TX3DNode);
168 begin
169 inherited Create;
170 FParentNode := AParentNode;
171 end;
172
173 destructor TX3DInterfaceDeclaration.Destroy;
174 begin
175 FreeAndNil(FFieldOrEvent);
176 FField := nil;
177 FEvent := nil;
178
179 inherited;
180 end;
181
182 procedure TX3DInterfaceDeclaration.SetFieldOrEvent(
183 const Value: TX3DFieldOrEvent);
184 begin
185 FFieldOrEvent := Value;
186
187 { set FField and FEvent, for fast access to them }
188 if FFieldOrEvent = nil then
189 begin
190 FField := nil;
191 FEvent := nil;
192 end else
193 if FFieldOrEvent is TX3DField then
194 begin
195 FField := TX3DField(FFieldOrEvent);
196 FEvent := nil;
197 end else
198 begin
199 Assert(FFieldOrEvent is TX3DEvent);
200 FField := nil;
201 FEvent := TX3DEvent(FFieldOrEvent);
202 end;
203 end;
204
205 procedure TX3DInterfaceDeclaration.Parse(Lexer: TX3DLexer; Reader: TX3DReaderNames;
206 FieldValue, IsClauseAllowed: boolean);
207 var
208 X3DType: String;
209 Access: TX3DAccessType;
210 FieldType: TX3DFieldClass;
211 ParsedName: String;
212 begin
213 { clear instance before parsing }
214 FieldOrEvent.Free;
215 FieldOrEvent := nil;
216
217 if Lexer.Token = vtKeyword then
218 begin
219 case Lexer.TokenKeyword of
220 vkEventIn, vkInputOnly: Access := atInputOnly;
221 vkEventOut, vkOutputOnly: Access := atOutputOnly;
222 vkField, vkInitializeOnly: Access := atInitializeOnly;
223 vkExposedField, vkInputOutput: Access := atInputOutput;
224 else raise EX3DParserError.Create(
225 Lexer, Format(SExpectedInterfaceDeclaration, [Lexer.DescribeToken]));
226 end;
227 end else
228 raise EX3DParserError.Create(
229 Lexer, Format(SExpectedInterfaceDeclaration, [Lexer.DescribeToken]));
230
231 Lexer.NextToken;
232 Lexer.CheckTokenIs(vtName, 'field type (for interface declaration)');
233 X3DType := Lexer.TokenName;
234 FieldType := X3DFieldsManager.X3DTypeToClass(X3DType);
235 if FieldType = nil then
236 raise EX3DParserError.Create(
237 Lexer, Format(SExpectedFieldType, [Lexer.DescribeToken]));
238
239 Lexer.NextToken;
240 Lexer.CheckTokenIs(vtName, 'name (for interface declaration)');
241 ParsedName := Lexer.TokenName;
242
243 { we know everything now to create Event/Field instance }
244 case Access of
245 atInputOnly, atOutputOnly:
246 FieldOrEvent := FieldType.CreateEvent(ParentNode, ParsedName, Access = atInputOnly);
247 atInitializeOnly, atInputOutput:
248 FieldOrEvent := FieldType.CreateUndefined(ParentNode, Access = atInputOutput, ParsedName);
249 {$ifndef COMPILER_CASE_ANALYSIS}
250 else raise EInternalError.Create('Access ? in TX3DInterfaceDeclaration.Parse');
251 {$endif}
252 end;
253
254 Lexer.NextToken;
255
256 if Event <> nil then
257 begin
258 if IsClauseAllowed then
259 Event.Parse(Lexer);
260 end else
261 begin
262 if FieldValue then
263 begin
264 if Field is TSFNode then
265 TSFNode(Field).AutomaticWeakLink := true;
266 Field.Parse(Lexer, Reader, IsClauseAllowed)
267 end else
268 if IsClauseAllowed then
269 Field.ParseIsClause(Lexer);
270 end;
271
272 FieldOrEvent.ParentInterfaceDeclaration := Self;
273 end;
274
275 procedure TX3DInterfaceDeclaration.ParseXML(
276 Element: TDOMElement; Reader: TX3DReaderNames; FieldValue: boolean);
277 var
278 Access: TX3DAccessType;
279 AccessIndex: Integer;
280 AccessName: String;
281 FieldX3DType: String;
282 FieldType: TX3DFieldClass;
283 ParsedName, FieldActualValue: String;
284 begin
285 { clear instance before parsing }
286 FieldOrEvent.Free;
287 FieldOrEvent := nil;
288
289 { calculate Access }
290 if Element.AttributeString('accessType', AccessName) then
291 begin
292 AccessIndex := ArrayPosStr(AccessName,
293 ['inputOnly', 'outputOnly', 'initializeOnly', 'inputOutput']);
294 if AccessIndex <> -1 then
295 Access := TX3DAccessType(AccessIndex) else
296 raise EX3DXmlError.CreateFmt('Access type "%s" unknown', [AccessName]);
297 end else
298 raise EX3DXmlError.Create('Missing access type in X3D interface declaration');
299
300 { calculate FieldType }
301 if Element.AttributeString('type', FieldX3DType) then
302 begin
303 FieldType := X3DFieldsManager.X3DTypeToClass(FieldX3DType);
304 if FieldType = nil then
305 raise EX3DXmlError.CreateFmt('Field type "%s" unknown', [FieldX3DType]);
306 end else
307 raise EX3DXmlError.Create('Missing field type in X3D interface declaration');
308
309 if not Element.AttributeString('name', ParsedName) then
310 raise EX3DXmlError.Create('Missing name in X3D interface declaration');
311
312 { we know everything now to create Event/Field instance }
313 case Access of
314 atInputOnly, atOutputOnly:
315 FieldOrEvent := FieldType.CreateEvent(ParentNode, ParsedName, Access = atInputOnly);
316 atInitializeOnly, atInputOutput:
317 FieldOrEvent := FieldType.CreateUndefined(ParentNode, Access = atInputOutput, ParsedName);
318 {$ifndef COMPILER_CASE_ANALYSIS}
319 else raise EInternalError.Create('AccessType ?');
320 {$endif}
321 end;
322
323 if Event <> nil then
324 begin
325 { Classic VRML parser has here
326 if IsClauseAllowed then Event.Parse(Lexer);
327 but for X3D XML encoding this is not needed, see comments above. }
328 end else
329 begin
330 if FieldValue then
331 begin
332 if Field is TSFNode then
333 TSFNode(Field).AutomaticWeakLink := true;
334
335 if Element.AttributeString('value', FieldActualValue) then
336 Field.ParseXMLAttribute(FieldActualValue, Reader)
337 else
338 Field.ParseXMLElement(Element, Reader);
339 end;
340
341 { Classic VRML parser has here
342 else if IsClauseAllowed then Field.ParseIsClause(Lexer);
343 but for X3D XML encoding this is not needed, see comments above. }
344 end;
345
346 FieldOrEvent.ParentInterfaceDeclaration := Self;
347 end;
348
349 function TX3DInterfaceDeclaration.CopyFieldOrEvent(
350 const NewParentNode: TX3DNode;
351 const CopyState: TX3DNodeDeepCopyState): TX3DFieldOrEvent;
352 var
353 F: TX3DField absolute Result;
354 E: TX3DEvent absolute Result;
355 begin
356 if Field <> nil then
357 begin
358 { F := copy of Field }
359 F := TX3DFieldClass(Field.ClassType).CreateUndefined(NewParentNode,
360 Field.Exposed, Field.X3DName);
361
362 if CopyState <> nil then
363 F.InternalAssignDeepCopy(Field, CopyState)
364 else
365 F.Assign(Field);
366
367 { CreateUndefined creates field without any default value,
368 so it will always get saved later to file.
369
370 But this is not nice: for non-node fields, it merely makes
371 resulting file longer. For node fields (SFNode and MFNode)
372 this means that node value will be written to file. But this
373 is bad, since this means that node contents will have to duplicated,
374 if node is not named or it's name is unbound now (e.g. overridden
375 by other node name) (otherwise "USE Xxx" could be used, which
376 is acceptable).
377
378 See
379 ../../../../demo-models/prototypes/proto_sfnode_default.x3dv
380 ../../../../demo-models/x3d/tricky_def_use.x3dv
381 for examples (open and save them back e.g. in castle-model-viewer).
382
383 So to make it work right, we have to set DefaultValue for our
384 fields, in particular for TSFNode and TMFNode fields.
385 So that EqualsDefaultValue will work Ok when saving to file. }
386 F.AssignDefaultValueFromValue;
387 end else
388 if Event <> nil then
389 begin
390 { E := copy of Event }
391 E := Event.FieldClass.CreateEvent(NewParentNode, Event.X3DName, Event.InEvent);
392 { Although above constructor already copied most event properties,
393 some were omitted (like IsClauseNames --- important for Script with
394 eventIn/out events with IS clauses inside prototypes).
395 Assign call below takes care of them. }
396 if CopyState <> nil then
397 E.InternalAssignDeepCopy(Event, CopyState) // note: for events actually now InternalAssignDeepCopy = Assign
398 else
399 E.Assign(Event);
400 end else
401 raise EInternalError.Create('interface declaration but no Field or Event');
402
403 Result.ParentInterfaceDeclaration := nil;
404 end;
405
406 procedure TX3DInterfaceDeclaration.AddFieldOrEvent(
407 Node: TX3DNode);
408 begin
409 if Field <> nil then
410 Node.AddField(Field) else
411 begin
412 Assert(Event <> nil);
413 Node.AddEvent(Event);
414 end;
415 end;
416
417 procedure TX3DInterfaceDeclaration.CopyAndAddFieldOrEvent(
418 const Node: TX3DNode);
419 var
420 Copy: TX3DFieldOrEvent;
421 begin
422 Copy := CopyFieldOrEvent(Node, nil);
423 if Copy is TX3DField then
424 Node.AddField(TX3DField(Copy)) else
425 begin
426 Assert(Copy is TX3DEvent);
427 Node.AddEvent(TX3DEvent(Copy));
428 end;
429 end;
430
431 procedure TX3DInterfaceDeclaration.IDeclSaveToStream(
432 Writer: TX3DWriter; FieldValue: boolean);
433
434 function ATName(const AccessType: TX3DAccessType): String;
435 const
436 Names: array
437 [ boolean { is it X3D or XML encoding ? },
438 TX3DAccessType] of string =
439 ( ('eventIn', 'eventOut', 'field', 'exposedField'),
440 ('inputOnly', 'outputOnly', 'initializeOnly', 'inputOutput') );
441 begin
442 Result := Names[(Writer.Encoding = xeXML) or (Writer.Version.Major >= 3),
443 AccessType];
444 end;
445
446 var
447 N: String;
448 begin
449 N := FieldOrEvent.NameForVersion(Writer.Version);
450
451 case Writer.Encoding of
452 xeClassic:
453 if Event <> nil then
454 begin
455 if Event.InEvent then
456 Writer.WriteIndent(ATName(atInputOnly) + ' ') else
457 Writer.WriteIndent(ATName(atOutputOnly) + ' ');
458 Writer.Write(Event.FieldClass.X3DType + ' ');
459 if Event.IsClauseNamesCount <> 0 then
460 begin
461 Writer.DiscardNextIndent;
462 { Note that there may be many IS clauses. This will still work Ok:
463 first IS clause will "belong" to this interface declaration,
464 the rest will look like normal IS clauses. }
465 Event.SaveToStreamClassicIsClauses(Writer);
466 end else
467 Writer.Writeln(N);
468 end else
469 begin
470 if Field.Exposed then
471 Writer.WriteIndent(ATName(atInputOutput) + ' ') else
472 Writer.WriteIndent(ATName(atInitializeOnly) + ' ');
473 Writer.Write(Field.X3DType + ' ');
474
475 { When saving from interface declaration, you can only
476 1. write sole field name
477 2. write field name + value (if FieldValue = @true)
478 3. write field name + IS clause (only one allowed) }
479
480 if ( FieldValue and
481 (not Field.ValueFromIsClause) and
482 (Field.IsClauseNamesCount = 0) ) then
483 begin
484 { Field.SaveToStream normally starts from new line with an indent...
485 In this case, we want it to start on the same line, so indent must
486 be discarded. }
487 Writer.DiscardNextIndent;
488 Field.FieldSaveToStream(Writer, true);
489 { In this case, Writer.Writeln will be done by Field.SaveToStream.
490 (we pass SaveWhenDefault anyway, so we can be sure that
491 this newline will be done). }
492 end else
493
494 if Field.IsClauseNamesCount <> 0 then
495 begin
496 Writer.DiscardNextIndent;
497 { Note that there may be many IS clauses. This will still work Ok:
498 first IS clause will "belong" to this interface declaration,
499 the rest will look like normal IS clauses. }
500 Field.SaveToStreamClassicIsClauses(Writer);
501 end else
502
503 begin
504 Writer.Writeln(N);
505 end;
506 end;
507 xeXML:
508 { We don't save IS clauses here for XML encoding. They must be saved
509 inside containing TX3DNode. }
510 if Event <> nil then
511 begin
512 Writer.WritelnIndent(Format('<field accessType=%s type=%s name=%s />',
513 [ Iff(Event.InEvent,
514 StringToX3DXml(ATName(atInputOnly)),
515 StringToX3DXml(ATName(atOutputOnly))),
516 StringToX3DXml(Event.FieldClass.X3DType),
517 StringToX3DXml(N) ]));
518 end else
519 begin
520 Writer.WriteIndent(Format('<field accessType=%s type=%s name=%s',
521 [ Iff(Field.Exposed,
522 StringToX3DXml(ATName(atInputOutput)),
523 StringToX3DXml(ATName(atInitializeOnly))),
524 StringToX3DXml(Field.X3DType),
525 StringToX3DXml(N) ]));
526
527 if ( FieldValue and
528 (not Field.ValueFromIsClause) and
529 (Field.IsClauseNamesCount = 0) ) then
530 begin
531 if Field.SaveToXml in [sxAttribute, sxAttributeCustomQuotes] then
532 begin
533 Writer.Write(' value=');
534 Field.FieldSaveToStream(Writer, true, true);
535 Writer.Writeln(' />');
536 end else
537 begin
538 Writer.Writeln('>');
539 { Parameter XmlAvoidSavingNameBeforeValue doesn't matter here }
540 Field.FieldSaveToStream(Writer, true);
541 Writer.WritelnIndent('</field>');
542 end;
543 end else
544 { no field value, no IS clauses.
545 This can happen for field/event declaration inside <ExternProto>.
546 Just close <field> element. }
547 Writer.Writeln(' />');
548 end;
549
550 {$ifndef COMPILER_CASE_ANALYSIS}
551 else raise EInternalError.Create('TX3DInterfaceDeclaration.IDeclSaveToStream Encoding?');
552 {$endif}
553 end;
554 end;
555
556 procedure TX3DInterfaceDeclaration.SaveToStream(Writer: TX3DWriter);
557 begin
558 IDeclSaveToStream(Writer, true);
559 end;
560
561 function TX3DInterfaceDeclaration.AccessType: TX3DAccessType;
562 begin
563 if Event <> nil then
564 begin
565 if Event.InEvent then
566 Result := atInputOnly else
567 Result := atOutputOnly;
568 end else
569 if Field <> nil then
570 begin
571 if Field.Exposed then
572 Result := atInputOutput else
573 Result := atInitializeOnly;
574 end else
575 { Result is undefined in this case, but we don't want to signal any error }
576 Result := atInitializeOnly
577 end;
578
579 function TX3DInterfaceDeclaration.DeepCopy(
580 const NewParentNode: TX3DNode;
581 const CopyState: TX3DNodeDeepCopyState): TX3DInterfaceDeclaration;
582 begin
583 Result := TX3DInterfaceDeclaration.Create(NewParentNode);
584 Result.FieldOrEvent := CopyFieldOrEvent(NewParentNode, CopyState);
585 Result.FieldOrEvent.ParentInterfaceDeclaration := Result;
586 end;
587
588 { TX3DInterfaceDeclarationList --------------------------------------------- }
589
590 function TX3DInterfaceDeclarationList.TryFindName(
591 const Name: String): TX3DFieldOrEvent;
592 var
593 I: Integer;
594 begin
595 for I := 0 to Count - 1 do
596 begin
597 Result := Items[I].FieldOrEvent;
598 if Result.X3DName = Name then
599 Exit;
600 end;
601 Result := nil;
602 end;
603
604 function TX3DInterfaceDeclarationList.TryFindFieldName(const Name: String): TX3DField;
605 var
606 I: Integer;
607 begin
608 for I := 0 to Count - 1 do
609 if Items[I].FieldOrEvent is TX3DField then
610 begin
611 Result := Items[I].Field;
612 if Result.X3DName = Name then
613 Exit;
614 end;
615 Result := nil;
616 end;
617
618 function TX3DInterfaceDeclarationList.TryFindEventName(const Name: String): TX3DEvent;
619 var
620 I: Integer;
621 begin
622 for I := 0 to Count - 1 do
623 if Items[I].FieldOrEvent is TX3DEvent then
624 begin
625 Result := Items[I].Event;
626 if Result.X3DName = Name then
627 Exit;
628 end;
629 Result := nil;
630 end;
631
632 {$endif read_implementation}