Debian Codegraph @

src/delphi/castleinternalcontainer.pas

raw
1 {
2 Copyright 2022-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Container class TCastleContainerEasy,
17 that is easier to use than TCastleContainer.
18 In particular it relies on
19
20 - private OpenGL(ES) context handled by TGLContext descendants
21
22 - with requirements expressed by public TGLContextRequirements.
23
24 TODO: It is our long-term plan to merge TCastleContainerEasy capabilities
25 into TCastleContainer. Thus, the implementation done here will be shared
26 by TCastleWindow (all backends) and LCL TCastleControl,
27 unifying them more.
28 Right now, TCastleWindow and LCL TCastleControl do some things manually
29 for historic purposes, e.g. they expose GL context requirements
30 like TCastleWindow.DepthBits,
31 and they expose callbacks like TCastleWindow.OnRender that we don't advise to use
32 (use TCastleView instead or TCastleUserInterface.OnRender to do rendering).
33 Nowadays we know that
34
35 - API of classes like TCastleWindow / TCastleControl should be simpler and just expose
36 Container for everything reasonable.
37
38 - Container also should delegate to TCastleView and in turn to TCastleUserInterface
39 for everything reasonable.
40
41 }
42 unit CastleInternalContainer;
43
44 {$I castleconf.inc}
45
46 interface
47
48 uses Classes, Generics.Collections,
49 {$ifdef MSWINDOWS} CastleInternalContextWgl, {$endif}
50 {$ifdef LINUX} CastleInternalContextEgl, {$endif}
51 CastleRectangles, CastleImages,
52 CastleUIControls, CastleInternalContextBase;
53
54 type
55 TCastleContainerEasy = class(TCastleContainer)
56 strict private
57 FRequirements: TGLContextRequirements;
58 { Internal platform-specific context data and initialization/finalization.
59 This is in contrast to TCastleContainer.Context, that is public
60 and manages context properties that are cross-platform and available
61 for all OpenGL(ES). }
62 FPlatformContext: TGLContext;
63 FGLInitialized: Boolean;
64 FAutoRedisplay: Boolean;
65 { Copy of Requirements.DoubleBuffer when the context was created. }
66 FEffectiveDoubleBuffer: Boolean;
67 FDesignUrl: String;
68 FDesignLoaded: TCastleUserInterface;
69 FDesignLoadedOwner: TComponent;
70 procedure SetAutoRedisplay(const Value: Boolean);
71 procedure DoUpdate;
72 procedure SetDesignUrl(const Value: String);
73 procedure LoadDesign;
74 procedure UnLoadDesign;
75 protected
76 { Adjust context parameters right before usage. }
77 procedure AdjustContext(const PlatformContext: TGLContext); virtual;
78
79 { Call these methods from final components that wrap TCastleContainerEasy,
80 like TCastleControl, TCastleWindow. }
81 procedure InitializeContext;
82 procedure FinalizeContext;
83 procedure DoRender;
84
85 class var
86 { "Updating" means that the mechanism to call DoUpdateEverything
87 continuosly is set up. }
88 UpdatingEnabled: Boolean;
89
90 class procedure DoUpdateEverything;
91 class procedure UpdatingEnable; virtual; abstract;
92 class procedure UpdatingDisable; virtual; abstract;
93 public
94 constructor Create(AOwner: TComponent); override;
95 destructor Destroy; override;
96 function SaveScreen(const SaveRect: TRectangle): TRGBImage; overload; override;
97
98 { Is OpenGL(ES) context initialized for this container. }
99 function GLInitialized: boolean; override;
100
101 { Make given OpenGL(ES) context current.
102 Can only be used if GLInitialized. }
103 procedure MakeContextCurrent;
104
105 { When the DesignUrl is set you can use this method to find
106 loaded components. Like this:
107
108 @longCode(#
109 MyButton := MyCastleControl.DesignedComponent('MyButton') as TCastleButton;
110 #)
111
112 When the name is not found, raises exception (unless Required is @false,
113 then it returns @nil).
114
115 @seealso DesignUrl }
116 function DesignedComponent(const ComponentName: String;
117 const Required: Boolean = true): TComponent;
118 published
119 { Should we automatically redraw the window all the time,
120 without the need for an @link(Invalidate) call.
121 If @true (the default), rendering and other processing will
122 be called constantly.
123
124 If your game may have a still screen (nothing animates),
125 then this approach is a little unoptimal, as we use CPU and GPU
126 for drawing, when it's not needed. In such case, you can set this
127 property to @false, and make sure that you call
128 @link(Invalidate) always when you need to redraw the screen.
129 Note that the engine components always call @link(Invalidate) when
130 necessary, so usually you should only call it yourself if you provide
131 a custom @link(OnRender) implementation. }
132 property AutoRedisplay: Boolean read FAutoRedisplay write SetAutoRedisplay
133 default true;
134
135 { Context required parameters. }
136 property Requirements: TGLContextRequirements read FRequirements;
137
138 { Load and show the design (.castle-user-interface file).
139 You can reference the loaded components by name using @link(DesignedComponent).
140
141 If you have more complicated control flow,
142 we recommend to leave this property empty, and split your management
143 into a number of states (TCastleView) instead.
144 In this case, load design using TCastleView.DesignUrl.
145 This property makes it however easy to use .castle-user-interface
146 in simple cases, e.g. when TCastleControl just shows one UI.
147
148 The design loaded here is visible also at design-time,
149 when editing the form in Lazarus/Delphi.
150 Though we have to way to edit it now in Lazarus/Delphi (you have to use CGE editor
151 to edit the design), so it is just a preview in this case.
152
153 See https://castle-engine.io/control_on_form for documentation how to use TCastleControl. }
154 property DesignUrl: String read FDesignUrl write SetDesignUrl;
155 end;
156
157 TCastleContainerEasyList = {$ifdef FPC}specialize{$endif} TObjectList<TCastleContainerEasy>;
158
159 implementation
160
161 uses SysUtils,
162 CastleRenderContext, CastleGLUtils, CastleApplicationProperties, CastleGLImages,
163 CastleGLVersion, CastleTimeUtils, CastleUtils, CastleLog, CastleUriUtils,
164 CastleComponentSerialize, CastleInternalDelphiUtils, CastleFilesUtils;
165
166 var
167 { All TCastleContainerEasy instances created. }
168 ContainersList: TCastleContainerEasyList;
169
170 LastLimitFPSTime: TTimerResult;
171
172 constructor TCastleContainerEasy.Create(AOwner: TComponent);
173 begin
174 inherited;
175
176 FRequirements := TGLContextRequirements.Create(Self);
177 FRequirements.Name := 'Requirements';
178 FRequirements.SetSubComponent(true);
179
180 FPlatformContext := ContextCreateBestInstance;
181
182 FAutoRedisplay := true;
183
184 ContainersList.Add(Self);
185 end;
186
187 destructor TCastleContainerEasy.Destroy;
188 begin
189 UnLoadDesign;
190 FreeAndNil(FPlatformContext);
191 if ContainersList <> nil then
192 ContainersList.Remove(Self);
193 inherited;
194 end;
195
196 procedure TCastleContainerEasy.MakeContextCurrent;
197 begin
198 Assert(GLInitialized);
199 RenderContext := Context;
200 FPlatformContext.MakeCurrent;
201 end;
202
203 function TCastleContainerEasy.SaveScreen(const SaveRect: TRectangle): TRGBImage;
204
205 { Color buffer where we draw, and from which it makes sense to grab pixels. }
206 function SaveScreenBuffer: TColorBuffer;
207 begin
208 if FEffectiveDoubleBuffer then
209 Result := cbBack
210 else
211 Result := cbFront;
212 end;
213
214 begin
215 MakeContextCurrent;
216 EventBeforeRender;
217 EventRender;
218 Result := SaveScreen_NoFlush(Rect, SaveScreenBuffer);
219 end;
220
221 procedure TCastleContainerEasy.InitializeContext;
222 begin
223 if not FGLInitialized then
224 begin
225 FGLInitialized := true;
226
227 AdjustContext(FPlatformContext);
228
229 FPlatformContext.Initialize(FRequirements);
230
231 FEffectiveDoubleBuffer := Requirements.DoubleBuffer;
232
233 // initialize CGE OpenGL resources
234 MakeContextCurrent;
235 GLInformationInitialize;
236 RenderContext.Viewport := Rect;
237 ApplicationProperties._GLContextEarlyOpen;
238
239 // Note that this will cause ApplicationProperties._GLContextOpen if necessary
240 EventOpen(TGLContext.InitializedContextsCount);
241 EventResize;
242 Invalidate;
243
244 // do this even at design-time, to allow animating in Delphi IDE
245 if {(not (csDesigning in ComponentState)) and} (not UpdatingEnabled) then
246 begin
247 UpdatingEnabled := true;
248 UpdatingEnable;
249 end;
250 end;
251 end;
252
253 procedure TCastleContainerEasy.AdjustContext(const PlatformContext: TGLContext);
254 begin
255 end;
256
257 procedure TCastleContainerEasy.FinalizeContext;
258 begin
259 if FGLInitialized then
260 begin
261 EventClose(TGLContext.InitializedContextsCount);
262 FGLInitialized := false;
263 FPlatformContext.Finalize;
264
265 if UpdatingEnabled and (TGLContext.InitializedContextsCount = 0) then
266 begin
267 UpdatingEnabled := false;
268 UpdatingDisable;
269 end;
270 end;
271 inherited;
272 end;
273
274 function TCastleContainerEasy.GLInitialized: boolean;
275 begin
276 Result := FGLInitialized;
277 end;
278
279 procedure TCastleContainerEasy.DoRender;
280 begin
281 MakeContextCurrent;
282
283 EventBeforeRender;
284 Fps.InternalRenderBegin;
285 try
286 EventRender;
287 if GLVersion.BuggySwapNonStandardViewport then
288 RenderContext.Viewport := Rect;
289 FPlatformContext.SwapBuffers;
290
291 // Note that calling Invalidate from RenderContext is not allowed,
292 // it doesn't play OK with LCL or VCL.
293 // if AutoRedisplay then Invalidate;
294 finally Fps.InternalRenderEnd end;
295 end;
296
297 procedure TCastleContainerEasy.DoUpdate;
298 begin
299 if AutoRedisplay then
300 Invalidate;
301
302 { Update event also requires that proper OpenGL context is current.
303
304 This matters because OpenGL resources may be used durign update,
305 e.g. TCastleScene.Update will update auto-generated textures,
306 doing e.g. TGLGeneratedCubeMapTextureNode.Update.
307 This should run in proper OpenGL context.
308 Esp. as not all resources must be shared between contexts:
309 FBO are not shared in new OpenGL versions, see
310 https://stackoverflow.com/questions/4385655/is-it-possible-to-share-an-opengl-framebuffer-object-between-contexts-threads
311
312 Testcase: open examples/mobile/simple_3d_demo/ in editor,
313 open main design,
314 click on previews with GeneratedCubeMap like castle_with_lights_and_camera.wrl .
315 Without this fix, we'll have an OpenGL error.
316
317 Doing MakeCurrent here is consistent with TCastleWindow.DoUpdate . }
318 MakeContextCurrent;
319 EventUpdate;
320 end;
321
322 procedure TCastleContainerEasy.SetAutoRedisplay(const Value: boolean);
323 begin
324 if FAutoRedisplay <> Value then
325 begin
326 FAutoRedisplay := value;
327 if Value then
328 Invalidate;
329 end;
330 end;
331
332 class procedure TCastleContainerEasy.DoUpdateEverything;
333
334 procedure DoLimitFPS;
335 var
336 NowTime: TTimerResult;
337 TimeRemainingFloat: Single;
338 begin
339 if ApplicationProperties.LimitFPS > 0 then
340 begin
341 NowTime := Timer;
342
343 { When this is run for the 1st time, LastLimitFPSTime is zero,
344 so NowTime - LastLimitFPSTime is huge, so we will not do any Sleep
345 and only update LastLimitFPSTime.
346
347 For the same reason, it is not a problem if you do not call DoLimitFPS
348 often enough (for example, you do a couple of ProcessMessage calls
349 without DoLimitFPS for some reason), or when user temporarily sets
350 LimitFPS to zero and then back to 100.0.
351 In every case, NowTime - LastLimitFPSTime will be large, and no sleep
352 will happen. IOW, in the worst case --- we will not limit FPS,
353 but we will *never* slow down the program when it's not really necessary. }
354
355 TimeRemainingFloat :=
356 { how long I should wait between _LimitFPS calls }
357 1 / ApplicationProperties.LimitFPS -
358 { how long I actually waited between _LimitFPS calls }
359 TimerSeconds(NowTime, LastLimitFPSTime);
360 { Don't do Sleep with too small values.
361 It's better to have larger FPS values than limit,
362 than to have them too small. }
363 if TimeRemainingFloat > 0.001 then
364 begin
365 Sleep(Round(1000 * TimeRemainingFloat));
366 LastLimitFPSTime := Timer;
367 end else
368 LastLimitFPSTime := NowTime;
369 end;
370 end;
371
372 var
373 I: Integer;
374 C: TCastleContainerEasy;
375 begin
376 { Be extra careful about processing here, so check ContainersList <> nil.
377
378 As this may run after our
379 "finalization" has run in case of VCL TCastleControl,
380 when ReportMemoryLeaksOnShutdown:=true is used.
381 In this case, the dialog shown by ReportMemoryLeaksOnShutdown happens
382 after our "finalization", but before
383 the TCastleControl.TContainer.UpdatingDisable from Vcl.CastleControl,
384 so before the TCastleControl lost GL context.
385 And during ReportMemoryLeaksOnShutdown, the WinAPI message loop runs,
386 making the TCastleControl timer execute.
387 }
388
389 if ContainersList <> nil then
390 for I := ContainersList.Count - 1 downto 0 do
391 begin
392 C := ContainersList[I];
393 if C.GLInitialized then
394 C.DoUpdate;
395 end;
396 if ApplicationProperties(false) <> nil then
397 begin
398 ApplicationProperties(false)._Update;
399
400 { For unknown reason, DoLimitFPS causes weird application freezes on FMXLinux.
401 Application update seems not to work, controls (both our OpenGL and
402 regular FMX) seem occasionally not rendered (esp. after window resize),
403 buttons react to clicks unreliably.
404
405 Note: in case of Linux, this code is only used when Delphi + Linux + FMX.
406 Because TCastleContainerEasy is only used with Delphi for FMX and VCL,
407 and on Linux only FMX is possible. }
408 {$ifndef LINUX}
409 DoLimitFPS;
410 {$endif}
411 end;
412
413 end;
414
415 procedure TCastleContainerEasy.LoadDesign;
416
417 { Note: implementation of LoadDesign, UnLoadDesign and friends follow similar
418 methods in TCastleView. Here they are much simplified, as we have no concept
419 of "started" / "stopped", so no DesignPreload too. }
420
421 procedure FixApplicationDataInIDE;
422 var
423 ProjectPath: String;
424 begin
425 if CastleDesignMode and
426 (csDesigning in ComponentState) and
427 Assigned(OnGetDesignTimeProjectPath) then
428 begin
429 ProjectPath := OnGetDesignTimeProjectPath();
430
431 { Override ApplicationData interpretation, and castle-data:/xxx URL meaning. }
432 ApplicationDataOverride := FilenameToUriSafe(
433 InclPathDelim(ProjectPath) + 'data' + PathDelim);
434 end;
435 end;
436
437 var
438 OldCastleApplicationMode: TCastleApplicationMode;
439 begin
440 if DesignUrl <> '' then
441 begin
442 { Make sure InternalCastleApplicationMode is correct, to
443 - not e.g. do physics in Lazarus/Delphi form designer.
444 - not show design-time stuff in DesignUrl loaded in CGE editor "help->system information".
445
446 Note that we restore later InternalCastleApplicationMode.
447 This way we avoid changing InternalCastleApplicationMode for future loads,
448 when TCastleControl is used inside castle-editor.
449 Testcase:
450 in CGE editor:
451 - open tools/castle-editor project
452 - double click on demo design in data/demo_animation/
453 - open help->system information (this uses TCastleControl too, with DesignUrl assigned)
454 - close help->system information
455 - close design
456 - reopen design
457 }
458 OldCastleApplicationMode := InternalCastleApplicationMode;
459 try
460 if csDesigning in ComponentState then
461 InternalCastleApplicationMode := appDesign
462 else
463 InternalCastleApplicationMode := appRunning;
464 FixApplicationDataInIDE; // in case DesignUrl uses castle-data: protocol, which is most often the case
465
466 FDesignLoadedOwner := TComponent.Create(nil);
467 try
468 FDesignLoaded := UserInterfaceLoad(DesignUrl, FDesignLoadedOwner);
469 except
470 { If loading design file failed, and we're inside form designer,
471 merely report a warning. This allows deserializing LFMs with broken URLs. }
472 on E: Exception do
473 begin
474 if CastleDesignMode then // looks at InternalCastleApplicationMode
475 begin
476 WritelnWarning('TCastleControl', 'Failed to load design "%s": %s', [
477 UriDisplay(DesignUrl),
478 ExceptMessage(E)
479 ]);
480 Exit;
481 end else
482 raise;
483 end;
484 end;
485 Controls.InsertFront(FDesignLoaded);
486 finally
487 InternalCastleApplicationMode := OldCastleApplicationMode;
488 end;
489 end;
490 end;
491
492 procedure TCastleContainerEasy.UnLoadDesign;
493 begin
494 FreeAndNil(FDesignLoadedOwner);
495 FDesignLoaded := nil; // freeing FDesignLoadedOwner must have freed this too
496 end;
497
498 procedure TCastleContainerEasy.SetDesignUrl(const Value: String);
499 begin
500 if FDesignUrl <> Value then
501 begin
502 UnLoadDesign;
503 FDesignUrl := Value;
504 LoadDesign;
505 end;
506 end;
507
508 function TCastleContainerEasy.DesignedComponent(const ComponentName: String;
509 const Required: Boolean = true): TComponent;
510 begin
511 if FDesignLoaded <> nil then
512 Result := FDesignLoadedOwner.FindComponent(ComponentName)
513 else
514 Result := nil;
515
516 if Required and (Result = nil) then
517 raise EComponentNotFound.CreateFmt('Cannot find component named "%s" in design "%s"', [
518 ComponentName,
519 UriDisplay(DesignUrl)
520 ]);
521 end;
522
523 initialization
524 {
525 // This is some way to debug behavior at design-time when this code runs as part of Delphi IDE.
526 // Uncomment to just have WritelnLog / WritelnWarning be recorded in the indicated file.
527 LogFileName := 'c:/cygwin64/home/michalis/log2.txt';
528 InitializeLog;
529 }
530
531 ContainersList := TCastleContainerEasyList.Create(false);
532 //TODO: InitializeClipboard;
533 //TODO: OnMainContainer := @TCastleControl(nil).GetMainContainer;
534 finalization
535 //TODO: OnMainContainer := nil;
536 FreeAndNil(ContainersList);
537 end.