Debian Codegraph @

src/scene/x3d/x3dnodes_standard_networking.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2002-2024 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 { Basis for all sensors that generate events based on network activity. }
19 TAbstractNetworkSensorNode = class(TAbstractSensorNode)
20 {$I auto_generated_node_helpers/x3dnodes_x3dnetworksensornode.inc}
21 end;
22
23 { Functionality used by all nodes that contain data located on the World Wide Web.
24 This corresponds to X3D abstract type X3DUrlObject supported by various nodes. }
25 TUrlFunctionality = class(TNodeFunctionality)
26 // FdUrl: TMFString
27 end;
28
29 TAbstractViewpointNode = class;
30
31 { Load the URL when the user activates (clicks)
32 some geometry contained within the Anchor node's children. }
33 TAnchorNode = class(TAbstractGroupingNode)
34 protected
35 function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override;
36 public
37 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
38
39 { Load the document, world and/or viewpoint referenced by this Anchor node.
40
41 This iterates over url field, for each URL trying to load
42 referenced file. If URL specifies viewpoint name within 3D file (or current
43 3D world), we also search for viewpoint.
44 If it will succeed for some URL, returns @true,
45 setting output parameters. Returns @false if no loadable URL is found.
46
47 Output NewRootNode is the loaded world,
48 or @nil if actually we should stay within the same world.
49 @nil happens for URLs like @code(#ViewpointName),
50 or when URL refers to some non-3D document (that is opened with appropriate
51 application on user system).
52
53 NewViewpoint is the new viewpoint that should be bound,
54 or @nil if URL doesn't specify viewpoint name within 3D file.
55 This viewpoint is part of NewRootNode graph, if NewRootNode <> @nil,
56 or is part of CurrentRootNode if we should stay within
57 current world (NewRootNode = @nil).
58
59 Note that this means that NewRootNode = nil and
60 NewViewpoint = nil are valid output from this method,
61 and indicate that nothing should be done.
62
63 CurrentRootNode is required to detect invalid viewpoint names
64 within current file. An explanation why this is needed follows:
65
66 Invalid viewpoint names within newly loaded
67 files are harmless, that is newly loaded file is accepted anyway
68 and invalid viewpoint name is ignored. X3D spec says this explicitly.
69
70 But what should happen for invalid viewpoint names within current file?
71 X3D spec doesn't say anything clear here (the part before "#" is
72 valid in this case, since it just indicates current file, so someone
73 could argue that URL is valid, only viewpoint name is wrong and
74 so it should be ignored...). Consider url field like
75
76 @preformatted(
77 [ "#NotExistingViewpoint", "#ExistingViewpoint" ]
78 )
79
80 It seems sensible that we detect "#NotExistingViewpoint" as invalid,
81 and move on to the next URL (which may be local or not).
82 That's why we need CurrentRootNode instance.
83 When CurrentRootNode = nil, we understand that no file is currently
84 loaded (at least, you don't have it's X3D graph). It means that
85 any "#Viewpoint" within current model is considered invalid. }
86 function LoadAnchor(
87 out NewRootNode: TX3DRootNode;
88 out NewViewpoint: TAbstractViewpointNode;
89 CurrentRootNode: TX3DRootNode): boolean;
90
91 {$I auto_generated_node_helpers/x3dnodes_anchor.inc}
92 end;
93
94 { Embed another X3D scene into the current scene. }
95 TInlineNode = class(TAbstractInternalGroupingNode)
96 strict private
97 procedure EventLoadReceive(
98 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
99 procedure EventUrlReceive(
100 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
101 private
102 { Is the inline currently loaded. This means "loaded",
103 not "successfully loaded": when InlinedLoaded := true,
104 we condider "url" field as handled, and loaded *if possible*.
105 If "url" didn't contain anything useful, InlinedLoaded is still set to @true,
106 to avoid constantly trying to reload. }
107 InlinedLoaded: boolean;
108 FInlined: TX3DRootNode;
109 protected
110 procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); override;
111 procedure AfterTraverse(StateStack: TX3DGraphTraverseStateStack); override;
112 { You can override this to do anything after the Inline children were
113 loaded. It's called only after actual loading occurred, e.g. it's not
114 called when LoadInlined was called on the already-loaded node with
115 CanReload = @false. }
116 procedure AfterLoadInlined; virtual;
117 procedure ParseAfter(Reader: TX3DReaderNames); override;
118 protected
119 function DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode; override;
120 public
121 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
122
123 class function VRML1ChildrenSaveToStream: boolean; override;
124
125 { Load inlined content @bold(now).
126 If @link(Inlined) is already loaded:
127 if CanReload = @true then it will be freed and loaded again,
128 else (if CanReload = @false) nothing will happen.
129
130 Note that this has a really simple support for "load" field
131 (this concerns VRML 97 amendment 1 "InlineLoadControl.load" and
132 X3D (actually used also in VRML 97 handling) "Inline.load" fields).
133 It simply doesn't do any loading when "load" = @false.
134
135 Note that this doesn't perform setting the "load" field,
136 or sending any notifications to Scene
137 about "load" field. It's the caller's job to keep loaded state
138 synchronized with "load" field value.
139
140 LoadInlined(false) will be called automatically, to ensure the inlined
141 contents are always loaded. It will be called at the end of Parse
142 (this is needed to handle VRML/X3D IMPORT/EXPORT mechanism),
143 it will also be called in BeforeTraverse (in case you constructed node
144 by code, not by parsing; this also happens when node was made by expanding
145 a PROTO).
146
147 @param(Exported If non-nil, we will assign here node names
148 exported from the file. Used to handle IMPORT/EXPORT X3D mechanism.) }
149 procedure LoadInlined(CanReload: boolean;
150 const CurrentLengthConversionFactor: Float = 1.0;
151 const Exported: TX3DNodeNames = nil);
152
153 procedure UnLoadInlined;
154
155 { Call this to indicate that you loaded the inline contents directly,
156 by using AddChild yourself. }
157 procedure LoadedInlineDirectly;
158
159 { The inlined content (loaded from inlined url).
160 @nil if not yet loaded, or no loading was successful.
161
162 This is also kept in VRML 1.0 children list as VRML1Children[0],
163 but for future it's better to not depend on that.
164 But it will always be enumerated by things like TX3DNode.EnumerateNodes. }
165 property Inlined: TX3DRootNode read FInlined;
166
167 {$I auto_generated_node_helpers/x3dnodes_inline.inc}
168 end;
169
170 { Embed another X3D scene into the current scene,
171 with additional output event when they are loaded (VRML 97 version).
172
173 This node is implemented only for compatibility with VRML 97.
174 It has additional "children" output field.
175 See VRML 97 Amendment spec,
176 https://www.web3d.org/documents/specifications/14772-1/V2.1/index.html . }
177 TInlineLoadControlNode = class(TInlineNode)
178 protected
179 procedure AfterLoadInlined; override;
180
181 {$I auto_generated_node_helpers/x3dnodes_inlineloadcontrol.inc}
182 end;
183
184 { Monitors the progress and success of downloading URL elements over a network. }
185 TLoadSensorNode = class(TAbstractNetworkSensorNode)
186 public
187 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
188 {$I auto_generated_node_helpers/x3dnodes_loadsensor.inc}
189 end;
190
191 {$endif read_interface}
192
193 {$ifdef read_implementation}
194
195 { TAnchorNode ---------------------------------------------------------------- }
196
197 constructor TAnchorNode.Create(const AX3DName, ABaseUrl: String);
198 begin
199 inherited;
200 AddFunctionality(TUrlFunctionality.Create(Self));
201 end;
202
203 function TAnchorNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer;
204 var
205 I: Integer;
206 begin
207 Result := nil;
208 for I := 0 to FdChildren.Count - 1 do
209 begin
210 Result := Func(Self, FdChildren[I]);
211 if Result <> nil then Exit;
212 end;
213 end;
214
215 function TAnchorNode.LoadAnchor(
216 out NewRootNode: TX3DRootNode;
217 out NewViewpoint: TAbstractViewpointNode;
218 CurrentRootNode: TX3DRootNode): boolean;
219
220 procedure ViewpointNameInvalid(const NewViewpointName: string);
221 begin
222 WritelnWarning('X3D', Format('Viewpoint "%s" specified by Anchor not found',
223 [NewViewpointName]));
224 end;
225
226 var
227 I: Integer;
228 Url, UrlWithoutViewpoint, NewViewpointName: string;
229 begin
230 for I := 0 to FdUrl.Count - 1 do
231 begin
232 Url := FdUrl.Items[I];
233
234 { We have to call URIExtractAnchor before PathFromBaseUrl.
235 Otherwise, in case of Urls like '' or '#viewpoint_in_this_world'
236 PathFromBaseUrl would prefix it with our path,
237 making it invalid. }
238 UrlWithoutViewpoint := Url;
239 URIExtractAnchor(UrlWithoutViewpoint, NewViewpointName);
240
241 NewRootNode := nil;
242 NewViewpoint := nil;
243
244 if UrlWithoutViewpoint = '' then
245 begin
246 { in this case, we have either a viewpoint in current 3D world, or nothing }
247
248 if NewViewpointName = '' then
249 begin
250 Assert(NewViewpoint = nil); // already assigned NewViewpoint := nil above
251 Exit(true);
252 end else
253 begin
254 if CurrentRootNode <> nil then
255 begin
256 NewViewpoint := CurrentRootNode.FindNode(TAbstractViewpointNode,
257 NewViewpointName, [fnOnlyActive, fnNilOnMissing]) as TAbstractViewpointNode;
258 if NewViewpoint <> nil then
259 Exit(true)
260 else
261 ViewpointNameInvalid(NewViewpointName);
262 end else
263 ViewpointNameInvalid(NewViewpointName);
264
265 { In this case invalid viewpoint name is treated as a failure,
266 that is we try to find next URL.
267 This happens when CurrentRootNode = nil or when
268 CurrentRootNode doesn't contain NewViewpointName. }
269 end;
270
271 end else
272 begin
273 { in this case (UrlWithoutViewpoint <> ''),
274 we have either a new X3D root node, or a document that isn't a model }
275
276 UrlWithoutViewpoint := PathFromBaseUrl(UrlWithoutViewpoint);
277 try
278 if TFileFilterList.Matches(LoadScene_FileFilters, UrlWithoutViewpoint) then
279 begin
280 NewRootNode := LoadNode(UrlWithoutViewpoint);
281 end else
282 begin
283 { we have a document URL, Exit or Continue }
284 if OpenURL(PathFromBaseUrl(Url)) then
285 begin
286 Assert(NewViewpoint = nil); // already assigned NewViewpoint := nil earlier
287 Exit(true);
288 end else
289 begin
290 WritelnWarning('X3D', Format('Cannot open browser to handle document on this URL: %s',
291 [PathFromBaseUrl(Url)]));
292 Continue;
293 end;
294 end;
295
296 except
297 on E: Exception do
298 begin
299 { Catch exception and produce WritelnWarning, go to next URL }
300 WritelnWarning('X3D', Format('Loading world from Anchor URL "%s" failed: %s',
301 [UrlWithoutViewpoint, E.Message]));
302 Continue;
303 end;
304 end;
305
306 Assert(NewRootNode <> nil);
307
308 if NewViewpointName = '' then
309 begin
310 NewViewpoint := nil;
311 end else
312 begin
313 NewViewpoint := NewRootNode.FindNode(TAbstractViewpointNode,
314 NewViewpointName, [fnOnlyActive, fnNilOnMissing]) as TAbstractViewpointNode;
315 if NewViewpoint = nil then
316 ViewpointNameInvalid(NewViewpointName);
317
318 { In this case invalid viewpoint name is ignored,
319 that is we still accept this URL. This follows X3D spec
320 (also, this is sensible, otherwise we would have to free
321 loaded model just because viewpoint is invalid). }
322 end;
323
324 Exit(true);
325 end;
326 end;
327 Result := false;
328 end;
329
330 { TInlineNode ---------------------------------------------------------------- }
331
332 constructor TInlineNode.Create(const AX3DName, ABaseUrl: String);
333 begin
334 inherited;
335 AddFunctionality(TUrlFunctionality.Create(Self));
336
337 FdLoad.AddNotification({$ifdef FPC}@{$endif} EventLoadReceive);
338 FdUrl.AddNotification({$ifdef FPC}@{$endif} EventUrlReceive);
339
340 { To allow inlined children (they are loaded as VRML 1.0 style children) }
341 VRML1ChildrenAllowed := true;
342 VRML1ChildrenParsingAllowed := false;
343
344 FInlined := nil;
345 end;
346
347 procedure TInlineNode.ParseAfter(Reader: TX3DReaderNames);
348 var
349 Exported: TX3DNodeNames;
350 begin
351 inherited;
352
353 if X3DName <> '' then
354 Exported := TX3DNodeNames.Create(false)
355 else
356 Exported := nil;
357
358 LoadInlined(false, Reader.LengthConversionFactor, Exported);
359
360 { do not add Exported to Importable list, if nothing was exported.
361 This just saves the size of the Importable list. }
362 if (Exported <> nil) and (Exported.Count = 0) then
363 FreeAndNil(Exported);
364
365 if Exported <> nil then
366 begin
367 { connect Exported nodes with our inline Name }
368 Assert(X3DName <> '');
369 Reader.Importable.Bind(X3DName, Exported);
370 end;
371 end;
372
373 procedure TInlineNode.UnLoadInlined;
374 begin
375 VRML1ChildrenClear;
376 FInlined := nil;
377 InlinedLoaded := false;
378 end;
379
380 procedure TInlineNode.LoadInlined(CanReload: boolean;
381 const CurrentLengthConversionFactor: Float;
382 const Exported: TX3DNodeNames);
383
384 { Assign TX3DExportList contents to TX3DNodeNames.
385 This is done only after loading the X3D file,
386 as earlier the final names of X3D nodes are not yet finalized,
387 as FixNames may change them. }
388 procedure InitializeExported(const Target: TX3DNodeNames; const Source: TX3DExportList);
389 var
390 NodeName: String;
391 I: Integer;
392 begin
393 Target.Clear;
394 for I := 0 to Source.Count - 1 do
395 begin
396 NodeName := Source[I].ExportedAlias;
397 if NodeName = '' then
398 NodeName := Source[I].ExportedNode.X3DName;
399 Target.Bind(Source[I].ExportedNode, true, NodeName);
400 end;
401 end;
402
403 var
404 I: Integer;
405 FullUrl: String;
406 begin
407 if Exported <> nil then Exported.Clear;
408
409 if InlinedLoaded then
410 begin
411 if CanReload then UnLoadInlined else Exit;
412 end;
413
414 Assert(not InlinedLoaded);
415 Assert(FInlined = nil);
416 Assert(VRML1ChildrenCount = 0);
417
418 if (not FdLoad.Value) or
419 { Do not do anything, in particular do not set InlinedLoaded:=true,
420 when url field is empty. This is important in case "url" field value
421 has an IS clause, and it will be really known only after expanding
422 the PROTO, see demo_models/prototypes/proto_inline.x3dv testcase. }
423 (FdUrl.Items.Count = 0) then
424 Exit;
425
426 for I := 0 to FdUrl.Items.Count - 1 do
427 { For VRML 1.0 WWWInline, an item on "url" (alias "name") field
428 may be empty, and should be nicely ignored then.
429 For VRML >= 2.0 we also can ignore it (otherwise confusing warning
430 about unrecognized 3D model file extension for dir name is done). }
431 if FdUrl.Items[I] <> '' then
432 begin
433 FullUrl := PathFromBaseUrl(FdUrl.Items[I]);
434 try
435 FInlined := LoadNode(FullUrl);
436 if (Exported <> nil) and
437 (TX3DRootNode(FInlined).ExportedNames <> nil) then
438 InitializeExported(Exported, TX3DRootNode(FInlined).ExportedNames);
439 Break;
440 except
441 on E: Exception do
442 { Careful here, as WritelnWarning may also raise exception. }
443 WritelnWarning('X3D', Format(SLoadError,
444 [E.ClassName, 'inline file', UriDisplay(FullUrl), E.Message]));
445 end;
446 end;
447
448 if FInlined <> nil then
449 begin
450 { The Inlined contents are usually TX3DRootNode,
451 but they should not be saved as such. Although usually this doesn't
452 get saved (since we do not save inline contents), but it may happen
453 if you copy nodes around, e.g. "expanding" inlines (see castle-model-viewer
454 planned feature, in castle-model-viewer/TODO-expand-inlines.txt).
455
456 TODO: Such expanding must inherently break mismatching UNIT clauses
457 for LengthConversionFactor. To overcome this, our TX3DRootNode
458 should descend from TTransformNode and have it's scale actually saved. }
459 FInlined.SaveAsRootNode := false;
460
461 { FInlined.Scale is adjusted now to make 1 unit = 1 meter inside.
462 However, we are already scaled by CurrentLengthConversionFactor.
463
464 (The check for CurrentLengthConversionFactor <> 1 is only to make sure
465 we keep Scale equal precisely 1.0 (no fp errors) when nothing uses
466 UNIT length.) }
467 if CurrentLengthConversionFactor <> 1 then
468 FInlined.Scale := FInlined.Scale / CurrentLengthConversionFactor;
469
470 VRML1ChildAdd(FInlined);
471 AfterLoadInlined;
472 end;
473
474 { Whether or not we successfully got FInlined <> nil, we always set
475 InlinedLoaded to true here. This way we will not try to reload this inline
476 at next LoadInlined(false) (this would be bad, as we already did
477 WritelnWarning in case loading failed and such). }
478 InlinedLoaded := true;
479 end;
480
481 procedure TInlineNode.LoadedInlineDirectly;
482 begin
483 InlinedLoaded := true;
484 if VRML1ChildrenCount <> 0 then
485 FInlined := VRML1Children[0] as TX3DRootNode else
486 FInlined := nil;
487 end;
488
489 function TInlineNode.DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode;
490 var
491 ResultI: TInlineNode;
492 begin
493 Result := inherited DeepCopyCore(CopyState);
494 ResultI := Result as TInlineNode;
495
496 { Since inherited copied our Children, we should also set "InlinedLoaded"
497 and "Inlined" field to the same value. }
498 ResultI.InlinedLoaded := InlinedLoaded;
499 if ResultI.VRML1ChildrenCount <> 0 then
500 ResultI.FInlined := ResultI.VRML1Children[0] as TX3DRootNode else
501 ResultI.FInlined := nil;
502 end;
503
504 procedure TInlineNode.AfterLoadInlined;
505 begin
506 { Nothing to do in this class. }
507 end;
508
509 procedure TInlineNode.BeforeTraverse(StateStack: TX3DGraphTraverseStateStack);
510 begin
511 inherited;
512
513 try
514 LoadInlined(false);
515 except
516 { LoadInlined may easily fail with exception, it's imprtant in such case
517 to still do AfterTraverse, to make "inherited AfterTraverse",
518 to finalize what "inherited BeginTraverse" did: usually StateStack.Pop. }
519 inherited AfterTraverse(StateStack);
520 raise;
521 end;
522
523 Inc(StateStack.Top.InsideInline);
524 end;
525
526 procedure TInlineNode.AfterTraverse(StateStack: TX3DGraphTraverseStateStack);
527 begin
528 Dec(StateStack.Top.InsideInline);
529 inherited;
530 end;
531
532 class function TInlineNode.VRML1ChildrenSaveToStream: boolean;
533 begin
534 Result := false;
535 end;
536
537 procedure TInlineNode.EventLoadReceive(
538 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
539 begin
540 { Changing the "load" and "url" fields causes LoadInlined or UnLoadInlined,
541 so the VRML graph changes, so they deserve ChangedAll.
542
543 Note that, in theory, actually LoadInlined and UnLoadInlined
544 should already call Scene.ChangedAll already.
545 But this opens a can of worms, because our BeforeTraverse also
546 calls LoadInlined. And you can't really reliably call ChangedAll
547 in the middle of traversing (since this means you may call ChangedAll
548 in the middle of ChangedAll, for which we're not ready).
549
550 Moreover, we need to use BeforeNodesFree. Otherwise our UnLoadInlined
551 will free items to which existing TCastleSceneCore / TShape may keep
552 references. Testcase: inline_load_control_test_1.x3dv,
553 with --debug-log-vrml-changes,
554 press ctrl then shift, without BeforeNodesFree will fail ->
555 because OriginalGeometry.ClassName is no longer available. }
556
557 if Scene <> nil then Scene.BeforeNodesFree;
558
559 if FdLoad.Value then
560 LoadInlined(false) else
561 UnLoadInlined;
562
563 if Scene <> nil then Scene.ChangedAll;
564 end;
565
566 procedure TInlineNode.EventUrlReceive(
567 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
568 begin
569 if FdLoad.Value then
570 begin
571 if Scene <> nil then Scene.BeforeNodesFree;
572 UnLoadInlined;
573 LoadInlined(false);
574 if Scene <> nil then Scene.ChangedAll;
575 end;
576 end;
577
578 { TInlineLoadControlNode ----------------------------------------------------- }
579
580 procedure TInlineLoadControlNode.AfterLoadInlined;
581 var
582 ChildrenToSend: TMFNode;
583 begin
584 { TODO: InlineLoadControl should load it's contents to
585 children MFNode, and we should make a way (analogous
586 to TInlineLoadControlNode.VRML1ChildrenSaveToStream)
587 to say that "we don't want to save to stream "children" field".
588 For now it's not really important (user doesn't see
589 where it's loaded), but it will be later for scripts. }
590
591 if EventChildren.SendNeeded and (Scene <> nil) then
592 begin
593 ChildrenToSend := TMFNode.CreateUndefined(Self, false, EventChildren.X3DName);
594 try
595 ChildrenToSend.Add(FInlined);
596 EventChildren.Send(ChildrenToSend, Scene.NextEventTime);
597 finally FreeAndNil(ChildrenToSend) end;
598 end;
599 end;
600
601 { TLoadSensorNode ------------------------------------------------------------ }
602
603 constructor TLoadSensorNode.Create(const AX3DName, ABaseUrl: String);
604 begin
605 inherited;
606 FdWatchList.AddAlternativeName('children', 4);
607 end;
608
609 procedure RegisterNetworkingNodes;
610 begin
611 NodesManager.RegisterNodeClasses([
612 TAnchorNode,
613 TInlineNode,
614 TInlineLoadControlNode,
615 TLoadSensorNode
616 ]);
617 end;
618
619 {$endif read_implementation}