Debian Codegraph @

src/scene/x3d/x3dnodes_standard_scripting.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 {$ifdef read_interface}
18
19 { Abstract node type for all scripting nodes. }
20 TAbstractScriptNode = class(TAbstractChildNode)
21 strict private
22 type
23 TScriptType = (stCompiled, stCastleScript);
24 var
25 FInitialized: boolean;
26 FInitializedScriptType: TScriptType;
27
28 CompiledScriptContents: TStringList;
29
30 CastleScriptProgram: TCasScriptProgram;
31 CastleScriptVariables: TCasScriptX3DValueList;
32
33 procedure SetInitialized(const Value: boolean);
34 procedure EventUrlReceive(
35 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
36 protected
37 procedure ExecuteScript(const FunctionName: string;
38 ReceivedValue: TX3DField; const Time: TX3DTime);
39 public
40 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
41 destructor Destroy; override;
42
43 { Initialize / shutdown of the script. Read this to know current
44 script state, write this is to actually initialize/shutdown if needed.
45
46 Note that the script node doesn't initialize itself at any point.
47 Reason: there's no comfortable moment to do this: 1. in constructor
48 some routes and such are not initialized yet, and we should initialize
49 script after whole VRML graph is loaded. 2. tricks with BeforeTraverse,
50 like used for TInlineNode, are not Ok, since scripts must work
51 even when they are in the inactive part of VRML graph.
52
53 If you want scripts to work, you have to initialize them yourself.
54 If you use TCastleSceneCore, this will be done for you automatically
55 when you change TCastleSceneCore.ProcessEvents, so it's not a problem in
56 practice. }
57 property Initialized: boolean read FInitialized write SetInitialized
58 default false;
59
60 { Clear the memory when the last events were generated from this script.
61
62 @seealso TX3DRoute.ResetLastEventTime
63 TCasScriptVRMLValuesList.ResetLastEventTimes }
64 procedure ResetLastEventTimes;
65
66 {$I auto_generated_node_helpers/x3dnodes_x3dscriptnode.inc}
67 end;
68
69 { Program behavior in a scene using scripts. }
70 TScriptNode = class(TAbstractScriptNode)
71 strict private
72 procedure IDeclEventReceive(
73 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
74 public
75 procedure PostAddInterfaceDeclaration(IDecl: TX3DInterfaceDeclaration); override;
76 {$I auto_generated_node_helpers/x3dnodes_script.inc}
77 end;
78
79 {$endif read_interface}
80
81 {$ifdef read_implementation}
82
83 { TAbstractScriptNode -------------------------------------------------------- }
84
85 constructor TAbstractScriptNode.Create(const AX3DName, ABaseUrl: String);
86 begin
87 inherited;
88 AddFunctionality(TUrlFunctionality.Create(Self));
89 Fdurl.AddNotification({$ifdef FPC}@{$endif} EventUrlReceive);
90
91 { VRML 97 says this is RestrictedAccessTypes.
92 X3D (both the general spec, and X3D classic encoding grammar,
93 so it's not by accident) allows here all access types, including inputOutput.
94 Some x3d-public mails confirm this was intentionally limited
95 (easier definition) in VRML 97, and intentionally improved in X3D. }
96 HasInterfaceDeclarations := AllAccessTypes;
97
98 CDataField := FdUrl;
99 end;
100
101 destructor TAbstractScriptNode.Destroy;
102 begin
103 { shutdown by directly setting FInitialized to false,
104 we don't want to call ExecuteScript at this point (as VRML graph
105 is partially destroyed here). }
106 FInitialized := false;
107
108 FreeAndNil(CompiledScriptContents);
109 FreeAndNil(CastleScriptProgram);
110 FreeAndNil(CastleScriptVariables);
111 inherited;
112 end;
113
114 procedure TAbstractScriptNode.EventUrlReceive(
115 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
116 begin
117 { Simply shutdown + initialize from new URL }
118 Initialized := false;
119 Initialized := true;
120 end;
121
122 procedure TAbstractScriptNode.ExecuteScript(const FunctionName: string;
123 ReceivedValue: TX3DField; const Time: TX3DTime);
124 var
125 I: Integer;
126 ParameterValue, ParameterTime: TCasScriptValue;
127 begin
128 if Initialized and (Scene <> nil) then
129 begin
130 { Disable this by default, as it really trashes the log with a lot
131 of messages in case script is used continuously (with TimeSensor or such).
132 WritelnLog('VRML Script', 'Executing "' + FunctionName + '"');
133 }
134
135 case FInitializedScriptType of
136 stCompiled:
137 begin
138 I := CompiledScriptContents.IndexOfName(FunctionName);
139 if I <> -1 then
140 Scene.ExecuteCompiledScript(CompiledScriptContents.ValueFromIndex[I], ReceivedValue) else
141 if CompiledScriptContents.IndexOf(FunctionName) <> -1 then
142 { If FunctionName exists, without any value, then just execute
143 the handler of the same name. }
144 Scene.ExecuteCompiledScript(FunctionName, ReceivedValue);
145 end;
146 stCastleScript:
147 begin
148 { ReceivedValue may be nil for initialize/shutdown calls. }
149 if ReceivedValue <> nil then
150 begin
151 ParameterValue := X3DCasScriptCreateValue(ReceivedValue);
152 X3DCasScriptBeforeExecute(ParameterValue, ReceivedValue);
153 end else
154 ParameterValue := nil;
155 { Note: it's not really important whether below we'd use
156 Scene.Time or Time.Seconds. }
157 ParameterTime := TCasScriptFloat.Create(true, Scene.Time);
158 try
159 CastleScriptVariables.BeforeExecute;
160 try
161 if ParameterValue <> nil then
162 CastleScriptProgram.ExecuteFunction(FunctionName,
163 [ ParameterValue, ParameterTime ], true) else
164 CastleScriptProgram.ExecuteFunction(FunctionName,
165 [ ParameterTime ], true);
166 except
167 on E: ECasScriptError do
168 begin
169 WritelnWarning('X3D', 'Error when executing CastleScript: ' + E.Message);
170 Exit;
171 end;
172 end;
173
174 { X3DCasScriptAfterExecute(ParameterValue, ...) is not called,
175 we don't want
176 to propagate changes to parameter in script to ReceivedValue.
177 ReceivedValue should not be even changed by event handler.
178 Actually, ParameterValue could be constant in script
179 (not Writeable), but we allow it to be writeable now, for local
180 changes by user (may be comfortable sometimes). }
181
182 CastleScriptVariables.AfterExecute(Time);
183 finally
184 FreeAndNil(ParameterValue);
185 FreeAndNil(ParameterTime)
186 end;
187 end;
188 {$ifndef COMPILER_CASE_ANALYSIS}
189 else raise EInternalError.Create('Unknown script type initialized');
190 {$endif}
191 end;
192 end;
193 end;
194
195 procedure TAbstractScriptNode.SetInitialized(const Value: boolean);
196
197 { @raises(ECasScriptSyntaxError in case of program parsing error
198 (we just let through ECasScriptSyntaxError from ParseProgram).) }
199 procedure CastleScriptInitialize(const ProgramContent: string);
200 var
201 I: Integer;
202 begin
203 FreeAndNil(CastleScriptProgram);
204 FreeAndNil(CastleScriptVariables);
205
206 CastleScriptVariables := TCasScriptX3DValueList.Create(true);
207
208 { Add fields and output events (coming from interface decl,
209 not normal Script fields/events) to CastleScriptVariables. }
210
211 for I := 0 to FieldsCount - 1 do
212 if Fields[I].ParentInterfaceDeclaration <> nil then
213 CastleScriptVariables.Add(Fields[I]);
214
215 for I := 0 to EventsCount - 1 do
216 if (not Events[I].InEvent) and
217 (Events[I].ParentInterfaceDeclaration <> nil) then
218 CastleScriptVariables.Add(Events[I]);
219
220 CastleScriptProgram := ParseProgram(ProgramContent, CastleScriptVariables);
221 CastleScriptProgram.Environment.BaseUrl := BaseUrl;
222 end;
223
224 function LoadUrl(Url: String; var FailedUrlsLog: string): boolean;
225 var
226 ScriptContents, MimeType: string;
227 ScriptContentsStream: TStream;
228 begin
229 Result := false;
230 try
231 ScriptContentsStream := Download(URL, [], MimeType);
232 try
233
234 if (MimeType = 'application/javascript') or // MIME official in RFC
235 (MimeType = 'text/javascript') or // MIME common in HTML
236 (MimeType = 'application/x-javascript') or // MIME commonly returned by http servers
237 (MimeType = 'text/ecmascript') or // MIME suggested by SVG
238 (MimeType = 'text/plain') then // MIME accepted just in case, discouraged
239 { see about MIMEs:
240 http://stackoverflow.com/questions/189850/what-is-the-javascript-mime-type-what-belongs-in-the-type-attribute-of-a-script
241 http://annevankesteren.nl/2005/02/javascript-mime-type }
242 begin
243 WritelnWarning('X3D', Format(
244 'ECMAScript is not yet implemented, ignoring URL "%s"',
245 [UriDisplay(URL)]));
246 end else
247
248 if MimeType = 'text/x-castlescript' then
249 begin
250 ScriptContents := ReadGrowingStreamToString(ScriptContentsStream);
251 CastleScriptInitialize(ScriptContents);
252
253 Result := true;
254 FInitializedScriptType := stCastleScript;
255 end else
256
257 if MimeType = 'text/x-castle-compiled' then
258 begin
259 ScriptContents := ReadGrowingStreamToString(ScriptContentsStream);
260
261 FreeAndNil(CompiledScriptContents);
262 CompiledScriptContents := TStringList.Create;
263 CompiledScriptContents.Text := ScriptContents;
264
265 Result := true;
266 FInitializedScriptType := stCompiled;
267 end else
268
269 begin
270 WritelnWarning('X3D', Format(
271 'Script MIME type not recognized in URL "%s": %s',
272 [UriDisplay(URL), MimeType]));
273 end;
274
275 finally FreeAndNil(ScriptContentsStream) end;
276 except
277 { Catch exceptions from Download and CastleScriptInitialize }
278 on E: Exception do
279 WritelnWarning('X3D', Format(
280 'Exception %s when loading Script from URL "%s": %s',
281 [E.ClassName, UriDisplay(URL), E.Message ]));
282 end;
283
284 // if Result and Log and LogScript then
285 // WritelnLog('Script', Format('Loaded from URL "%s"', [UriDisplay(URL)]));
286 end;
287
288 var
289 ValidUrlFound: boolean;
290 I: Integer;
291 FailedUrlsLog: string;
292 begin
293 if FInitialized <> Value then
294 begin
295 if Value then
296 begin
297 ValidUrlFound := false;
298 FailedUrlsLog := '';
299
300 for I := 0 to FdUrl.Items.Count - 1 do
301 begin
302 if LoadUrl(PathFromBaseUrl(FdUrl.Items[I]), FailedUrlsLog) then
303 begin
304 ValidUrlFound := true;
305 Break;
306 end;
307 end;
308
309 if ValidUrlFound then
310 begin
311 FInitialized := Value;
312 ExecuteScript('initialize', nil, Scene.NextEventTime);
313 end else
314 begin
315 if FailedUrlsLog <> '' then
316 FailedUrlsLog := ' (' + FailedUrlsLog + ')';
317 WritelnWarning('X3D', 'Script node ignored: no supported protocol found' + FailedUrlsLog);
318 end;
319 end else
320 begin
321 ExecuteScript('shutdown', nil, Scene.NextEventTime);
322 FInitialized := Value;
323 end;
324 end;
325 end;
326
327 procedure TAbstractScriptNode.ResetLastEventTimes;
328 begin
329 if Initialized and (FInitializedScriptType = stCastleScript) then
330 CastleScriptVariables.ResetLastEventTimes;
331 end;
332
333 { TScriptNode ---------------------------------------------------------------- }
334
335 procedure TScriptNode.PostAddInterfaceDeclaration(
336 IDecl: TX3DInterfaceDeclaration);
337 begin
338 inherited;
339
340 if (IDecl.Event <> nil) and IDecl.Event.InEvent then
341 IDecl.Event.AddNotification({$ifdef FPC}@{$endif} IDeclEventReceive) else
342 if (IDecl.Field <> nil) and IDecl.Field.Exposed then
343 IDecl.Field.AddNotification({$ifdef FPC}@{$endif} IDeclEventReceive);
344 end;
345
346 procedure TScriptNode.IDeclEventReceive(
347 const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime);
348 var
349 FunctionName: string;
350 begin
351 if Event.ParentExposedField <> nil then
352 FunctionName := Event.ParentExposedField.X3DName
353 else
354 FunctionName := Event.X3DName;
355 ExecuteScript(FunctionName, Value, Time);
356 end;
357
358 procedure RegisterScriptingNodes;
359 begin
360 NodesManager.RegisterNodeClasses([
361 TScriptNode
362 ]);
363 end;
364
365 {$endif read_implementation}