Debian Codegraph @

src/base_rendering/castleinternalcontextwgl.pas

raw
1 {
2 Copyright 2013-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 { Initializes OpenGL context using Windows WGL. }
17 unit CastleInternalContextWgl;
18
19 {$i castleconf.inc}
20
21 interface
22
23 {$ifndef MSWINDOWS}
24 { To make it easier to organize Lazarus packages
25 (to keep this unit in castle_base.lpk, since it doesn't depend on TCastleWindow,
26 but at the same time this unit cannot have "<AddToUsesPkgSection Value="False"/>"
27 in castle_base.lpk because castle_window.lpk expects to use this unit
28 without recompiling...) ->
29 this unit compiles even for platforms that don't have wgl (non-Windows),
30 the unit just doesn't define anything in this case. }
31 implementation
32 end.
33 {$else}
34
35 uses Windows, SysUtils, Classes,
36 CastleVectors, CastleRenderOptions, CastleInternalContextBase;
37
38 type
39 { OpenGL context created using Windows-specific wgl library. }
40 TGLContextWGL = class(TGLContext)
41 private
42 class var
43 WndClassName: UnicodeString;
44 class procedure NeedsWndClassName;
45 protected
46 procedure InitializeCore(const Requirements: TGLContextRequirements); override;
47 procedure FinalizeCore; override;
48 procedure MakeCurrentCore; override;
49 procedure SwapBuffersCore; override;
50 public
51 { Note about WndPtr:
52 We actually ignore it in the current implementation. Only h_Dc is used.
53 But we still define the field and require to set it (we assert it is <> 0),
54 because
55
56 - in all practical cases, you *have* HWND when using this,
57 no significant benefit from not requiring it.
58 - and it is consistent with EGL that only uses WinPtr.
59 - and it may be again useful in the future -- this is actually the major
60 argument. It is very likely to be useful for something in the future,
61 since so much WinAPI works with HWND,
62 and it would be detrimental having to readd it later,
63 after removing it now. }
64
65 // Set this before using Initialize and other methods
66 WndPtr: HWND;
67 h_Dc: HDC;
68
69 // Created by Initialize, destroyed by Finalize
70 h_GLRc: HGLRC;
71 end;
72
73 implementation
74
75 uses {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
76 CastleUtils, CastleStringUtils, CastleGLUtils, CastleInternalGLUtils, CastleLog;
77
78 { TGLContextWGL -------------------------------------------------------------- }
79
80 procedure TGLContextWGL.InitializeCore(const Requirements: TGLContextRequirements);
81
82 { Both SetPixelFormat* set pixel format (required context capabilities)
83 of Windows H_Dc device context. They try to set it, and eventually raise some
84 exception (e.g. by CheckRequestedBufferAttributes) if it's not possible.
85
86 SetPixelFormat_WGLChoose tries to use wglChoosePixelFormat, which is generally
87 much better, more flexible, most of all: it allows to set multisampling
88 parameters, which is not possible by classic ChoosePixelFormat.
89
90 But wglChoosePixelFormat is not guaranteed to exist, so if it doesn't --- we
91 fall back on classic ChoosePixelFormat (and DescribePixelFormat) by calling
92 SetPixelFormat_ClassicChoose. }
93 procedure SetPixelFormat_ClassicChoose;
94 var
95 PixelFormat: Int32;
96 pfd: Tpixelformatdescriptor;
97 begin
98 FillChar(pfd, SizeOf(pfd), 0);
99 with pfd do
100 begin
101 nSize := SizeOf(TPIXELFORMATDESCRIPTOR);
102 nVersion := 1;
103 dwFlags := PFD_DRAW_TO_WINDOW // Format Must Support Window
104 or PFD_SUPPORT_OPENGL; // Format Must Support OpenGL
105 if Requirements.DoubleBuffer then dwFlags := dwFlags or PFD_DOUBLEBUFFER;
106 iPixelType := PFD_TYPE_RGBA; // Request An RGBA Format
107 cColorBits := Requirements.ColorBits; // WinAPI accepts here 0 as "default"
108 cAlphaBits := Requirements.AlphaBits;
109 cDepthBits := Requirements.DepthBits;
110 cStencilBits := Requirements.StencilBits;
111 iLayerType := PFD_MAIN_PLANE; // Main Drawing Layer
112 end;
113 PixelFormat := Windows.ChoosePixelFormat(h_Dc, {$ifndef FPC}@{$endif}pfd);
114 OSCheck( PixelFormat <> 0, 'ChoosePixelFormat');
115
116 { Check if we got required AlphaBits, DepthBits, StencilBits -
117 because ChoosePixelFormat doesn't guarantee it.
118
119 In the future, I may switch to using SetPixelFormat_WGLChoose by default.
120 wglChoosePixelFormatARB makes CheckRequestedBufferAttributes not needed
121 (as wglChoosePixelFormatARB already sensibly guarantees that GL context will
122 satisfy appropriate limits).
123 So this un-elegant code below will not be used (on modern Windowses / GPUs). }
124 DescribePixelFormat(h_Dc, PixelFormat, SizeOf(pfd), pfd);
125 Requirements.CheckRequestedBufferAttributes('ChoosePixelFormat',
126 pfd.cStencilBits, pfd.cDepthBits, pfd.cAlphaBits,
127 0 { we have to assume that ChoosePixelFormat returns context
128 without multisampling abiilty });
129
130 { Since PixelFormat is OK, set it.
131 Passing pfd below is not necessary, as far as I understoon WinAPI docs.
132 It's important to pass PixelFormat. }
133 OSCheck( SetPixelFormat(h_Dc, PixelFormat, @pfd), 'SetPixelFormat');
134 end;
135
136 procedure SetPixelFormat_WGLChoose;
137 var
138 Temp_h_GLRc: HGLRC;
139 Temp_h_Dc: HDC;
140 Temp_h_Wnd: HWND;
141
142 { We have to create temporary window, just to query wgl. It's useless to
143 call wglGetProcAddress without any GL context active.
144 It is quite weird to create a window just to query wgl extensions,
145 but that's effectively what every program using wgl has to do.
146
147 We create this temporary window with absolutely standard, minumum
148 properties --- any system (supporting OpenGL at all) should
149 be able to create our CreateTemporaryWindow. }
150
151 procedure DestroyTemporaryWindow; forward;
152
153 procedure CreateTemporaryWindow;
154 var
155 PixelFormat: Int32;
156 pfd: Tpixelformatdescriptor;
157 begin
158 NeedsWndClassName;
159
160 Temp_h_Wnd := 0;
161 Temp_h_Dc := 0;
162 Temp_h_GLRc := 0;
163
164 try
165 { create Temp_H_wnd }
166 Temp_H_wnd := CreateWindowExW(WS_EX_APPWINDOW or WS_EX_WINDOWEDGE,
167 PWideChar(WndClassName),
168 PWideChar(StringToUtf16('Temporary window to query WGL extensions')),
169 WS_OVERLAPPEDWINDOW or WS_CLIPSIBLINGS or WS_CLIPCHILDREN,
170 0, 0, 100, 100,
171 0 { no parent window }, 0 { no menu }, hInstance,
172 nil { don't pass anything to WM_CREATE } );
173 Check( Temp_H_Wnd <> 0, 'Creating temporary window (CreateWindowExW) to query WGL extensions failed');
174
175 { create Temp_h_Dc }
176 Temp_h_Dc := GetDC(Temp_h_Wnd);
177 Check ( Temp_h_Dc <> 0, 'GetDC failed');
178
179 { create and set PixelFormat (must support OpenGL to be able to
180 later do wglCreateContext) }
181 FillChar(pfd, SizeOf(pfd), 0);
182 with pfd do
183 begin
184 nSize := SizeOf(TPIXELFORMATDESCRIPTOR);
185 nVersion := 1;
186 dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL;
187 iPixelType := PFD_TYPE_RGBA;
188 iLayerType := PFD_MAIN_PLANE;
189 end;
190 PixelFormat := Windows.ChoosePixelFormat(Temp_h_Dc, {$ifndef FPC}@{$endif}pfd);
191 OSCheck( PixelFormat <> 0, 'ChoosePixelFormat');
192 OSCheck( SetPixelFormat(Temp_h_Dc, PixelFormat, @pfd), 'SetPixelFormat');
193
194 { create and make current Temp_h_GLRc }
195 Temp_h_GLRc := wglCreateContext(Temp_h_Dc);
196 OSCheck( Temp_h_GLRc <> 0, 'wglCreateContext' );
197 OSCheck( wglMakeCurrent(Temp_h_Dc, Temp_h_GLRc), 'wglMakeCurrent');
198 except
199 { make sure to finalize all partially initialized window parts }
200 DestroyTemporaryWindow;
201 raise;
202 end;
203 end;
204
205 procedure DestroyTemporaryWindow;
206 begin
207 if Temp_h_GLRc <> 0 then
208 begin
209 wglMakeCurrent(Temp_h_Dc, 0);
210 wglDeleteContext(Temp_h_GLRc);
211 Temp_h_GLRc := 0;
212 end;
213
214 if Temp_h_Dc <> 0 then
215 begin
216 ReleaseDC(Temp_h_Wnd, Temp_h_Dc);
217 Temp_h_Dc := 0;
218 end;
219
220 if Temp_h_Wnd <> 0 then
221 begin
222 DestroyWindow(Temp_h_Wnd);
223 Temp_h_Wnd := 0;
224 end;
225 end;
226
227 var
228 PixelFormat: Int32;
229 ReturnedFormats: UINT;
230 VisualAttr: TInt32List;
231 VisualAttrFloat: array [0..1] of Single;
232 Success: WINBOOL;
233 begin
234 CreateTemporaryWindow;
235 try
236 { Note: CastleGL unit ReadImplementationProperties looks at wglGetCurrentDC
237 (this is passed to wglGetExtensionsStringARB call).
238 That's Ok, this current context is set by our CreateTemporaryWindow. }
239
240 ReadImplementationProperties;
241 ReadExtensions; // read extension entry points like wglChoosePixelFormatARB
242
243 if WGL_ARB_extensions_string then
244 begin
245 if WGL_ARB_pixel_format then
246 begin
247 { Ok, wglChoosePixelFormatARB is available }
248
249 VisualAttr := TInt32List.Create;
250 try
251 VisualAttr.AddRange([
252 WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
253 WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
254 { If indexed mode will be implemented in CastleWindow one day, this can take
255 WGL_TYPE_COLORINDEX_ARB instead of WGL_TYPE_RGBA_ARB. }
256 WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
257 WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB]);
258 if Requirements.DoubleBuffer then
259 VisualAttr.AddRange([WGL_DOUBLE_BUFFER_ARB, GL_TRUE]);
260 VisualAttr.AddRange([
261 WGL_RED_BITS_ARB, Requirements.RedBits,
262 WGL_GREEN_BITS_ARB, Requirements.GreenBits,
263 WGL_BLUE_BITS_ARB, Requirements.BlueBits,
264 WGL_DEPTH_BITS_ARB, Requirements.DepthBits,
265 WGL_STENCIL_BITS_ARB, Requirements.StencilBits,
266 WGL_ALPHA_BITS_ARB, Requirements.AlphaBits
267 ]);
268
269 if Requirements.MultiSampling > 1 then
270 begin
271 if WGL_ARB_multisample then
272 begin
273 VisualAttr.AddRange([
274 WGL_SAMPLE_BUFFERS_ARB, 1,
275 WGL_SAMPLES_ARB, Requirements.MultiSampling ]);
276 WritelnLog('MultiSampling', 'WGL_ARB_multisample supported, using multisampling');
277 end else
278 raise EGLContextNotPossible.CreateFmt('Multisampling (%d samples) ' +
279 'requested, but WGL_ARB_multisample not supported',
280 [Requirements.MultiSampling]);
281 end;
282
283 { end of VisualAttr array }
284 VisualAttr.AddRange([0, 0]);
285
286 FillChar(VisualAttrFloat, SizeOf(VisualAttrFloat), 0);
287
288 Success := wglChoosePixelFormatARB(H_Dc, PGLint(VisualAttr.L),
289 @VisualAttrFloat[0], 1, @PixelFormat, @ReturnedFormats);
290 finally FreeAndNil(VisualAttr) end;
291
292 if Success and (ReturnedFormats >= 1) then
293 begin
294 { We could use wglGetPixelFormatAttribivARB (equivalent to "classic"
295 DescribePixelFormat) here to query context we got, and call
296 CheckRequestedBufferAttributes to check whether we really got what
297 we requested.
298
299 But we don't have to: wglChoosePixelFormatARB (see
300 [http://www.opengl.org/registry/specs/ARB/wgl_pixel_format.txt])
301 clearly specifies which limits are "exact", which are "minimum",
302 and we're actually perfectly satisfied with this.
303
304 So, we're done now :) Just set this pixel format. }
305 OSCheck( SetPixelFormat(h_Dc, PixelFormat, nil), 'SetPixelFormat');
306 end else
307 raise EGLContextNotPossible.CreateFmt(
308 'wglChoosePixelFormatARB: pixel format with requested attributes (%s) not found',
309 [ Requirements.RequestedBufferAttributes ]);
310 end else
311 begin
312 WritelnLog('wgl', 'WGL_ARB_pixel_format not available, using classic ChoosePixelFormat');
313 SetPixelFormat_ClassicChoose;
314 end;
315 end else
316 begin
317 WritelnLog('wgl', 'wglGetExtensionsStringARB not available, using classic ChoosePixelFormat');
318 SetPixelFormat_ClassicChoose;
319 end;
320 finally DestroyTemporaryWindow end;
321 end;
322
323 procedure UseCreateContextAttribsARB;
324 var
325 Attribs: TInt32List;
326 ShareContextGlrc: HGLRC;
327 begin
328 // WritelnLog('wgl', 'Initializing Windows OpenGL context using modern wglCreateContextAttribsARB, good'); // too verbose
329
330 Attribs := TInt32List.Create;
331 try
332 { Select 3.2 core context.
333 See https://registry.khronos.org/OpenGL/extensions/ARB/WGL_ARB_create_context.txt
334 https://www.khronos.org/opengl/wiki/Creating_an_OpenGL_Context_(WGL) }
335 if TGLFeatures.RequestCapabilities = rcForceModern then
336 begin
337 Attribs.AddRange([
338 WGL_CONTEXT_MAJOR_VERSION_ARB, TGLFeatures.ModernVersionMajor,
339 WGL_CONTEXT_MINOR_VERSION_ARB, TGLFeatures.ModernVersionMinor,
340 WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB
341 { Not used, following https://www.khronos.org/opengl/wiki/OpenGL_Context#Context_types
342 forward-compatible really only makes sense on macOS.
343 The "core" profile is what should be just used with new OpenGLs on sane
344 (non-macOS) platforms. }
345 //WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
346 ]);
347 end;
348 { Select debug context.
349 Note that the implementation assumes nothing above passes WGL_CONTEXT_FLAGS_ARB. }
350 if TGLFeatures.Debug then
351 begin
352 Attribs.AddRange([
353 WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB
354 ]);
355 end;
356 Attribs.AddRange([0]);
357 Assert(SizeOf(TGLint) = SizeOf(Int32)); // make sure Attribs match PGLint type
358
359 if SharedContext <> nil then
360 ShareContextGlrc := (SharedContext as TGLContextWGL).h_GLRc
361 else
362 ShareContextGlrc := 0;
363
364 h_GLRc := wglCreateContextAttribsARB(h_Dc, ShareContextGlrc, PGLint(Attribs.L));
365 OSCheck(h_GLRc <> 0, 'wglCreateContextAttribsARB');
366 finally FreeAndNil(Attribs) end;
367 end;
368
369 procedure UseCreateContext;
370 begin
371 { create gl context and make it current }
372 h_GLRc := wglCreateContext(h_Dc);
373 OSCheck(h_GLRc <> 0, 'wglCreateContext');
374
375 { We need wglShareLists.
376 Testcase: see if examples/window/multi_window.lpr
377 shows font in all windows. }
378 if SharedContext <> nil then
379 OSCheck(wglShareLists((SharedContext as TGLContextWGL).h_GLRc, h_GLRc), 'wglShareLists');
380 end;
381
382 begin
383 // make sure caller didn't forget to set these before calling CreateContext
384 Assert(WndPtr <> 0);
385 Assert(h_Dc <> 0);
386
387 // load base (not extensions) WGL functions
388 if GL_LibHandle = nil then
389 InitOpenGL;
390
391 SetPixelFormat_WGLChoose;
392
393 { Note that SetPixelFormat_WGLChoose setup temporary context
394 and called ReadImplementationProperties
395 and thus initialized WGL_ARB_xxx. }
396
397 if (GetDeviceCaps(h_Dc, RASTERCAPS) and RC_PALETTE) <> 0 then
398 raise EGLContextNotPossible.Create('This device is paletted, bad display settings');
399
400 if WGL_ARB_create_context and
401 WGL_ARB_create_context_profile then
402 UseCreateContextAttribsARB
403 else
404 UseCreateContext;
405 end;
406
407 procedure TGLContextWGL.FinalizeCore;
408 begin
409 if h_GLRc <> 0 then
410 begin
411 if (not wglMakeCurrent(h_Dc, 0)) then
412 WritelnWarning('WinAPI', 'Deactivating current OpenGL rendering context (wglMakeCurrent(..., NULL)) failed.');
413 if (not wglDeleteContext(h_GLRc)) then
414 WritelnWarning('WinAPI', 'Releasing current OpenGL rendering context (wglDeleteContext) failed.');
415 h_GLRc := 0;
416 end;
417 end;
418
419 procedure TGLContextWGL.MakeCurrentCore;
420 begin
421 Assert(h_GLRc <> 0); // this is called only when Initialized
422 OSCheck( wglMakeCurrent(h_Dc, h_GLRc), 'wglMakeCurrent');
423 end;
424
425 procedure TGLContextWGL.SwapBuffersCore;
426 begin
427 Assert(h_GLRc <> 0); // this is called only when Initialized
428 Windows.SwapBuffers(h_Dc);
429 end;
430
431 { Handler for events for our temporary window.
432 Does nothing for now, we could as well pass
433 WindowClass.lpfnWndProc := @DefWindowProcW;
434 but maybe there will be a need to handle something here some day. }
435 function WndProc(hWnd: HWND; uMsg: UINT; wParm: WPARAM; lParm: LPARAM): LRESULT; stdcall;
436 begin
437 result := DefWindowProcW(hWnd, uMsg, wParm, lParm);
438 end;
439
440 class procedure TGLContextWGL.NeedsWndClassName;
441 var
442 WindowClass: TWndClassW;
443 begin
444 if WndClassName = '' then
445 begin
446 { Register minimal window class, just to create temporary WinAPI window
447 to query WGL extensions.
448 See https://www.khronos.org/opengl/wiki/Creating_an_OpenGL_Context_(WGL) }
449
450 WndClassName := 'TGLContextWGL';
451
452 FillChar(WindowClass, SizeOf(WindowClass), 0);
453 WindowClass.style := CS_OWNDC;
454 WindowClass.lpfnWndProc := @WndProc;
455 WindowClass.hInstance := hInstance;
456 WindowClass.lpszClassName := PWideChar(WndClassName);
457 OSCheck( RegisterClassW(WindowClass) <> 0, 'RegisterClassW');
458 end;
459 end;
460
461 end.
462
463 {$endif}