Debian Codegraph @

src/scene/x3d/x3dnodes_encoding_classic.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2002-2023 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 { Global routines for parsing classic VRML/X3D encoding. }
18
19 {$ifdef read_interface}
20
21 const
22 { File filters if you want to open a file and then
23 pass it to LoadX3DClassic.
24 Suitable for TCastleWindow.FileDialog and such. }
25 LoadX3DClassic_FileFilters =
26 'All files|*|' +
27 '*VRML (*.wrl, *.wrl.gz, *.wrz)|*.wrl;*.wrl.gz;*.wrz'
28 deprecated 'use LoadNode and LoadScene_FileFilters';
29
30 type
31 { Raised by classic X3D loading routines when the stream is compressed with gzip. }
32 EGzipCompressed = CastleInternalX3DLexer.EGzipCompressed;
33
34 { Load VRML/X3D file in classic encoding from a string. Return it's root node.
35 @raises(EGzipCompressed If the Stream is compressed with gzip.) }
36 function LoadX3DClassicFromString(const VRMLContents: String;
37 const BaseUrl: String): TX3DRootNode; deprecated 'use LoadNode with TStringStream';
38
39 { Load VRML/X3D file in classic encoding, return it's root node.
40
41 Automatically handles VRML/X3D files compressed with gzip,
42 uncompressing them on the fly.
43
44 URL without any protocol is treated as a filename (absolute or relative
45 to current dir). We can also load network URLs using CastleDownload.
46
47 If Gzipped then we can be relatively sure that stream is gzipped.
48 Otherwise, it can still be gzipped (.wrl files are sometimes gzipped
49 without extension indicating it). }
50 function LoadX3DClassic(const Url: String;
51 const Gzipped: boolean): TX3DRootNode; deprecated 'use LoadNode';
52
53 {$endif read_interface}
54
55 {$ifdef read_implementation}
56
57 { Internal for ParseIgnoreToMatchingSqBracket and
58 ParseIgnoreToMatchingCurlyBracket }
59 procedure ParseIgnoreToMatchingBracket(
60 Lexer: TX3DLexer; Reader: TX3DReaderNames;
61 LevelSqBracket, LevelCurlyBracket: integer);
62 begin
63 while (LevelSqBracket > 0) or
64 (LevelCurlyBracket > 0) do
65 begin
66 case Lexer.Token of
67 vtOpenCurlyBracket: Inc(LevelCurlyBracket);
68 vtCloseCurlyBracket: Dec(LevelCurlyBracket);
69 vtOpenSqBracket: Inc(LevelSqBracket);
70 vtCloseSqBracket: Dec(LevelSqBracket);
71 vtEnd: raise EX3DParserError.Create(Lexer, 'Unexpected end of stream');
72 else ;
73 end;
74 Lexer.NextToken;
75 end;
76 end;
77
78 (* Assume that we just read "[", and are looking at next character.
79 Read everything up to (and including) matching "]".
80 This is a hack to omit (not really parse) interface sections
81 of prototypes. *)
82 procedure ParseIgnoreToMatchingSqBracket(Lexer: TX3DLexer; Reader: TX3DReaderNames);
83 begin
84 ParseIgnoreToMatchingBracket(Lexer, Reader, 1, 0);
85 end;
86
87 (* Just like ParseIgnoreToMatchingSqBracket, but here for "{" and "}" brackets.
88 This is a hack to omit (not really parse) unknown VRML nodes. *)
89 procedure ParseIgnoreToMatchingCurlyBracket(Lexer: TX3DLexer; Reader: TX3DReaderNames);
90 begin
91 ParseIgnoreToMatchingBracket(Lexer, Reader, 0, 1);
92 end;
93
94 (*
95 Parse VRML node. This parses
96 @preformatted([ DEF <nodename> ] <nodetype> { node-content })
97 or
98 @preformatted(USE <nodename>)
99
100 If we will find USE clause but node name will be unknown, the normal
101 behavior (when NilIfUnresolvedUSE = @false, default) is to raise
102 EX3DParserError (just like in case of many other errors).
103 However, this is a particular parsing error, because we can probably
104 pretty safely continue parsing, ignoring this error.
105 So if you pass NilIfUnresolvedUSE = @true, this function will do
106 WritelnWarning and simply return @nil.
107
108 @raises(EX3DParserError On various parsing errors.)
109 *)
110 function ParseNode(const Lexer: TX3DLexer; const Reader: TX3DReaderNames;
111 const NilIfUnresolvedUSE: Boolean;
112 const AllowNodeCycle: Boolean; var UsingNodeCycle: Boolean): TX3DNode; overload;
113
114 procedure ParseNamedNode(const NodeName: String);
115 var
116 NodeClass: TX3DNodeClass;
117 X3DType: String;
118 Proto: TX3DPrototypeBase;
119 begin
120 Lexer.CheckTokenIs(vtName, 'node type');
121 X3DType := Lexer.TokenName;
122 Lexer.NextToken;
123
124 { VRML / X3D specifications say it is an error for a PROTO to have
125 the same name as built-in node. I didn't found any definite
126 statements about EXTERNPROTO names, although I vaguely remember
127 some notes that EXTERNPROTO name should take precedence over
128 built-in names. And this seems most sensible. Especially for
129 nodes that were not available in older VRML / X3D editions and
130 were declared (possibly slightly sensible) using EXTERNPROTOs,
131 it's a good thing to use EXTERNPROTOs: they were probably most
132 current with respect to given VRML file. Examples are CAD
133 test files from
134 http://www.web3d.org/x3d/content/examples/Basic/CAD/
135
136 So we first search for X3DType among protos.
137 Only when this failed, we look at built-in nodes in NodesManager.
138 }
139
140 Proto := Reader.Prototypes.Bound(X3DType);
141 if Proto <> nil then
142 begin
143 if (Proto is TX3DExternalPrototype) and
144 (TX3DExternalPrototype(Proto).ReferencedClass <> nil) then
145 Result := TX3DExternalPrototype(Proto).ReferencedClass.Create(NodeName, Reader.BaseUrl) else
146 Result := TX3DPrototypeNode.CreatePrototypeNode(NodeName, Reader.BaseUrl, Proto);
147 end else
148 begin
149 NodeClass := NodesManager.X3DTypeToClass(X3DType, Reader.Version);
150 if NodeClass <> nil then
151 begin
152 Result := NodeClass.Create(NodeName, Reader.BaseUrl);
153 end else
154 begin
155 Result := TX3DUnknownNode.CreateUnknown(NodeName, Reader.BaseUrl, X3DType);
156 end;
157 end;
158
159 { Register node name early, before it is finalized.
160 Reason:
161 - Some X3D models use ROUTEs inside the nodes to/from which they lead.
162 - Some X3D models may have cycles in node graph (see notes below about Script).
163 }
164 Reader.Nodes.Bind(Result, false);
165
166 Result.Parse(Lexer, Reader);
167
168 if Result is TX3DPrototypeNode then
169 try
170 { Note that this changes Result, and the new Result must be send to Nodes.Bind,
171 as the "instantiated" node must be registered. }
172 Result := TX3DPrototypeNode(Result).Instantiate;
173 except
174 on E: EX3DPrototypeInstantiateError do
175 { Just write E.Message and silence the exception.
176 Result will simply remain as TX3DPrototypeNode instance in this case. }
177 WritelnWarning('VRML/X3D', E.Message);
178 end;
179
180 { Cycles in VRML / X3D graph are possible.
181
182 Problems with them:
183 - they can cause our traversing routines to loop infinitely
184 (we don't check there to avoid visiting already visited nodes).
185 - they can cause memory leaks, since reference
186 counting doesn't work when we have loops.
187
188 But we cannot really avoid handling them.
189 We need to
190 Reader.Nodes.Bind(Result, false)
191 before parsing node centents, and
192 Reader.Nodes.Bind(Result, true)
193 after.
194
195 That is because a Script node's interface declarations may contain
196 cyclic references, to Script node itself or it's parents. See
197 demo-models/x3d/node_cycle_in_script.x3d
198 demo-models/x3d/node_cycle_in_script.x3dv
199
200 Also RenderedTexture.scene may contain a cycle.
201
202 Looking at spec: It prohibits certain special kinds of cycles,
203 but not *any* cycles in graph.
204
205 - X3D specification says
206 "A children field is not allowed to contain nodes that
207 are ancestors of the grouping node"
208 (so "children" MFNode field cycles are not allowed).
209
210 - Many other cases cycles are not possible,
211 e.g. Appearance cannot create cycles since no Appearance children
212 can be of Appearance type.
213
214 SFNode can handle cycles in some cases with AutomaticWeakLink.
215 When not AutomaticWeakLink, at least we use NilIfUnresolvedUSE
216 to clearly ignore such cycles and continue reading the file. }
217
218 Reader.Nodes.Bind(Result, true);
219 end;
220
221 var
222 NodeName, S: String;
223 UsedNodeFinished: boolean;
224 begin
225 Result := nil;
226 try
227 (* node means :
228 DEF <name> <nodetype> { node-content } or
229 USE <name> or
230 <nodetype> { node-content }
231 *)
232
233 case Lexer.Token of
234 vtKeyword:
235 case Lexer.TokenKeyword of
236 vkDEF:
237 begin
238 Lexer.NextTokenForceVTName;
239 NodeName := Lexer.TokenX3DName;
240 Lexer.NextToken;
241 ParseNamedNode(NodeName);
242 end;
243 vkUSE:
244 begin
245 Lexer.NextTokenForceVTName;
246 NodeName := Lexer.TokenX3DName;
247
248 {get appropriate node}
249 Result := Reader.Bound(NodeName, UsedNodeFinished, true);
250 { When AllowNodeCycle, then UsedNodeFinished=false is not a problem.
251 Just flip UsingNodeCycle to true, caller can handle a loop in node definition. }
252 if (Result <> nil) and (not UsedNodeFinished) and AllowNodeCycle then
253 begin
254 UsingNodeCycle := true;
255 UsedNodeFinished := true;
256 end;
257 if (Result = nil) or (not UsedNodeFinished) then
258 begin
259 if Result = nil then
260 S := Format(SIncorrectUse, [NodeName]) else
261 begin
262 S := Format(SNodeUseCycle, [NodeName]);
263 Result := nil; { return nil in case of cycles }
264 end;
265 if NilIfUnresolvedUSE then
266 WritelnWarning('VRML/X3D', S)
267 else
268 raise EX3DParserError.Create(Lexer, S);
269 end;
270
271 Lexer.NextToken;
272 end;
273 else raise EX3DParserError.Create(Lexer,
274 'Expected node type or DEF or USE, got '+Lexer.DescribeToken);
275 end;
276 vtName: ParseNamedNode('');
277 else raise EX3DParserError.Create(Lexer,
278 'Expected node type or DEF or USE, got '+Lexer.DescribeToken);
279 end;
280 except FreeAndNil(Result); raise end;
281 end;
282
283 function ParseNode(const Lexer: TX3DLexer; const Reader: TX3DReaderNames;
284 const NilIfUnresolvedUSE: Boolean): TX3DNode; overload;
285 var
286 IgnoredUsingNodeCycle: Boolean;
287 begin
288 IgnoredUsingNodeCycle := false;
289 Result := ParseNode(Lexer, Reader, NilIfUnresolvedUSE, false, IgnoredUsingNodeCycle);
290 end;
291
292 { Parse any "statement" from X3D grammar.
293 See https://www.web3d.org/documents/specifications/19776-2/V3.3/Part02/grammar.html ,
294 but it has been changed in X3D 4.0 to allow more things in "nodeStatement"
295 according to https://github.com/castle-engine/castle-model-viewer/issues/79 .
296
297 Adds new parsed stuff to ContainerNode...
298 Unless that stuff is a node, in which case it is
299 - when ContainerNode is TX3DRootNode:
300 added to ContainerNode using ContainerNode.AddRootNode.
301 You can leave ContainerField=nil in this case.
302 - otherwise:
303 added to ContainerField.
304
305 Reads and increments PositionInParent. }
306 function ParseStatement(
307 const Lexer: TX3DLexer; const Reader: TX3DReaderNames;
308 const ContainerNode: TX3DNode; const ContainerField: TMFNode;
309 const FileTopLevel: Boolean;
310 var PositionInParent: Integer): TX3DFileItem;
311
312 { Parse and add PROTO or EXTERNPROTO.
313 You can safely assume that current token is PROTO or EXTERNPROTO. }
314 procedure ParseProtoStatement;
315 var
316 Proto: TX3DPrototypeBase;
317 begin
318 if Lexer.TokenKeyword = vkPROTO then
319 Proto := TX3DPrototype.Create else
320 Proto := TX3DExternalPrototype.Create;
321 try
322 Proto.Parse(Lexer, Reader);
323 ContainerNode.AddPrototype(Proto);
324 Result := Proto;
325 except
326 FreeAndNil(Proto); { do not add invalid Proto, free it }
327 raise;
328 end;
329 end;
330
331 procedure ParseRouteStatement;
332 var
333 Route: TX3DRoute;
334 begin
335 Route := TX3DRoute.Create;
336 try
337 Route.Parse(Lexer, Reader);
338 ContainerNode.AddRoute(Route);
339 Result := Route;
340 except
341 FreeAndNil(Route); { do not add invalid Route, free it }
342 raise;
343 end;
344 end;
345
346 procedure ParseImportStatement;
347 var
348 Import: TX3DImport;
349 begin
350 Import := TX3DImport.Create;
351 try
352 Import.Parse(Lexer, Reader);
353 ContainerNode.AddImport(Import);
354 Result := Import;
355 except
356 FreeAndNil(Import); { do not add invalid Import, free it }
357 raise;
358 end;
359 end;
360
361 procedure ParseExportStatement;
362 var
363 Export: TX3DExport;
364 begin
365 Export := TX3DExport.Create;
366 try
367 Export.Parse(Lexer, Reader);
368 ContainerNode.AddExport(Export);
369 Result := Export;
370 except
371 FreeAndNil(Export); { do not add invalid Export, free it }
372 raise;
373 end;
374 end;
375
376 procedure ParseNodeStatement;
377 var
378 NewNode: TX3DNode;
379 begin
380 NewNode := ParseNode(Lexer, Reader, false);
381 if ContainerNode is TX3DRootNode then
382 TX3DRootNode(ContainerNode).AddRootNode(NewNode, FileTopLevel)
383 else
384 ContainerField.Add(NewNode);
385 Result := NewNode;
386 end;
387
388 begin
389 if (Lexer.Token = vtKeyword) and
390 (Lexer.TokenKeyword in [vkPROTO, vkEXTERNPROTO]) then
391 ParseProtoStatement
392 else
393 if Lexer.TokenIsKeyword(vkROUTE) then
394 ParseRouteStatement
395 else
396 if Lexer.TokenIsKeyword(vkIMPORT) then
397 ParseImportStatement
398 else
399 if Lexer.TokenIsKeyword(vkEXPORT) then
400 ParseExportStatement
401 else
402 ParseNodeStatement;
403
404 Assert(Result <> nil);
405 Result.PositionInParent := PositionInParent;
406 Inc(PositionInParent);
407 end;
408
409 { Parses a sequence of VRML/X3D statements: any number of nodes,
410 (external) protypes, routes, import/export declarations.
411 This is good to use to parse whole VRML/X3D file (when FileTopLevel = true),
412 or a (non-external) prototype content (when FileTopLevel = false). }
413 function ParseStatements(
414 Lexer: TX3DLexer; Reader: TX3DReaderNames;
415 const EndToken: TX3DToken;
416 FileTopLevel: boolean): TX3DRootNode; overload;
417 var
418 PositionInParent: Integer;
419
420 { Create root group node, appropriate for current VRML version in Lexer. }
421 function CreateRootNode: TX3DRootNode;
422 begin
423 Result := TX3DRootNode.Create('', Reader.BaseUrl);
424 Result.HasForceVersion := true;
425 Result.ForceVersion := Reader.Version;
426 end;
427
428 procedure ParseProfile;
429 begin
430 if Lexer.TokenIsKeyword(vkPROFILE) then
431 begin
432 Lexer.NextToken;
433 Lexer.CheckTokenIs(vtName, 'X3D profile name');
434 Result.Profile := Lexer.TokenName;
435
436 Lexer.NextToken;
437 end else
438 { We allow PROFILE to be omitted, which is not really allowed by
439 X3D spec. }
440 WritelnWarning('VRML/X3D', 'X3D PROFILE statement missing');
441 end;
442
443 procedure ParseComponents;
444 var
445 Name: String;
446 Level: Integer;
447 begin
448 while Lexer.TokenIsKeyword(vkCOMPONENT) do
449 begin
450 Lexer.NextToken;
451 Lexer.CheckTokenIs(vtName, 'X3D component name');
452 Name := Lexer.TokenName;
453
454 Lexer.NextToken;
455 Lexer.CheckTokenIs(vtColon);
456
457 Lexer.NextToken;
458 Lexer.CheckTokenIs(vtInteger, 'X3D component level');
459 Level := Lexer.TokenInteger;
460 Result.Components[Name] := Level;
461
462 Lexer.NextToken;
463 end;
464 end;
465
466 procedure ParseUnits;
467 var
468 Category, Name: String;
469 ConversionFactor: Float;
470 begin
471 while Lexer.TokenIsKeyword(vkUNIT) do
472 begin
473 Lexer.NextToken;
474 Lexer.CheckTokenIs(vtName, 'X3D unit category');
475 Category := Lexer.TokenName;
476
477 Lexer.NextToken;
478 Lexer.CheckTokenIs(vtName, 'X3D unit name');
479 Name := Lexer.TokenName;
480
481 Lexer.NextToken;
482 Lexer.CheckTokenIs(TokenNumbers, 'X3D unit conversion factor (double-precision float)');
483 ConversionFactor := Lexer.TokenFloat;
484
485 Lexer.NextToken;
486
487 Reader.UnitConversion(Category, Name, ConversionFactor);
488 end;
489 Result.Scale := Reader.LengthConversionFactor;
490 end;
491
492 procedure ParseMetas;
493 var
494 Key, Value: String;
495 begin
496 if Lexer.TokenIsKeyword(vkMETA) and
497 (Reader.Version.Major < 3) then
498 WritelnWarning('VRML/X3D', 'META is not allowed in VRML, you should use X3D instead');
499
500 while Lexer.TokenIsKeyword(vkMETA) do
501 begin
502 Lexer.NextToken;
503 Lexer.CheckTokenIs(vtString, 'X3D meta key');
504 Key := Lexer.TokenString;
505
506 Lexer.NextToken;
507 Lexer.CheckTokenIs(vtString, 'X3D meta value');
508 Value := Lexer.TokenString;
509 Result.Meta[Key] := Value;
510
511 Lexer.NextToken;
512 end;
513 end;
514
515 begin
516 { We used to have more conservative mechanism here when it comes to using
517 CreateRootNode: we used to start with Result = nil.
518 First ParseNodeInternal simply set the Result to it's contents.
519 ParseProtoStatement, ParseRouteInternal and second and subsequent
520 ParseNodeInternal calls called CreateRootNode, and added previous
521 content as new root node child.
522
523 This was an unnecessarily complicated mechanism. The history is that
524 initially, for correct VRML 1.0, the whole concept of RootGroup was
525 not needed. It became needed since VRML 2.0, to
526 - store multiple root nodes of VRML 2.0 file
527 - and many VRML 1.0 files also used (incorrectly) the "multiple root nodes"
528 feature
529 - also, VRML 2.0 / X3D routes and prototypes declared at global scope had
530 to be stored in a root group
531 - Finally, ForceVersion mechanism is available for RootGroup to force
532 writing of specific VRML/X3D version.
533 - And for X3D, TX3DRootNode has to be enhanced
534 to keep other top-level X3D data: profile, components, meta statements.
535
536 So now, we simply always create root node by ParseStatements. }
537
538 Result := CreateRootNode;
539 try
540 { Parse X3D "configuration information": profile, component and meta
541 statements here. }
542 if FileTopLevel and (Reader.Version.Major >= 3) then
543 begin
544 ParseProfile;
545 ParseComponents;
546 ParseUnits;
547 end;
548 if FileTopLevel then { META is not part of VRML 2.0, but Titania uses it }
549 ParseMetas;
550
551 PositionInParent := 0;
552
553 if EndToken <> vtEnd then
554 begin
555 while Lexer.Token <> EndToken do
556 begin
557 ParseStatement(Lexer, Reader, Result, nil, FileTopLevel, PositionInParent);
558 end;
559 end else
560 begin
561 { Somewhat more involved version of the loop, the idea is to catch
562 EX3DClassicReadError happening in the ParseStatement
563 and convert it to WritelnWarning (then merely stop reading VRML file,
564 but the file contents read so far are Ok). }
565 while Lexer.Token <> EndToken do
566 try
567 ParseStatement(Lexer, Reader, Result, nil, FileTopLevel, PositionInParent);
568 except
569 on E: EX3DClassicReadError do
570 begin
571 WritelnWarning('VRML/X3D', Format('Error when reading, will skip the rest of X3D file: %s', [E.Message]));
572 Break;
573 end;
574 end;
575 end;
576 except FreeAndNil(Result); raise end;
577 end;
578
579 function LoadX3DClassicInternal(const Stream: TStream;
580 const BaseUrl: String): TX3DRootNode;
581 var
582 PeekStream: TPeekCharStream;
583 Lexer: TX3DLexer;
584 Reader: TX3DReaderNames;
585 begin
586 PeekStream := TBufferedReadStream.Create(Stream, false);
587 try
588 Lexer := TX3DLexer.Create(PeekStream, false);
589 try
590 Reader := TX3DReaderNames.Create(false, BaseUrl, Lexer.Version);
591 try
592 Result := ParseStatements(Lexer, Reader, vtEnd, true);
593 Reader.ExtractNames(Result.FPrototypeNames, Result.FExportedNames, Result.FImportedNames);
594 finally FreeAndNil(Reader) end;
595 finally FreeAndNil(Lexer) end;
596 finally FreeAndNil(PeekStream) end;
597 end;
598
599 function LoadX3DClassic(const Url: String;
600 const Gzipped: boolean): TX3DRootNode;
601
602 function DoIt(BaseStream: TStream; const BaseUrl: String): TX3DRootNode;
603 begin
604 try
605 Result := LoadX3DClassicInternal(BaseStream, BaseUrl);
606 finally FreeAndNil(BaseStream) end;
607 end;
608
609 var
610 BaseUrl: String;
611 begin
612 BaseUrl := AbsoluteURI(Url);
613
614 if Gzipped then
615 Result := DoIt(Download(Url, [soGzip]), BaseUrl) else
616 begin
617 try
618 Result := DoIt(Download(Url, []), BaseUrl);
619 except
620 { It's somewhat hacky solution to reopen the file, creating new stream.
621 But in practice, this works OK, and it allows us to read files
622 compressed by gzip but without indicating this by file extension.
623 See LoadNode comments. }
624 on EGzipCompressed do
625 Result := DoIt(Download(Url, [soGzip]), BaseUrl);
626 end;
627 end;
628 end;
629
630 function LoadX3DClassicFromString(const VRMLContents: String;
631 const BaseUrl: String): TX3DRootNode;
632 var
633 Stream: TStringStream;
634 begin
635 Stream := TStringStream.Create(VRMLContents);
636 try
637 Result := LoadX3DClassicInternal(Stream, BaseUrl);
638 finally FreeAndNil(Stream) end;
639 end;
640
641 { Internal parsing helper. }
642 function InterfaceDeclarationKeywords(
643 const AccessTypes: TX3DAccessTypes): TX3DKeywords;
644 begin
645 Result := [];
646 if atInputOnly in AccessTypes then
647 Result := Result + [vkEventIn, vkInputOnly];
648 if atOutputOnly in AccessTypes then
649 Result := Result + [vkEventOut, vkOutputOnly];
650 if atInitializeOnly in AccessTypes then
651 Result := Result + [vkField, vkInitializeOnly];
652 if atInputOutput in AccessTypes then
653 Result := Result + [vkExposedField, vkInputOutput];
654 end;
655
656 {$endif read_implementation}