Debian Codegraph @

src/base_rendering/castleglutils_features.inc

raw
1 {%MainUnit castleglutils.pas}
2 {
3 Copyright 2016-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 { Part of CastleGLUtils unit: TGLFeatures and friends. }
18
19 {$ifdef read_interface}
20
21 type
22 { Unused for now.
23 Was used to differentiate in TGLFeatures whether something is supported as core or extension,
24 but in the end -- this it not needed for anything now.
25 Maybe will be useful again in the future.
26 @exclude }
27 TGLSupport = (gsNone, gsExtension, gsStandard);
28
29 const
30 { Unused for now.
31 Was used to differentiate in TGLFeatures whether something is supported as core or extension,
32 but in the end -- this it not needed for anything now.
33 Maybe will be useful again in the future.
34 @exclude }
35 GLSupportNames: array [TGLSupport] of string =
36 ( 'None', 'Extension', 'Standard' );
37
38 type
39 { OpenGL memory information. }
40 TGLMemoryInfo = class
41 strict private
42 ExtensionNVidia, ExtensionATI: Boolean;
43 public
44 { Total and current memory available, in Kb.
45 May be zero if unknown (only some NVidia GPUs support this). }
46 Total, Current: TGLint;
47
48 { Current memory free for a particular feature, in Kb.
49 May be zero if unknown (only some AMD GPUs support this). }
50 CurrentVbo, CurrentTexture, CurrentRenderbuffer: TGLint;
51
52 constructor Create;
53 procedure Refresh;
54
55 { Detect GPUs with low texture memory.
56 Looks at @link(Current) or @link(CurrentTexture), whichever is available.
57
58 This is useful to detect at runtime when to use e.g. compressed textures
59 (S3TC and such) or downscaled textures (using @link(GLTextureScale) or
60 @link(TextureLoadingScale)). }
61 function LessTextureMemoryThan(const RequiredMemoryKb: Integer): Boolean;
62 end;
63
64 { OpenGL(ES) capabilities to request at context creation.
65 Use with @link(TGLFeatures.RequestCapabilities). }
66 TGLRequestCapabilities = (
67 { Use modern GPU code (shaders, VBO etc.) unless it is not possible
68 (not supported by GPU).
69 This is the default mode.
70
71 GLFeatures.EnableFixedFunction may be @false (preferred) or @true (fallback).
72
73 TODO: At some point, rcAutomatic will automatically require modern context
74 with deprecated functionality removed (just like rcForceModern)
75 and only fallback on non-modern context if that is not possible.
76 For now, rcAutomatic still initializes context with compatibility entry points
77 too, although it will not use them if the resulting context is modern.
78 We use flag rcForceModern to test whether the "modern (core) context with
79 deprecated stuff removed" is worth the hassle, i.e. is there a practical benefit
80 (measurable speedup / functionality boost) of not having compatibility entry points. }
81 rcAutomatic,
82
83 { Force using deprecated fixed-function even on modern GPUs.
84 Should only be used to test our fixed-function code,
85 never use this in production code -- you should always strive to use
86 modern GPU code.
87
88 GLFeatures.EnableFixedFunction will be always @true.
89
90 We will keep OpenGL API usage at 1.x, for large things (no shaders,
91 no VBO) and small things (like querying OpenGL extensions).
92 The goal is to really simulate ancient GPU, before shaders were part
93 of the OpenGL standard.
94
95 Not possible on OpenGLES, where CGE always uses modern shader pipeline. }
96 rcForceFixedFunction,
97
98 { Force initializing modern OpenGL context, with deprecated functionality
99 not available.
100
101 Modern context requires support for modern functionality (like shaders)
102 and may actually remove support for deprecated functionality (like fixed-function).
103 This may provide some additional speedup / functionality at some point
104 (but nothing you can really observe in practice, for now, in my experience).
105
106 Using this guarantees you always have GLFeatures.EnableFixedFunction = @false.
107
108 On platforms where we honor this flag at context creation (using glX etc.):
109 This even guarantees more: that at least OpenGL version 3.3
110 (TGLFeatures.ModernVersionMajor, TGLFeatures.ModernVersionMinor) is available.
111 In exchange, it really prohibits using any older deprecated OpenGL API.
112 So the code must, when Version_3_3 (or maybe from earlier versions for each
113 functionality), use new OpenGL API (and not any deprecated API).
114
115 The specifics what it does:
116 We try to initialize "core" profile of OpenGL version 3.3
117 (TGLFeatures.ModernVersionMajor, TGLFeatures.ModernVersionMinor). }
118 rcForceModern
119 );
120
121 const
122 CapabilitiesStr: array [TGLRequestCapabilities] of String = (
123 'automatic',
124 'force-fixed-function',
125 'force-modern'
126 );
127
128 type
129 { OpenGL(ES) features, analyzed based on extensions and version.
130 A single instance of this class is assigned to @link(GLFeatures)
131 after the first rendering context was created.
132 If you have multiple rendering contexts, our engine assumes they share resources
133 and have equal features. }
134 TGLFeatures = class
135 strict private
136 {$ifndef OpenGLES}
137 FVersion_1_2: Boolean;
138 FVersion_1_3: Boolean;
139 FVersion_1_4: Boolean;
140 FVersion_1_5: Boolean;
141 FVersion_2_0: Boolean;
142 FVersion_2_1: Boolean;
143 FVersion_3_0: Boolean;
144 FVersion_3_1: Boolean;
145 FVersion_3_2: Boolean;
146 FVersion_3_3: Boolean;
147 FVersion_4_0: Boolean;
148 {$else}
149 FVersionES_2_0: Boolean;
150 FVersionES_3_0: Boolean;
151 FVersionES_3_1: Boolean;
152 FVersionES_3_2: Boolean;
153 {$endif}
154 FTextureFilterAnisotropic: Boolean;
155 FNV_multisample_filter_hint: Boolean;
156 FOcclusionQuery: Boolean;
157 FCLAMP_TO_EDGE: TGLenum;
158 FMaxTextureSize: Cardinal;
159 FMaxLights: Cardinal;
160 FMaxCubeMapTextureSize: Cardinal;
161 FMaxTexture3DSize: Cardinal;
162 FMaxTextureMaxAnisotropy: Single;
163 FOcclusionQueryCounterBits: TGLint;
164 FMaxRenderbufferSize: TGLuint;
165 FMaxClipPlanes: Cardinal;
166 FMultisample: Boolean;
167 FMaxTextureUnitsFixedFunction: Cardinal;
168 FMaxTextureUnitsShaders: Cardinal;
169 FUseMultiTexturing: Boolean;
170 FTexture3D: Boolean;
171 FFramebuffer: Boolean;
172 FFramebufferBlit: Boolean;
173 FFBOMultiSampling: Boolean;
174 FCurrentMultiSampling: Cardinal;
175 FPackedDepthStencil: Boolean;
176 FShadowVolumesPossible: Boolean;
177 FTextureNonPowerOfTwo: Boolean;
178 FTextureCubeMap: Boolean;
179 FTextureCompression: TTextureCompressions;
180 FVertexBufferObject: Boolean;
181 FVertexArrayObject: Boolean;
182 FBlendConstant: Boolean;
183 FTextureFloat: Boolean;
184 FTextureDepth, FTextureDepthCompare: Boolean;
185 FShaders: Boolean;
186 FEnableFixedFunction: Boolean;
187 FMemory: TGLMemoryInfo;
188 FMaxViewportDimensions: TVector2Integer;
189 FTextureModernFormatsAndSwizzle: Boolean;
190 SupportedExtensions: AnsiString;
191 FRedBits, FGreenBits, FBlueBits, FAlphaBits, FDepthBits, FStencilBits: TGLint;
192 FDoubleBuffer: Boolean;
193 FLineWidth: TVector2;
194 FTextureMaxLevel: Boolean;
195 class var
196 FRequestCapabilities: TGLRequestCapabilities;
197 FDebug: Boolean;
198 class procedure SetRequestCapabilities(const Value: TGLRequestCapabilities); static;
199 class procedure SetDebug(const Value: Boolean); static;
200 private
201 function HasExtension(const Extension: String): Boolean;
202 function AllExtensions: String;
203 public
204 constructor Create;
205 destructor Destroy; override;
206
207 {$ifndef OpenGLES}
208 const
209 { OpenGL version considered "modern" for us,
210 that we can use with its "core" profile.
211
212 We need >= 3.2 as before it, there were no profiles (only "forward compatibility").
213
214 We need >= 3.3 as it has texture swizzle.
215 When we don't have texture swizzle,
216 then we cannot use modern OpenGL texture format constants,
217 and so we need compatibility.
218 See TextureModernFormatsAndSwizzle . }
219 ModernVersionMajor = 3;
220 ModernVersionMinor = 3;
221
222 { OpenGL versions supported. Checked by looking at GL version string
223 @italic(and) by checking whether actual entry points are available.
224
225 This is important because bad OpenGL implementations
226 (like the horrible ATI Linux closed drivers) sometimes lie,
227 claiming support in the GL version string but actually lacking proper
228 function entry points.
229 We check the actual presence of entry points (GLExt.Load_GL_version_x_x
230 do that).
231
232 We *also* check version string (TGLVersion.AtLeast),
233 since OpenGL may have some buggy entry point in case of work-in-progress
234 features (not yet advertised in GL version string),
235 e.g. Mesa 6.x had such buggy glStencilOpSeparate. This is correct OpenGL
236 behavior AFAIK, and we handle it. }
237 property Version_1_2: Boolean read FVersion_1_2;
238 property Version_1_3: Boolean read FVersion_1_3;
239 property Version_1_4: Boolean read FVersion_1_4;
240 property Version_1_5: Boolean read FVersion_1_5;
241 property Version_2_0: Boolean read FVersion_2_0;
242 property Version_2_1: Boolean read FVersion_2_1;
243 property Version_3_0: Boolean read FVersion_3_0;
244 property Version_3_1: Boolean read FVersion_3_1;
245 property Version_3_2: Boolean read FVersion_3_2;
246 property Version_3_3: Boolean read FVersion_3_3;
247 property Version_4_0: Boolean read FVersion_4_0;
248 {$else}
249 property VersionES_2_0: Boolean read FVersionES_2_0;
250 property VersionES_3_0: Boolean read FVersionES_3_0;
251 property VersionES_3_1: Boolean read FVersionES_3_1;
252 property VersionES_3_2: Boolean read FVersionES_3_2;
253 {$endif}
254
255 { Supports anisotropic texture filtering, as EXT_texture_filter_anisotropic extension
256 (possible for both OpenGL and OpenGLES).
257 This was introduced into OpenGL core late, but is widely available as extension.
258 https://www.khronos.org/opengl/wiki/Sampler_Object#Anisotropic_filtering
259 https://www.khronos.org/opengl/wiki/Ubiquitous_Extension }
260 property TextureFilterAnisotropic: Boolean read FTextureFilterAnisotropic;
261
262 property NV_multisample_filter_hint: Boolean read FNV_multisample_filter_hint;
263
264 { Occlusion query (glGenQueries, glGetQueryObject, glBeginQuery, glEndQuery)
265 in core OpenGL or OpenGLES. }
266 property OcclusionQuery: Boolean read FOcclusionQuery;
267
268 { GL_CLAMP_TO_EDGE, if available in current OpenGL version.
269 Otherwise GL_CLAMP.
270 Use this (instead of just GL_CLAMP_TO_EDGE)
271 to work with @italic(really ancient) OpenGL versions before 1.2. }
272 property CLAMP_TO_EDGE: TGLenum read FCLAMP_TO_EDGE;
273
274 { Constant (for given context) OpenGL limits.
275 Initialized to 0 if appropriate OpenGL functionality is not available.
276
277 Note that MaxLights is only relevant if we use OpenGL fixed-function pipeline.
278 Otherwise the actual limit is defined purely by
279 @link(TCastleRenderOptions.MaxLightsPerShape Scene.RenderOptions.MaxLightsPerShape),
280 specific to each TCastleScene,
281 and is completely configurable (can be higher or lower than MaxLights).
282
283 @groupBegin }
284 property MaxTextureSize: Cardinal read FMaxTextureSize;
285 property MaxLights: Cardinal read FMaxLights;
286 property MaxCubeMapTextureSize: Cardinal read FMaxCubeMapTextureSize;
287 property MaxTexture3DSize: Cardinal read FMaxTexture3DSize;
288 property MaxTextureMaxAnisotropy: Single read FMaxTextureMaxAnisotropy;
289 property OcclusionQueryCounterBits: TGLint read FOcclusionQueryCounterBits;
290 property MaxRenderbufferSize: TGLuint read FMaxRenderbufferSize;
291 property MaxClipPlanes: Cardinal read FMaxClipPlanes;
292 { @groupEnd }
293
294 { Multisampling is available and can be disabled / enabled by GL_MULTISAMPLE flag
295 (it is enabled by default, if buffers have multiple samples available). }
296 property Multisample: Boolean read FMultisample;
297
298 { Number of texture units available for fixed-function pipeline.
299
300 Since querying glGetInteger(GL_MAX_TEXTURE_UNITS) is deprecated
301 (or not even possible in case of OpenGLES or "core" profile)
302 and we want to keep fixed-function support as simple as possible,
303 we just assume 2 (the only number guaranteed) if only multi-texturing
304 is available (UseMultiTexturing). }
305 property MaxTextureUnitsFixedFunction: Cardinal read FMaxTextureUnitsFixedFunction;
306
307 { Number of texture units available for shader pipeline. }
308 property MaxTextureUnitsShaders: Cardinal read FMaxTextureUnitsShaders;
309
310 { Are all OpenGL multi-texturing extensions for
311 VRML/X3D MultiTexture support available.
312
313 This used to check a couple of multitexturing extensions,
314 like ARB_multitexture. Right now, it simply checks for OpenGL 1.3 version.
315 It is supported by virtually all existing GPUs.
316 So it's acceptable to just check it, and write your code for 1.3,
317 and eventual fallback code (when this is false) write only for really
318 ancient GPUs. }
319 property UseMultiTexturing: Boolean read FUseMultiTexturing;
320
321 { Are 3D textures (GL_TEXTURE_3D, glTexImage3D) supported by core OpenGL or OpenGLES. }
322 property Texture3D: Boolean read FTexture3D;
323
324 { Framebuffer supported, by core OpenGL or OpenGLES. }
325 property Framebuffer: Boolean read FFramebuffer;
326
327 { glFramebufferBlit supported, by core OpenGL or OpenGLES. }
328 property FramebufferBlit: Boolean read FFramebufferBlit;
329
330 { Is multisampling possible for FBO buffers and textures.
331 Although these are two orthogonal features of OpenGL,
332 in practice you want to use multisample for both FBO buffers and textures,
333 or for none --- otherwise, FBO can not be initialized correctly
334 when you mix various multisample settings. }
335 property FBOMultiSampling: Boolean read FFBOMultiSampling;
336
337 { How multi-sampling was initialized for this OpenGL context.
338 Value = 1 means that no multi-sampling is initialized.
339 Values > 1 mean that you have multi-sampling, with given number of samples
340 per pixel.
341 Contrast this with TCastleWindow.MultiSampling or TOpenGLControl.MultiSampling,
342 that say @italic(how many samples you wanted to get). }
343 property CurrentMultiSampling: Cardinal read FCurrentMultiSampling;
344
345 { Does OpenGL context have depth buffer packed with stencil buffer.
346 See OpenGL extensions EXT_packed_depth_stencil and OES_packed_depth_stencil
347 (http://www.opengl.org/registry/specs/EXT/packed_depth_stencil.txt,
348 https://www.khronos.org/registry/OpenGL/extensions/OES/OES_packed_depth_stencil.txt)
349 for explanation what does it mean.
350
351 This is important for FBOs, as the depth/stencil have to be set up differently
352 depending on PackedDepthStencil value.
353 This is also important for all code using TGLRenderToTexture
354 with TGLRenderToTexture.Buffer equal tbDepth or tbColorAndDepth:
355 your depth texture must be prepared differently, to include both depth+stencil
356 data, to work.
357
358 For now, this is simply equal to GL_EXT_packed_depth_stencil.
359 (TODO: for core OpenGL 3, how to detect should we use packed version?
360 http://www.opengl.org/registry/specs/ARB/framebuffer_object.txt
361 incorporates EXT_packed_depth_stencil, so forward-compatible contexts
362 do not need to declare it.
363 Should we assume that forward-compatible gl 3 contexts always have
364 depth/stencil packed?) }
365 property PackedDepthStencil: Boolean read FPackedDepthStencil;
366
367 { Does OpenGL context support shadow volumes.
368 This checks do we have:
369 - stencil buffer with at least 4 bits
370 - stencil operations that wrap (GL_INCR/DECR_WRAP in OpenGL >= 2.0)
371 - separate stencil operation (glStencilOpSeparate, without this shadow volumes
372 are more complicated, and now we just require it) }
373 property ShadowVolumesPossible: Boolean read FShadowVolumesPossible;
374
375 { Are non-power-of-2 textures supported. }
376 property TextureNonPowerOfTwo: Boolean read FTextureNonPowerOfTwo;
377
378 { Are cubemaps supported (so you can load to texture targets like
379 GL_TEXTURE_CUBE_MAP_POSITIVE/NEGATIVE_X/Y/Z) by core OpenGL or OpenGLES. }
380 property TextureCubeMap: Boolean read FTextureCubeMap;
381
382 { Which texture compression formats are supported.
383 If this is not [], then we guarantee glCompressedTexImage2D is also supported. }
384 property TextureCompression: TTextureCompressions read FTextureCompression;
385
386 { VBO support (in OpenGL (ES) core). }
387 property VertexBufferObject: Boolean read FVertexBufferObject;
388
389 { VAO support (in OpenGL (ES) core). }
390 property VertexArrayObject: Boolean read FVertexArrayObject;
391
392 { glBlendColor and GL_CONSTANT_ALPHA support. }
393 property BlendConstant: Boolean read FBlendConstant;
394
395 { Support for float texture formats for glTexImage2d. }
396 property TextureFloat: Boolean read FTextureFloat;
397
398 { Support for depth texture formats for glTexImage2d. }
399 property TextureDepth: Boolean read FTextureDepth;
400
401 { Ability to create depth textures (TextureDepth), to define comparison on them:
402 GL_TEXTURE_COMPARE_MODE, GL_TEXTURE_COMPARE_FUNC, GL_COMPARE_REF_TO_TEXTURE,
403 finally to use then in shaders (sampler2DShadow).
404 On OpenGLES the GLSL constructs require that we can use "#version 300 es",
405 to access sampler2DShadow using texture / textureProj calls. }
406 property TextureDepthCompare: Boolean read FTextureDepthCompare;
407
408 { Are GLSL shaders supported. }
409 property Shaders: Boolean read FShaders;
410
411 { Use OpenGL fixed-function rendering for ancient OpenGL versions on desktops.
412 This rules whole rendering approach.
413
414 When this is @false, you can be sure that these features are supported
415 (OpenGL API exposes them, they are not detected as "buggy"):
416
417 @unorderedList(
418 @item(Multi-texturing (@link(UseMultiTexturing) is guaranteed to be @true))
419 @item(VBO (@link(VertexBufferObject) is guaranteed to be @true))
420 @item(Shaders (@link(Shaders) is guaranteed to be @true))
421 @item(OpenGL version >= 2.0 is available on desktops.
422
423 Note that when using rcForceModern, we want to have a "core" profile with OpenGL >= 3.3
424 (TGLFeatures.ModernVersionMajor, TGLFeatures.ModernVersionMinor).
425 And as such when Version_3_3 is @true, you should use OpenGL 3.3 API,
426 not API from older OpenGL like 2.x.
427
428 This means that, aside from EnabledFixedFunction boolean,
429 you should still check Version_X_Y to avoid using functionality that is deprecated
430 and replaced with something else
431 (in OpenGL 3.3, TGLFeatures.ModernVersionMajor, TGLFeatures.ModernVersionMinor).
432 )
433 )
434
435 When this is @true, you should use ancient fixed-function pipeline for all rendering,
436 without shaders or VBO.
437 In fact, to make it easier, we set Shaders and VertexBufferObject to @false
438 in this case (even if in theory one of them could be used, at least in some cases...
439 we don't want to maintain too many alternatives for ancient systems,
440 we want only one path for ancient systems: all modern stuff disabled).
441 This makes Shaders and VertexBufferObject practically useless now:
442 they are always negation of EnabledFixedFunction. And this is OK, it means we have
443 2 clear approaches to rendering, not a lot of possible combinations to test.
444
445 Note that @link(UseMultiTexturing) may be @true or @false when
446 EnableFixedFunction is @true. So we still allow the option to support fixed-function
447 with or without multi-texturing.
448
449 When this is @true:
450
451 @unorderedList(
452 @item(This forces Gouraud shading.)
453 @item(It makes TDrawableImage, DrawPrimitive2D, TCastleRenderUnlitMesh
454 use OpenGL fixed-function pipeline.)
455 @item(It allows you to use fixed-function pipeline calls in the
456 @link(TCastleWindow.OnRender) callback, @link(TCastleUserInterface.Render)
457 override and related places.)
458 @item(It also allows some deprecated rendering features like WindowPos
459 to continue to work.)
460 )
461
462 Note that on OpenGLES, it must be always @false, since OpenGLES >= 2
463 has no fixed-function pipeline, and it guarantees having working shaders and VBO.
464 }
465 property EnableFixedFunction: Boolean read FEnableFixedFunction;
466
467 { Request specific OpenGL(ES) capabilities at context creation.
468
469 @unorderedList(
470 @item(By default we work in automatic mode: @link(rcAutomatic).
471 We will use only modern (core, >= 3.3) OpenGL features, if your OpenGL version is sufficiently high.
472 But we will fallback sensibly on OpenGL 2.0 or even OpenGL 1.1 if necessary.)
473
474 @item(You can force using only modern OpenGL 3.3 (on desktops) by setting this to @link(rcForceModern).
475
476 You can alternatively select @italic("Run -> Run Parameters -> Force Modern Rendering Context") menu item
477 before running any application from CGE editor to test it.
478 Or you can pass command-line option @code(--capabilities=force-modern).
479 )
480
481 @item(You can force using ancient OpenGL 1.1 (on desktops), only for testing, by setting this to @link(rcForceFixedFunction).
482
483 You can alternatively select @italic("Run -> Run Parameters -> Force Ancient Rendering Context") menu item
484 before running any application to test it.
485 Or you can pass command-line option @code(--capabilities=force-fixed-function).
486 )
487 )
488
489 This is a class property and it can only change before OpenGL(ES)
490 context is initialized, which means before TCastleWindow.Open
491 occurs, which means before @link(GLFeatures) instance is initialized.
492
493 The routines that initialize OpenGL(ES) context, like using wgl (on Windows) or glX (on Unix)
494 should look at this setting and honour it.
495
496 Normal code using OpenGL(ES) should not look at this property:
497 instead, detect the current OpenGL(ES) capabilities looking at properties of current
498 @link(TGLFeatures) instance, like @link(TGLFeatures.Framebuffer), @link(TGLFeatures.Version_4_0) etc.
499 This way, we should use modern features both when rcForceFixedFunction and rcAutomatic is set. }
500 class property RequestCapabilities: TGLRequestCapabilities
501 read FRequestCapabilities write SetRequestCapabilities;
502
503 { Request debug OpenGL(ES) context.
504 OpenGL will report a lot of information and errors to log,
505 and OpenGL API usage errors will result in immediate exception (with useful stack-trace
506 pointing to their usage in CGE).
507 This should never be used at production, but it is very useful when developing
508 and using OpenGL(ES) API directly.
509
510 See https://www.khronos.org/opengl/wiki/Debug_Output . }
511 class property Debug: Boolean read FDebug write SetDebug;
512
513 { Total and current memory available.
514 Call Memory.Refresh whenever needed. }
515 property Memory: TGLMemoryInfo read FMemory;
516
517 property MaxViewportDimensions: TVector2Integer read FMaxViewportDimensions;
518
519 { Maximum number of texture units you can safely always use.
520 If EnableFixedFunction, this is MaxTextureUnitsFixedFunction,
521 otherwise MaxTextureUnitsShaders. }
522 function MaxTextureUnits: Cardinal;
523
524 { We should use modern OpenGL enums for format, internal format
525 and we have texture swizzle available.
526
527 This means we should use e.g. GL_RG8 and not GL_LUMINANCE_ALPHA.
528 See https://www.khronos.org/opengl/wiki/Image_Format .
529
530 To make it always work (e.g. to use grayscale or grayscale+alpha images),
531 we really need
532 https://www.khronos.org/opengl/wiki/Texture#Swizzle_mask
533 https://registry.khronos.org/OpenGL/extensions/ARB/ARB_texture_swizzle.txt
534 https://registry.khronos.org/OpenGL/extensions/EXT/EXT_texture_swizzle.txt
535 (core extension since 3.3).
536 }
537 property TextureModernFormatsAndSwizzle: Boolean read FTextureModernFormatsAndSwizzle;
538
539 { Size, in bits, of the red channel of the color buffer. }
540 property RedBits: TGLint read FRedBits;
541 { Size, in bits, of the green channel of the color buffer. }
542 property GreenBits: TGLint read FGreenBits;
543 { Size, in bits, of the blue channel of the color buffer. }
544 property BlueBits: TGLint read FBlueBits;
545 { Size, in bits, of the alpha channel of the color buffer. }
546 property AlphaBits: TGLint read FAlphaBits;
547 { Size, in bits, of the depth buffer. }
548 property DepthBits: TGLint read FDepthBits;
549 { Size, in bits, of the stencil buffer. }
550 property StencilBits: TGLint read FStencilBits;
551 { Do we have double-buffer. }
552 property DoubleBuffer: Boolean read FDoubleBuffer;
553
554 { Line width granularity and maximum width. }
555 property LineWidth: TVector2 read FLineWidth;
556
557 { Supports glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, ...); }
558 property TextureMaxLevel: Boolean read FTextureMaxLevel;
559 end;
560
561 { Initialize GLVersion and GLFeatures. }
562 procedure GLInformationInitialize;
563
564 var
565 GLFeatures: TGLFeatures;
566
567 { Much more verbose logging of current context capabilities in GLInformationInitialize. }
568 LogGLInformationVerbose: Boolean = false;
569
570 { Convert a string (like command-line argument) to TGLRequestCapabilities. }
571 function StrToCapabilities(const S: String): TGLRequestCapabilities;
572
573 {$endif read_interface}
574
575 {$ifdef read_implementation}
576
577 procedure GLInformationInitialize;
578 begin
579 {$ifdef USE_DGL}
580 // Do it to initialize glGetString using dglOpenGL
581 if GL_LibHandle = nil then
582 InitOpenGL;
583 ReadOpenGLCore;
584 if not Assigned(glGetString) then
585 raise Exception.Create('Failed to load OpenGL library');
586 {$endif}
587
588 FreeAndNil(GLVersion);
589 GLVersion := TGLVersion.Create(
590 PGLChar(glGetString(GL_VERSION)),
591 PGLChar(glGetString(GL_VENDOR)),
592 PGLChar(glGetString(GL_RENDERER)));
593
594 FreeAndNil(GLFeatures);
595 GLFeatures := TGLFeatures.Create;
596
597 if LogGLInformationVerbose then
598 WritelnLogMultiline('Rendering Initialized', GLInformationString)
599 else
600 WritelnLog('Rendering Initialized', GLInformationStringSummary +
601 ' (for more info: LogGLInformationVerbose:=true)');
602 end;
603
604 function TGLFeatures.HasExtension(const Extension: String): Boolean;
605
606 {$ifdef OpenGLES}
607 { Based on GLExt unit in FPC. This function is missing from GLES header,
608 which does not check for extensions presence at all. }
609 function glext_ExtensionSupported(const extension: String;
610 const searchIn: String): Boolean;
611 var
612 extensions: PChar;
613 start: PChar;
614 where, terminator: PChar;
615 begin
616 if (Pos(' ', extension) <> 0) or (extension = '') then
617 begin
618 Result := FALSE;
619 Exit;
620 end;
621
622 if searchIn = '' then extensions := PGLChar(glGetString(GL_EXTENSIONS))
623 else extensions := PChar(searchIn);
624 start := extensions;
625 while TRUE do
626 begin
627 where := StrPos(start, PChar(extension));
628 if where = nil then Break;
629 terminator := Pointer(PtrUInt(where) + PtrUInt(Length(extension)));
630 {$warnings off} { Stop warning about unportable PtrUInt conversions }
631 if (where = start) or (PChar(Pointer(PtrUInt(where) - PtrUInt(1)))^ = ' ') then
632 {$warnings on}
633 begin
634 if (terminator^ = ' ') or (terminator^ = #0) then
635 begin
636 Result := TRUE;
637 Exit;
638 end;
639 end;
640 start := terminator;
641 end;
642 Result := FALSE;
643 end;
644 {$endif}
645
646 {$ifdef USE_DGL}
647 function glext_ExtensionSupported(const extension: String;
648 { SearchIn ignored with dglOpenGL }
649 const searchIn: String): Boolean;
650 begin
651 Result := dglCheckExtension(Extension);
652 end;
653 {$endif}
654
655 var
656 SupportedExt: AnsiString;
657 I: Integer;
658 begin
659 { Catch an often mistake in Extension name. }
660 if not IsPrefix('GL_', Extension, false) then
661 raise Exception.CreateFmt('Using TGLFeatures.HasExtension with extension name without GL_ prefix: %s', [
662 Extension
663 ]);
664
665 if {$ifdef OpenGLES} VersionES_3_0 {$else} Version_3_0 {$endif} then
666 begin
667 { With new OpenGL, one should use glGetStringi to enumerate over extensions,
668 see https://www.khronos.org/opengl/wiki/GLAPI/glGetString }
669 for I := 0 to glGetInteger(GL_NUM_EXTENSIONS) - 1 do
670 begin
671 SupportedExt := PGLChar(glGetStringi(GL_EXTENSIONS, I));
672 if SupportedExt = Extension then
673 begin
674 // WritelnLog('Detected extension as supported: ' + Extension);
675 Exit(true);
676 end;
677 end;
678 Result := false;
679 end else
680 begin
681 if SupportedExtensions = '' then
682 SupportedExtensions := PAnsiChar(glGetString(GL_EXTENSIONS));
683 Result := glext_ExtensionSupported(Extension, SupportedExtensions);
684 end;
685 end;
686
687 function TGLFeatures.AllExtensions: String;
688 var
689 NumExtensions: TGLint;
690 SupportedExt: AnsiString;
691 I: Integer;
692 begin
693 if {$ifdef OpenGLES} VersionES_3_0 {$else} Version_3_0 {$endif} then
694 begin
695 { Output in this case is a bit richer, since it was natural to implement using
696 new OpenGL way to query for extensions. }
697 NumExtensions := glGetInteger(GL_NUM_EXTENSIONS);
698 Result := Format('%d extensions: ', [NumExtensions]);
699 for I := 0 to glGetInteger(GL_NUM_EXTENSIONS) - 1 do
700 begin
701 SupportedExt := PGLChar(glGetStringi(GL_EXTENSIONS, I));
702 Result := Result + Format('(%d) %s ', [I, SupportedExt]);
703 end;
704 end else
705 begin
706 if SupportedExtensions = '' then
707 SupportedExtensions := PAnsiChar(glGetString(GL_EXTENSIONS));
708 Result := SupportedExtensions;
709 end;
710 end;
711
712 procedure CallbackGLDebug(Source: TGLenum; AType: TGLenum; Id: TGLuint; Severity: TGLenum;
713 Length: TGLsizei; Message: PAnsiChar; UserParam: Pointer);
714 {$if defined(OPENGL_CALLBACK_STDCALL)} stdcall;
715 {$elseif defined(OPENGL_CALLBACK_CDECL)} cdecl;
716 {$else} {$fatal Include openglmac.inc that should define OPENGL_CALLBACK_xxx}
717 {$endif}
718 var
719 SourceStr, TypeStr, SeverityStr, MessageStr, MessageWhole: String;
720 begin
721 case Source of
722 GL_DEBUG_SOURCE_API : SourceStr := 'API';
723 GL_DEBUG_SOURCE_WINDOW_SYSTEM : SourceStr := 'Window System';
724 GL_DEBUG_SOURCE_SHADER_COMPILER: SourceStr := 'Shader Compiler';
725 GL_DEBUG_SOURCE_THIRD_PARTY : SourceStr := '3rd Party';
726 GL_DEBUG_SOURCE_APPLICATION : SourceStr := 'Application';
727 GL_DEBUG_SOURCE_OTHER : SourceStr := 'Other';
728 else SourceStr := 'Unknown';
729 end;
730
731 case AType of
732 GL_DEBUG_TYPE_ERROR : TypeStr := 'GL error';
733 GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: TypeStr := 'Attempted use of deprecated features';
734 GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR : TypeStr := 'Triggering of undefined behavior';
735 GL_DEBUG_TYPE_PORTABILITY : TypeStr := 'Portability issue';
736 GL_DEBUG_TYPE_PERFORMANCE : TypeStr := 'Performance notification';
737 GL_DEBUG_TYPE_MARKER : TypeStr := 'Marker';
738 GL_DEBUG_TYPE_PUSH_GROUP : TypeStr := 'Group push';
739 GL_DEBUG_TYPE_POP_GROUP : TypeStr := 'Group pop';
740 GL_DEBUG_TYPE_OTHER : TypeStr := 'Other';
741 else TypeStr := 'Unknown';
742 end;
743
744 case Severity of
745 GL_DEBUG_SEVERITY_LOW : SeverityStr := 'Low';
746 GL_DEBUG_SEVERITY_MEDIUM : SeverityStr := 'Medium';
747 GL_DEBUG_SEVERITY_HIGH : SeverityStr := 'High';
748 GL_DEBUG_SEVERITY_NOTIFICATION: SeverityStr := 'Notification';
749 else SeverityStr := 'Unknown';
750 end;
751
752 MessageStr := Message;
753
754 MessageWhole := Format('OpenGL debug: %s, %s, %d, %s: %s', [
755 SourceStr,
756 TypeStr,
757 Id,
758 SeverityStr,
759 MessageStr
760 ]);
761
762 if AType = GL_DEBUG_TYPE_ERROR then
763 raise EOpenGLError.Create(MessageWhole)
764 else
765 // Don't output notifcations, too much log every frame
766 if Severity <> GL_DEBUG_SEVERITY_NOTIFICATION then
767 WritelnLog(MessageWhole);
768 end;
769
770 {$ifdef USE_DGL}
771 type
772 GLDEBUGPROC = TGLDEBUGPROC;
773
774 function Load_GL_ARB_texture_multisample: Boolean;
775 begin
776 Result := dglCheckExtension('GL_ARB_texture_multisample');
777 end;
778 {$endif}
779
780 constructor TGLFeatures.Create;
781
782 function GetVector2Integer(const Param: TGLenum): TVector2Integer;
783 var
784 V: packed array [0..1] of TGLInt;
785 begin
786 glGetIntegerv(Param, @V);
787 Result.X := V[0];
788 Result.Y := V[1];
789 end;
790
791 procedure InitializeDebug;
792 begin
793 if HasExtension('GL_KHR_debug') then
794 begin
795 if not Assigned(glDebugMessageCallback) then raise Exception.Create('glDebugMessageCallback missing');
796 if not Assigned(glDebugMessageControl) then raise Exception.Create('glDebugMessageControl missing');
797
798 glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
799 glDebugMessageCallback(
800 {$ifdef USE_DGL} GLDEBUGPROC(@CallbackGLDebug)
801 {$else} @CallbackGLDebug
802 {$endif}, nil);
803 WritelnLog('OpenGL(ES) debugging enabled, expect extra log messages');
804 end;
805 end;
806
807 {$ifndef OpenGLES}
808 var
809 ErrorCode: TGLenum;
810 {$endif}
811 begin
812 inherited;
813
814 {$ifndef OpenGLES}
815 { With dglOpenGL (our CastleGL) the Version_X_Y just reflect
816 whether GL_VERSION is at least X.Y.
817
818 dglOpenGL doesn't have any function to check if all entry points
819 for X.Y are defined, it only has "Read_xxx" for 4.x stuff.
820
821 The Version_X_Y are somewhat unclear anyway,
822 since having core/forward-compatible context
823 means we may have version > X.Y, but still not have entry points for X.Y.
824 In practice they are always used as "at least X.Y". }
825 FVersion_1_2 := GLVersion.AtLeast(1, 2);
826 FVersion_1_3 := GLVersion.AtLeast(1, 3);
827 FVersion_1_4 := GLVersion.AtLeast(1, 4);
828 FVersion_1_5 := GLVersion.AtLeast(1, 5);
829 if RequestCapabilities <> rcForceFixedFunction then
830 begin
831 FVersion_2_0 := GLVersion.AtLeast(2, 0);
832 FVersion_2_1 := GLVersion.AtLeast(2, 1);
833 FVersion_3_0 := GLVersion.AtLeast(3, 0);
834 FVersion_3_1 := GLVersion.AtLeast(3, 1);
835 FVersion_3_2 := GLVersion.AtLeast(3, 2);
836 FVersion_3_3 := GLVersion.AtLeast(3, 3);
837 FVersion_4_0 := GLVersion.AtLeast(4, 0);
838 end;
839 ReadImplementationProperties;
840 ReadExtensions;
841 {$else}
842 FVersionES_2_0 := GLVersion.AtLeast(2, 0);
843 FVersionES_3_0 := GLVersion.AtLeast(3, 0);
844 FVersionES_3_1 := GLVersion.AtLeast(3, 1);
845 FVersionES_3_2 := GLVersion.AtLeast(3, 2);
846
847 if not VersionES_2_0 then
848 raise Exception.Create('We only support OpenGL ES versions >= 2.0');
849 {$endif}
850
851 { Do this as early as possible, which means: after Version_3_2 is defined,
852 to debug even errors below in TGLFeatures initialization. }
853 if Debug then
854 InitializeDebug;
855
856 FNV_multisample_filter_hint := HasExtension('GL_NV_multisample_filter_hint');
857
858 {$ifdef OpenGLES}
859 FCLAMP_TO_EDGE := GL_CLAMP_TO_EDGE;
860 {$else}
861 if Version_1_2 then
862 FCLAMP_TO_EDGE := GL_CLAMP_TO_EDGE
863 else
864 FCLAMP_TO_EDGE := GL_CLAMP;
865 {$endif}
866
867 FMaxTextureSize := glGetInteger(GL_MAX_TEXTURE_SIZE);
868 if GLVersion.BuggyTextureSizeAbove2048 then
869 FMaxTextureSize := Min(FMaxTextureSize, 2048);
870
871 { Querying glGetInteger(GL_MAX_LIGHTS) is deprecated in core profile,
872 as it makes sense only for fixed-function.
873 Just assume 8 now. }
874 FMaxLights := 8;
875
876 FTextureCubeMap := {$ifdef OpenGLES} true
877 {$else} Version_1_3
878 {$endif};
879
880 if TextureCubeMap then
881 FMaxCubeMapTextureSize := glGetInteger(GL_MAX_CUBE_MAP_TEXTURE_SIZE)
882 else
883 FMaxCubeMapTextureSize := 0;
884
885 { OpenGLES: Since 3.0, https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage3D.xhtml .
886 OpenGL: Since 1.2, https://registry.khronos.org/OpenGL-Refpages/gl4/html/glTexImage3D.xhtml
887 (actually they don't show there OpenGL 1.x anymore) }
888 FTexture3D := {$ifdef OpenGLES} VersionES_3_0
889 {$else} Version_1_2
890 {$endif};
891
892 { calculate MaxTexture3DSize, eventually correct Texture3D if buggy }
893 if Texture3D then
894 begin
895 FMaxTexture3DSize := glGetInteger(GL_MAX_3D_TEXTURE_SIZE);
896 if MaxTexture3DSize = 0 then
897 begin
898 FTexture3D := false;
899 WritelnLog('OpenGL', 'Buggy OpenGL 3D texture support: reported as supported, but GL_MAX_3D_TEXTURE_SIZE is zero. (Bug may be found on Mesa 7.0.4.)');
900 end;
901 end else
902 FMaxTexture3DSize := 0;
903
904 { Both OpenGL and OpenGLES commonly define this extension.
905 See https://registry.khronos.org/OpenGL/index_es.php#otherextspecs (OpenGLES list),
906 https://www.khronos.org/opengl/wiki/Sampler_Object#Anisotropic_filtering
907 https://www.khronos.org/opengl/wiki/Ubiquitous_Extension }
908 FTextureFilterAnisotropic := HasExtension('GL_EXT_texture_filter_anisotropic');
909 if TextureFilterAnisotropic then
910 FMaxTextureMaxAnisotropy := glGetFloat(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)
911 else
912 FMaxTextureMaxAnisotropy := 0.0;
913
914 FOcclusionQuery :=
915 {$ifdef OpenGLES} VersionES_3_0
916 {$else} Version_1_5
917 {$endif};
918
919 if OcclusionQuery then
920 begin
921 {$ifdef OpenGLES}
922 FOcclusionQueryCounterBits := 32; // just use some sensible default
923 {$else}
924 glGetQueryiv(GL_SAMPLES_PASSED, GL_QUERY_COUNTER_BITS, @FOcclusionQueryCounterBits);
925 {$endif}
926 end else
927 FOcclusionQueryCounterBits := 0;
928
929 { calculate Framebuffer }
930 FFramebuffer := {$ifdef OpenGLES} true // OpenGLES >= 2 includes FBO
931 {$else} Version_3_0 or GL_ARB_framebuffer_object
932 {$endif};
933
934 if Framebuffer then
935 begin
936 FMaxRenderbufferSize := glGetInteger(GL_MAX_RENDERBUFFER_SIZE);
937 if MaxRenderbufferSize = 0 then
938 begin
939 FFramebuffer := false;
940 WritelnLog('OpenGL', 'Buggy OpenGL Framebuffer: reported as supported, but GL_MAX_RENDERBUFFER_SIZE is zero. (Bug may be found on Mesa 7.0.4.)');
941 end;
942 end else
943 FMaxRenderbufferSize := 0;
944
945 { - In case of OpenGLES: while OpenGLES 2 includes base FBO,
946 only OpenGLES 3 has glBlitFramebuffer.
947 - In case of OpenGL: OpenGL 3 core includes both base FBO and glBlitFramebuffer. }
948 FFramebufferBlit := {$ifdef OpenGLES} VersionES_3_0
949 {$else} Version_3_0
950 {$endif};
951
952 { Calculate UseMultiTexturing.
953 We used to require a couple of extensions for multitexturing:
954 - EXT_texture_env_combine
955 - ARB_multitexture
956 - ARB_texture_env_dot3
957 But GL version >= 1.3 is actually required for GL_subtract,
958 and includes all above extensions in core.
959 It is simpler to just depend on presense in core, and all modern OpenGLs will satisfy this. }
960 FUseMultiTexturing := {$ifdef OpenGLES} true
961 {$else} Version_1_3
962 {$endif};
963
964 if FUseMultiTexturing then
965 FMaxTextureUnitsFixedFunction := 2
966 else
967 FMaxTextureUnitsFixedFunction := 1;
968
969 FFBOMultiSampling := {$ifdef OpenGLES} false
970 {$else}
971 Framebuffer and
972 GL_ARB_texture_multisample and
973 (not GLVersion.BuggyFBOMultiSampling)
974 {$endif};
975
976 FMultisample :=
977 {$ifdef OpenGLES} true
978 {$else} Version_1_3 or HasExtension('GL_ARB_multisample')
979 {$endif};
980 if FMultisample and (glGetInteger(GL_SAMPLE_BUFFERS) <> 0) then
981 begin
982 FCurrentMultiSampling := glGetInteger(GL_SAMPLES);
983 if FCurrentMultiSampling <= 1 then
984 begin
985 WritelnWarning('MultiSampling', Format('We successfully got multi-sampling buffer, but only %d samples per pixel. This doesn''t make much sense, assuming buggy OpenGL implementation, and anti-aliasing may not work.',
986 [CurrentMultiSampling]));
987 FCurrentMultiSampling := 1;
988 end;
989 end else
990 FCurrentMultiSampling := 1;
991
992 FPackedDepthStencil :=
993 {$ifdef OpenGLES} HasExtension('GL_OES_packed_depth_stencil')
994 // macOS doesn't have GL_EXT_packed_depth_stencil, but FBO creation only works when using packed depth+stencil
995 {$else} HasExtension('GL_EXT_packed_depth_stencil') {$ifdef DARWIN} or true {$endif}
996 {$endif};
997
998 {$ifndef OpenGLES}
999 if Version_3_2 then
1000 begin
1001 // check for errors now, as we'll check glGetError later
1002 CheckGLErrors('before glGetFramebufferAttachmentParameteriv');
1003
1004 { Read buffer sizes with new OpenGL core
1005 https://registry.khronos.org/OpenGL-Refpages/gl4/html/glGetFramebufferAttachmentParameter.xhtml
1006 https://stackoverflow.com/questions/27371067/how-to-query-the-depth-of-the-opengl-stencil-buffer }
1007 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1008 GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, @FRedBits);
1009 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1010 GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, @FGreenBits);
1011 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1012 GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, @FBlueBits);
1013 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1014 GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, @FAlphaBits);
1015 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1016 GL_STENCIL, GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, @FStencilBits);
1017 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1018 GL_DEPTH, GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, @FDepthBits);
1019
1020 ErrorCode := glGetError();
1021 if ErrorCode = GL_INVALID_ENUM then
1022 begin
1023 WritelnWarning('Detected buggy glGetFramebufferAttachmentParameteriv, possible on older ATI Radeon GPUs; assuming reasonable context properties');
1024
1025 { Workaround buggy ATI (Michalis codename: hpek):
1026
1027 Version string: 3.3.11672 Compatibility Profile Context
1028 Vendor string: ATI Technologies Inc.
1029 Renderer: ATI Mobility Radeon HD 4300 Series
1030
1031 with 32-bit Windows 7. Using
1032
1033 glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER,
1034 GL_FRONT_LEFT, GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, @FRedBits);
1035
1036 fails there with GL_INVALID_ENUM. }
1037 FRedBits := 8;
1038 FGreenBits := 8;
1039 FBlueBits := 8;
1040 FAlphaBits := 8;
1041 FStencilBits := 8;
1042 FDepthBits := 24;
1043 end else
1044 if ErrorCode <> GL_NO_ERROR then
1045 raise EOpenGLError.Create(ErrorCode, 'after glGetFramebufferAttachmentParameteriv');
1046
1047 FDoubleBuffer := true; // TODO: any way to query it?
1048 end else
1049 {$endif}
1050 begin
1051 FRedBits := glGetInteger(GL_RED_BITS);
1052 FGreenBits := glGetInteger(GL_GREEN_BITS);
1053 FBlueBits := glGetInteger(GL_BLUE_BITS);
1054 FAlphaBits := glGetInteger(GL_ALPHA_BITS);
1055 FStencilBits := glGetInteger(GL_STENCIL_BITS);
1056 FDepthBits := glGetInteger(GL_DEPTH_BITS);
1057 {$ifndef OpenGLES}
1058 FDoubleBuffer := glGetBoolean(GL_DOUBLEBUFFER) <> GL_FALSE;
1059 {$else}
1060 FDoubleBuffer := true;
1061 {$endif}
1062 end;
1063
1064 FShadowVolumesPossible :=
1065 (StencilBits >= 4) and
1066 { OpenGLES 2 always has GL_INCR/DECR_WRAP, glStencilOpSeparate:
1067 see bottom table at https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glStencilOpSeparate.xhtml }
1068 {$ifdef OpenGLES} true
1069 {$else} Version_2_0
1070 {$endif};
1071
1072 FTextureNonPowerOfTwo :=
1073 {$ifdef OpenGLES} true
1074 {$else} Version_2_0 or HasExtension('GL_ARB_texture_non_power_of_two')
1075 {$endif};
1076
1077 FTextureCompression := [];
1078
1079 {$ifndef OpenGLES}
1080 { OpenGL 1.3 introduced glCompressedTexImage2D in core.
1081 To keep things simple, we don't support compressed textures with older OpenGLs
1082 by looking at GL_ARB_texture_compression. }
1083 if Version_1_3 then
1084 {$endif}
1085 begin
1086 { See http://stackoverflow.com/questions/9148795/android-opengl-texture-compression
1087 and http://developer.android.com/guide/topics/graphics/opengl.html
1088 for possible GPU extensions for compression formats. }
1089
1090 if HasExtension('GL_OES_texture_compression_S3TC') or
1091 HasExtension('GL_EXT_texture_compression_s3tc') or
1092 HasExtension('GL_NV_texture_compression_s3tc') then
1093 FTextureCompression := TextureCompression + [
1094 tcDxt1_RGB, tcDxt1_RGBA, tcDxt3, tcDxt5];
1095
1096 if HasExtension('GL_EXT_texture_compression_dxt1') then
1097 FTextureCompression := TextureCompression + [tcDxt1_RGB, tcDxt1_RGBA];
1098 if HasExtension('GL_EXT_texture_compression_dxt3') then
1099 FTextureCompression := TextureCompression + [tcDxt3];
1100 if HasExtension('GL_EXT_texture_compression_dxt5') then
1101 FTextureCompression := TextureCompression + [tcDxt5];
1102
1103 if HasExtension('GL_IMG_texture_compression_pvrtc') then
1104 FTextureCompression := TextureCompression + [
1105 tcPvrtc1_4bpp_RGB,
1106 tcPvrtc1_2bpp_RGB,
1107 tcPvrtc1_4bpp_RGBA,
1108 tcPvrtc1_2bpp_RGBA];
1109
1110 if HasExtension('GL_IMG_texture_compression_pvrtc2') then
1111 FTextureCompression := TextureCompression + [
1112 tcPvrtc2_4bpp,
1113 tcPvrtc2_2bpp];
1114
1115 if HasExtension('GL_AMD_compressed_ATC_texture') or
1116 HasExtension('GL_ATI_texture_compression_atitc') then
1117 FTextureCompression := TextureCompression + [
1118 tcATITC_RGB,
1119 tcATITC_RGBA_ExplicitAlpha,
1120 tcATITC_RGBA_InterpolatedAlpha];
1121
1122 if HasExtension('GL_OES_compressed_ETC1_RGB8_texture') then
1123 FTextureCompression := TextureCompression + [tcETC1];
1124
1125 if HasExtension('GL_KHR_texture_compression_astc_ldr') or
1126 HasExtension('GL_KHR_texture_compression_astc_hdr') then
1127 FTextureCompression := TextureCompression + [
1128 tcASTC_4x4_RGBA,
1129 tcASTC_5x4_RGBA,
1130 tcASTC_5x5_RGBA,
1131 tcASTC_6x5_RGBA,
1132 tcASTC_6x6_RGBA,
1133 tcASTC_8x5_RGBA,
1134 tcASTC_8x6_RGBA,
1135 tcASTC_8x8_RGBA,
1136 tcASTC_10x5_RGBA,
1137 tcASTC_10x6_RGBA,
1138 tcASTC_10x8_RGBA,
1139 tcASTC_10x10_RGBA,
1140 tcASTC_12x10_RGBA,
1141 tcASTC_12x12_RGBA,
1142 tcASTC_4x4_SRGB8_ALPHA8,
1143 tcASTC_5x4_SRGB8_ALPHA8,
1144 tcASTC_5x5_SRGB8_ALPHA8,
1145 tcASTC_6x5_SRGB8_ALPHA8,
1146 tcASTC_6x6_SRGB8_ALPHA8,
1147 tcASTC_8x5_SRGB8_ALPHA8,
1148 tcASTC_8x6_SRGB8_ALPHA8,
1149 tcASTC_8x8_SRGB8_ALPHA8,
1150 tcASTC_10x5_SRGB8_ALPHA8,
1151 tcASTC_10x6_SRGB8_ALPHA8,
1152 tcASTC_10x8_SRGB8_ALPHA8,
1153 tcASTC_10x10_SRGB8_ALPHA8,
1154 tcASTC_12x10_SRGB8_ALPHA8,
1155 tcASTC_12x12_SRGB8_ALPHA8 ];
1156 end;
1157
1158 SupportedTextureCompressionKnown := true;
1159 SupportedTextureCompression := TextureCompression;
1160
1161 FVertexBufferObject := {$ifdef OpenGLES} true
1162 {$else} Version_1_5 and not GLVersion.BuggyVBO
1163 {$endif};
1164
1165 FBlendConstant := {$ifdef OpenGLES} true
1166 {$else}
1167 { OpenGL 1.4 has GL_CONSTANT_ALPHA, glBlendColor is available since 1.2. }
1168 Version_1_4
1169 {$endif};
1170
1171 FTextureFloat :=
1172 {$ifdef OpenGLES} false
1173 {$else} HasExtension('GL_ATI_texture_float') or HasExtension('GL_ARB_texture_float')
1174 {$endif};
1175
1176 FTextureDepth :=
1177 {$ifdef OpenGLES} VersionES_3_0
1178 {$else} Version_1_4 or HasExtension('GL_ARB_depth_texture')
1179 {$endif};
1180
1181 FTextureDepthCompare :=
1182 { Note that we don't look at GL_EXT_shadow_samplers, we need GLSL "300 es" anyway
1183 to access shadow samplers from GLSL. }
1184 {$ifdef OpenGLES} VersionES_3_0
1185 {$else} Version_1_4 or HasExtension('GL_ARB_shadow')
1186 {$endif};
1187
1188 if FTextureDepthCompare and (not FTextureDepth) then
1189 begin
1190 WritelnWarning('OpenGL(ES) feature TextureDepthCompare is not possible without TextureDepth, fixing');
1191 FTextureDepthCompare := false;
1192 end;
1193
1194 FShaders := {$ifdef OpenGLES} true
1195 {$else} Version_2_0
1196 {$endif};
1197
1198 FEnableFixedFunction :=
1199 {$ifdef OpenGLES} false
1200 {$else}
1201 (not UseMultiTexturing) or
1202 (not Shaders) or
1203 // checking for VertexBufferObject also makes sure that BuggyVBO = false
1204 (not VertexBufferObject)
1205 {$endif};
1206
1207 { Right now, EnableFixedFunction is actually synchronized with Shaders and VertexBufferObject.
1208 When not EnableFixedFunction, everything should fall to rendering using ancient way. }
1209 if EnableFixedFunction then
1210 begin
1211 FShaders := false;
1212 FVertexBufferObject := false;
1213 end;
1214
1215 // RequestCapabilities = rcForceFixedFunction overrides above detection
1216 if RequestCapabilities = rcForceFixedFunction then
1217 begin
1218 {$ifdef OpenGLES}
1219 raise Exception.Create('Requested deprecated fixed-function approach, but this is an OpenGLES >= 2.0 context. Cannot use fixed-function.');
1220 {$else}
1221 if Version_3_1 and not HasExtension('GL_ARB_compatibility') then
1222 raise Exception.Create('Requested deprecated fixed-function approach, but this is a modern context without compatibility (ARB_compatibility). Cannot use fixed-function.');
1223 {$endif}
1224
1225 FEnableFixedFunction := true;
1226 FShaders := false;
1227 FVertexBufferObject := false;
1228 end;
1229
1230 Assert(EnableFixedFunction = (not Shaders));
1231 Assert(EnableFixedFunction = (not VertexBufferObject));
1232
1233 { We do not look at GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
1234 which is usually much smaller (may even be 0).
1235 But most of our texture uses do not access the texture from the vertex shader,
1236 only fragment shader.
1237
1238 Note: we read this only if shaders are supported (OpenGL 2.0),
1239 otherwise GL_MAX_TEXTURE_IMAGE_UNITS is invalid enum for older OpenGL. }
1240 if Shaders then
1241 FMaxTextureUnitsShaders := glGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS);
1242
1243 FVertexArrayObject := {$ifdef OpenGLES} false {$else} (not EnableFixedFunction) and Version_3_0 {$endif};
1244
1245 { Calculate MaxClipPlanes.
1246 The logic follows various approaches to clip planes in TShader.EnableClipPlane. }
1247 {$ifndef OpenGLES}
1248 if EnableFixedFunction or (not Version_3_0) then
1249 FMaxClipPlanes := glGetInteger(GL_MAX_CLIP_PLANES)
1250 else
1251 FMaxClipPlanes := glGetInteger(GL_MAX_CLIP_DISTANCES);
1252 {$else}
1253 { Any value is in theory correct for OpenGLES.
1254 The only limit is number of varying variables we can pass from vertex
1255 to fragment shader, and fragment code speed.
1256 With OpenGLES 2, the clipping requires
1257 passing data to the fragment shader, and discarding fragments there.
1258
1259 We set 8, as it seems reasonable, and is the minimal guaranteed value
1260 of GL_MAX_CLIP_DISTANCES. }
1261 FMaxClipPlanes := 8;
1262 {$endif}
1263
1264 FMaxViewportDimensions := GetVector2Integer(GL_MAX_VIEWPORT_DIMS);
1265
1266 FTextureModernFormatsAndSwizzle :=
1267 { when EnableFixedFunction, so we don't use shaders, don't rely
1268 on "texture swizzle" that only affects texture reading from GLSL. }
1269 (not EnableFixedFunction) and
1270 (
1271 {$ifndef OpenGLES} Version_3_3 or {$endif}
1272 HasExtension('GL_ARB_texture_swizzle') or
1273 HasExtension('GL_EXT_texture_swizzle')
1274 );
1275
1276 {$ifndef OpenGLES}
1277 // set LineWidth to some reasonable default when it cannot be queried on old OpenGL
1278 if not Version_2_0 then
1279 FLineWidth := Vector2(1, 8)
1280 else
1281 {$endif}
1282 begin
1283 Assert(SizeOf(TGLFloat) = SizeOf(Single));
1284 glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, @FLineWidth);
1285 end;
1286
1287 FTextureMaxLevel :=
1288 {$ifdef OpenGLES} VersionES_3_0
1289 {$else} Version_1_2
1290 {$endif};
1291
1292 // set GLFeatures singleton, TGLMemoryInfo.Create and TGLMemoryInfo.Refresh depend on it
1293 GLFeatures := Self;
1294
1295 FMemory := TGLMemoryInfo.Create;
1296
1297 if (RequestCapabilities = rcForceModern) and EnableFixedFunction then
1298 raise Exception.Create('Requested modern context, but it was detected that we have to use fixed-function. We failed to really get modern context.');
1299
1300 CheckGLErrors('End of TGLFeatures.Create');
1301 end;
1302
1303 destructor TGLFeatures.Destroy;
1304 begin
1305 FreeAndNil(FMemory);
1306 end;
1307
1308 function TGLFeatures.MaxTextureUnits: Cardinal;
1309 begin
1310 if EnableFixedFunction then
1311 { Note doing
1312 Result := Min(MaxTextureUnitsFixedFunction, MaxTextureUnitsShaders)
1313 would not be OK, since then a GPU that cannot do shaders would not
1314 be able to use textures at all. }
1315 Result := MaxTextureUnitsFixedFunction
1316 else
1317 Result := MaxTextureUnitsShaders;
1318 end;
1319
1320 const
1321 SCannotChangeAfterContextInitialized = 'You cannot change "%s" once rendering context is already initialized.' + NL +
1322 NL +
1323 'You can only change it before TCastleWindow.Open and before TCastleApplication.OnInitialize. In usual applications, put it in "initialization" of unit like GameInitialize that creates TCastleWindow.';
1324
1325 class procedure TGLFeatures.SetRequestCapabilities(const Value: TGLRequestCapabilities);
1326 begin
1327 if FRequestCapabilities <> Value then
1328 begin
1329 { Reason why you cannot change it after context is initialized:
1330
1331 1. Cannot change to rcForceFixedFunction:
1332
1333 Otherwise creating OpenGL context could
1334 initialize early some resources for modern pipeline,
1335 e.g. RenderLoadingBackground would initialize TDrawableImage shaders.
1336 Setting EnableFixedFunction to true later, and disabling shaders,
1337 would put us in a weird state -- some TDrawableImage
1338 shader could be enabled,
1339 and it couldn't be disabled (because InternalSetCurrentProgram
1340 now thinks that shaders are not available).
1341
1342 It is more reliable to guarantee that EnableFixedFunction
1343 is constant once OpenGL(ES) context is open.
1344 So e.g. if EnableFixedFunction=true, you can be 100% certain
1345 that no shaders are enabled, because they are disabled from the start.
1346
1347 2. Cannot change to rcForceModern:
1348
1349 Naturally, rcForceModern is applied at context creation,
1350 so it would be useless to set it later.
1351 }
1352 if GLFeatures <> nil then
1353 raise Exception.CreateFmt(SCannotChangeAfterContextInitialized, ['TGLFeatures.SetRequestCapabilities']);
1354 FRequestCapabilities := Value;
1355 end;
1356 end;
1357
1358 class procedure TGLFeatures.SetDebug(const Value: Boolean);
1359 begin
1360 if FDebug <> Value then
1361 begin
1362 if GLFeatures <> nil then
1363 raise Exception.CreateFmt(SCannotChangeAfterContextInitialized, ['TGLFeatures.Debug']);
1364 FDebug := Value;
1365 end;
1366 end;
1367
1368 { TGLMemoryInfo -------------------------------------------------------------- }
1369
1370 constructor TGLMemoryInfo.Create;
1371 begin
1372 inherited;
1373 ExtensionNVidia := GLFeatures.HasExtension('GL_NVX_gpu_memory_info');
1374 ExtensionATI := GLFeatures.HasExtension('GL_ATI_meminfo');
1375 Refresh;
1376 end;
1377
1378 procedure TGLMemoryInfo.Refresh;
1379 const
1380 GL_GPU_MEM_INFO_TOTAL_AVAILABLE_MEM_NVX = $9048;
1381 GL_GPU_MEM_INFO_CURRENT_AVAILABLE_MEM_NVX = $9049;
1382 GL_VBO_FREE_MEMORY_ATI = $87FB;
1383 GL_TEXTURE_FREE_MEMORY_ATI = $87FC;
1384 GL_RENDERBUFFER_FREE_MEMORY_ATI = $87FD;
1385 var
1386 FreeMemory: TVector4Integer;
1387 begin
1388 // see http://nasutechtips.blogspot.com/2011/02/how-to-get-gpu-memory-size-and-usage-in.html
1389
1390 // http://developer.download.nvidia.com/opengl/specs/GL_NVX_gpu_memory_info.txt
1391 if ExtensionNVidia then
1392 begin
1393 glGetIntegerv(GL_GPU_MEM_INFO_TOTAL_AVAILABLE_MEM_NVX, @Total);
1394 glGetIntegerv(GL_GPU_MEM_INFO_CURRENT_AVAILABLE_MEM_NVX, @Current);
1395 end;
1396
1397 // https://www.khronos.org/registry/OpenGL/extensions/ATI/ATI_meminfo.txt
1398 if ExtensionATI then
1399 begin
1400 if GLFeatures.VertexBufferObject then
1401 begin
1402 glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, @FreeMemory);
1403 CurrentVbo := FreeMemory[0];
1404 end;
1405
1406 glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, @FreeMemory);
1407 CurrentTexture := FreeMemory[0];
1408
1409 if GLFeatures.Framebuffer then
1410 begin
1411 glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, @FreeMemory);
1412 CurrentRenderbuffer := FreeMemory[0];
1413 end;
1414 end;
1415 end;
1416
1417 function TGLMemoryInfo.LessTextureMemoryThan(const RequiredMemoryKb: Integer): Boolean;
1418 begin
1419 if Current <> 0 then
1420 Result := Current < RequiredMemoryKb
1421 else
1422 if CurrentTexture <> 0 then
1423 Result := CurrentTexture < RequiredMemoryKb
1424 else
1425 // unknown memory, assume old GPU with low memory
1426 Result := true;
1427 end;
1428
1429 { global routines --------------------------------------------------------------------- }
1430
1431 function StrToCapabilities(const S: String): TGLRequestCapabilities;
1432 begin
1433 for Result := Low(Result) to High(Result) do
1434 if SameText(CapabilitiesStr[Result], S) then
1435 Exit;
1436 raise Exception.CreateFmt('Invalid capabilities name "%s"', [S]);
1437 end;
1438
1439 {$endif read_implementation}