Debian Codegraph @

src/base_rendering/castleglshaders.pas

raw
1 {
2 Copyright 2007-2024 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 { OpenGL shaders in GLSL language.
17
18 @unorderedList(
19 @item(
20 GLSL version:
21
22 For maximum portability, provide shader code
23 that works with oldest GLSL versions, and do not declare "#version".
24 This means targeting ancient GLSL 1.10 version for desktop OpenGL
25 (introduced in OpenGL 2.0)
26 and targeting GLSL 1.00 for OpenGLES (introduced in OpenGLES 2.0).
27 This means using "attribute", "varying" keywords, and querying
28 the textures using "texture2D", "textureCube" and so on.
29
30 When compiling the shader on modern OpenGL or OpenGLES,
31 we will add a modern #version statement to the shader,
32 and define a few macros that make it use modern keywords
33 (e.g. "attribute" will be replaced with "in" in vertex shader;
34 "texture2D" call will be replaced with "texture").
35 The resulting shader will not use any deprecated features,
36 so it should be fine for OpenGL "core" profile (without compatibility) too.
37
38 As of now, this means we bump the #version for the desktop OpenGL 3.1
39 core profile (if OpenGL >= 3.1) and we bump the #version for
40 the mobile OpenGLES 3 (if OpenGLES >= 3.0).
41
42 Note: If you know you want to target only newer OpenGL(ES) versions,
43 you can also specify #version in shader code explicitly.
44 We will not add another #version then. It is your responsibility
45 then to provide proper alternatives for desktop OpenGL and mobile OpenGLES,
46 as they use similar but not exactly compatible GLSL versions.
47
48 For geometry shaders, you can assume GLSL >= 1.50 (OpenGL 3.2).
49 We do not support geometry shaders with older versions.
50
51 Set InternalUpgradeGlslVersion to @false to test that shaders work also without it.
52 )
53
54 @item(
55 Precision on OpenGLES:
56
57 We automatically add "precision mediump float;" to fragment shader on OpenGLES,
58 if no declaration "precision mediump/lowp/highp float;" is found in the code.
59 This is practically universally needed for OpenGLES fragment shader,
60 that have no default precision.
61 )
62
63 @item(
64 Creating/destroying the TGLSLProgram instance immediately creates/destroys
65 appropriate program on GPU. So be sure to create/destroy it only
66 when you have OpenGL context available (for example, create in TCastleWindow.OnOpen
67 and destroy in TCastleWindow.OnClose).)
68
69 @item(
70 Upon creation, we check current OpenGL context abilities.
71
72 Currently 2 support levels are possible:
73 no support at all (ancient OpenGL) or support built-in (newer OpenGL versions, >= 2.0).
74 The support for shaders using ARB extensions has been removed at 2023-01,
75 as practically no GPU had it and we didn't really test it.
76
77 Both cases are automatically handled inside, so usually you
78 do not have to care about these details.)
79
80 )
81 }
82 unit CastleGLShaders;
83
84 { Define CASTLE_COLLECT_SHADER_SOURCE to collect in TGLSLProgram shader code as Srting, to
85
86 - show it in case of error
87 - show it before linking, if LogShaders.
88
89 Note:
90
91 - The resulting error message can be quite long,
92 as it will contain a full GLSL code.
93 That's useful if you're a developer familiar with GLSL, and able to modify it.
94 But it makes the log very long and hard to read,
95 which is a problem if you're not interested in this particular GLSL bug now.
96
97 - Showing it (at linking) requires collecting shader source code,
98 which uses a bit of memory and time.
99 (But in practice, this is negligible, so this isn't an important argument.)
100 }
101 {$ifdef DEBUG}
102 {$define CASTLE_COLLECT_SHADER_SOURCE}
103 {$endif}
104
105 {$I castleconf.inc}
106
107 interface
108
109 uses SysUtils, Classes, Generics.Collections,
110 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
111 CastleGLUtils, CastleUtils, CastleVectors, CastleRenderOptions;
112
113 type
114 { Common class for exceptions related to GLSL programs. }
115 EGLSLError = class(Exception);
116
117 EGLSLShaderCompileError = class(EGLSLError);
118 EGLSLProgramLinkError = class(EGLSLError);
119 EGLSLAttributeNotFound = class(EGLSLError);
120 EGLSLTransformFeedbackError = class(EGLSLError);
121
122 TGLuintList = TCardinalList;
123
124 TGLSLProgram = class;
125
126 { GLSL uniform provides information to shader that is constant for a given shader execution. }
127 TGLSLUniform = record
128 public
129 Owner: TGLSLProgram;
130 Name: string;
131 Location: TGLint;
132
133 { Calling @link(TGLSLUniform.SetValue) of this is ignored. }
134 class function NotExisting: TGLSLUniform; static;
135
136 { Set uniform variable value.
137 You should get the uniform information first using the
138 @link(TGLSLProgram.Uniform) call. All the documentation for
139 @link(TGLSLProgram.SetUniform) applies also here, so the program must be
140 linked, and enabled (it will be enabled automatically by calling this).
141
142 This method always ignores a missing uniform.
143 Rely on @link(TGLSLProgram.Uniform) to make something else (like make a warning).
144
145 The TGLSLUniform information about a given uniform stays constant while
146 the program is linked. Using the @link(TGLSLProgram.Uniform) one time, and then
147 repeatedly calling @link(TGLSLUniform.SetValue), is faster than repeatedly
148 calling @link(TGLSLProgram.SetUniform). Because the latter will
149 effectively call @link(TGLSLProgram.Uniform) every time, which may have non-zero cost.
150
151 Actually, the uniform location (TGLSLUniform.Location) is constant for a given program,
152 and you can even predict the location in some cases without calling @link(TGLSLProgram.Uniform)
153 method (see GLSL reference). So it can be even faster, as you can prepare
154 correct TGLSLUniform instance in your own code, without calling
155 @link(TGLSLProgram.Uniform).
156
157 @groupBegin }
158 procedure SetValue(const Value: boolean ); overload;
159 procedure SetValue(const Value: TGLint ); overload;
160 procedure SetValue(const Value: TVector2Integer); overload;
161 procedure SetValue(const Value: TVector3Integer); overload;
162 procedure SetValue(const Value: TVector4Integer); overload;
163 procedure SetValue(const Value: TGLfloat ); overload;
164 procedure SetValue(const Value: TVector2 ); overload;
165 procedure SetValue(const Value: TVector3 ); overload;
166 procedure SetValue(const Value: TVector4 ); overload;
167 procedure SetValue(const Value: TMatrix2 ); overload;
168 procedure SetValue(const Value: TMatrix3 ); overload;
169 procedure SetValue(const Value: TMatrix4 ); overload;
170
171 procedure SetValue(const Value: TBooleanList); overload;
172 procedure SetValue(const Value: TInt32List ); overload;
173 procedure SetValue(const Value: TSingleList ); overload;
174 procedure SetValue(const Value: TVector2List); overload;
175 procedure SetValue(const Value: TVector3List); overload;
176 procedure SetValue(const Value: TVector4List); overload;
177 procedure SetValue(const Value: TMatrix3List); overload;
178 procedure SetValue(const Value: TMatrix4List); overload;
179 { @groupEnd }
180 end;
181
182 { GLSL attribute provides per-vertex information to the shader. }
183 TGLSLAttribute = record
184 public
185 type
186 TLocationOffset = 0..3;
187 var
188 Owner: TGLSLProgram;
189 Name: string;
190 Location: TGLint;
191 LocationOffsetsToDisable: array [TLocationOffset] of boolean;
192
193 { Enable an array of arbitary OpenGL type.
194 See the OpenGL documentation of glVertexAttribPointer for meaning of the
195 parameters.
196
197 Note that Ptr is usually an offset relative to the currently bound VBO
198 (Vertex Buffer Object), not a regular pointer to a memory content.
199 That is why is has a type PtrUInt (not Pointer), since usually you calculate
200 it as an integer.
201
202 Note that the array size is not specified anywhere. The way you access
203 the array (what indexes you use) determines the minimum count of the array
204 you should have (and uploaded to VBO).
205
206 You have to provide VertexArrayObject where the array is bound. }
207 procedure EnableArray(const Vao: TVertexArrayObject;
208 const LocationOffset: TLocationOffset;
209 const Size: TGLint; const AType: TGLenum; const Normalized: TGLboolean; const Stride: TGLsizei;
210 const Ptr: PtrUInt);
211 { Shortcut to enable an array of floats (Single in Pascal). }
212 procedure EnableArraySingle(const Vao: TVertexArrayObject;
213 const Stride: TGLsizei; const Ptr: PtrUInt);
214 { Shortcut to enable an array of TVector2. }
215 procedure EnableArrayVector2(const Vao: TVertexArrayObject;
216 const Stride: TGLsizei; const Ptr: PtrUInt);
217 { Shortcut to enable an array of TVector3. }
218 procedure EnableArrayVector3(const Vao: TVertexArrayObject;
219 const Stride: TGLsizei; const Ptr: PtrUInt);
220 { Shortcut to enable an array of TVector4. }
221 procedure EnableArrayVector4(const Vao: TVertexArrayObject;
222 const Stride: TGLsizei; const Ptr: PtrUInt);
223 { Shortcut to enable an array of TMatrix3. }
224 procedure EnableArrayMatrix3(const Vao: TVertexArrayObject;
225 const Stride: TGLsizei; const Ptr: PtrUInt);
226 { Shortcut to enable an array of TMatrix4. }
227 procedure EnableArrayMatrix4(const Vao: TVertexArrayObject;
228 const Stride: TGLsizei; const Ptr: PtrUInt);
229
230 procedure DisableArray;
231
232 { Set attribute variable value.
233 The used type must match the type of this variable in GLSL program.
234
235 OpenGL forces some constraints on using this, see SetUniform.
236 In short: use this only after linking the program.
237 The program is automatically enabled (set as @link(TRenderContext.CurrentProgram RenderContext.CurrentProgram)) by this.
238 And note that attributes declared but not actually used in shader code
239 may be eliminated, use DebugInfo to see which attributes are actually
240 used (@italic(active) in OpenGL terminology).
241
242 These should not be often useful. Usually, you should rather load
243 attribute arrays, by EnableArray.
244
245 @groupBegin }
246 procedure SetValue(const Value: TGLfloat); overload;
247 procedure SetValue(const Value: TVector2); overload;
248 procedure SetValue(const Value: TVector3); overload;
249 procedure SetValue(const Value: TVector4); overload;
250 procedure SetValue(const Value: TMatrix3); overload;
251 procedure SetValue(const Value: TMatrix4); overload;
252 {$ifndef OpenGLES}
253 procedure SetValue(const Value: TVector4Integer); overload;
254 procedure SetValue(const Value: TVector4Byte); overload;
255 procedure SetValue(const Value: TGLdouble); overload;
256 // Makes FPC errors: Error: Asm: Duplicate label, see https://bugs.freepascal.org/view.php?id=32188
257 // procedure SetValue(const Value: TVector2Double);
258 // procedure SetValue(const Value: TVector3Double);
259 // procedure SetValue(const Value: TVector4Double);
260 {$endif}
261 { @groupEnd }
262 end;
263
264 TGLSLAttributeList = {$ifdef FPC}specialize{$endif} TList<TGLSLAttribute>;
265
266 TLocationCache = {$ifdef FPC}specialize{$endif} TDictionary<String, TGLint>;
267
268 { Manage (build, use) a program in GLSL (OpenGL Shading Language). }
269 TGLSLProgram = class
270 private
271 ProgramId: TGLuint;
272 ShaderIds: TGLuintList;
273
274 FUniformMissing: TUniformMissing;
275 FUniformLocations, FAttributeLocations: TLocationCache;
276 FUniformReportedMissing: TStringList;
277
278 // Given stage was attached and compiled by @link(AttachShader).
279 HasStage: array [TShaderType] of Boolean;
280
281 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
282 FSource: array [TShaderType] of TStringList;
283 {$endif CASTLE_COLLECT_SHADER_SOURCE}
284
285 class function GetCurrent: TGLSLProgram; static;
286 class procedure SetCurrent(const Value: TGLSLProgram); static;
287
288 { Make sure all shaders are detached and deleted, to free all resources.
289 This may be called repeatedly, calling it the 2nd time will not free
290 any more resources.
291
292 Note that we don't support calling "Link" repeatedly,
293 this class assumes that TGLSLProgram is only linked once and then used,
294 for now.
295 So calling GLContextClose multiple times has really simple semantics:
296 2nd call just does nothing. The shader is not useful after the 1st
297 GLContextClose call. }
298 procedure GLContextClose;
299 procedure OnGlContextClose(Sender: TObject);
300 public
301 { Shader name is used in log messages. Any String is OK. }
302 Name: String;
303
304 { Is fragment shader required to link successfully.
305
306 By default this is @false (for now) and you can attempt to link
307 a shader with only vertex shader, without fragment shader.
308 This makes sense on OpenGL
309 ( https://www.khronos.org/opengl/wiki/Fragment_Shader#Optional ).
310 Only OpenGLES, or OpenGL on macOS with Core profile,
311 strictly requires fragment shader to be present.
312
313 Setting this to @true is useful when you know shader really requires
314 fragment shader and you want to get more clear error message.
315 CGE then knows to abort linking early, with clear error message,
316 when fragment shader is missing. }
317 FragmentShaderRequired: Boolean;
318
319 constructor Create;
320 destructor Destroy; override;
321
322 { Create shader from given string, compile it and attach to current program.
323
324 For desktop OpenGL, you can attach more than one shader of given
325 type, just make sure that only one main() function is among each type
326 (otherwise link error will be raised later).
327 For OpenGLES, this is not allowed, so don't use this if you want
328 to work with OpenGLES too.
329
330 If you want to explicitly get rid of old shaders, use DetachAllShaders.
331
332 @raises(EGLSLShaderCompileError If the shader source code cannot be compiled,
333 exception message contains precise description from OpenGL where
334 the error is.)
335
336 @groupBegin }
337 procedure AttachVertexShader(const S: string);
338 procedure AttachGeometryShader(const S: string);
339 procedure AttachFragmentShader(const S: string);
340 procedure AttachShader(const ShaderType: TShaderType; S: string); overload;
341 { @groupEnd }
342
343 { Attach multiple shader parts for given type.
344
345 For normal OpenGL, we can use GLSL separate compilation units.
346 So this is equivalent to just calling
347 @code(AttachShader(ShaderType, Parts[I])) for each part.
348
349 For OpenGL ES, this is unfortunately not possible,
350 you can only attach a single shader of a given type (see
351 http://www.khronos.org/opengles/sdk/docs/man/xhtml/glAttachShader.xml ).
352 So we simply concatenate the shaders into one. }
353 procedure AttachShader(const ShaderType: TShaderType;
354 const Parts: TStrings); overload;
355
356 procedure DetachAllShaders;
357
358 { Specify values to record in transform feedback buffers.
359 This must be called before @link(Link) method. }
360 procedure SetTransformFeedbackVaryings(const Varyings: array of PAnsiChar;
361 const IsSingleBufferMode: Boolean = True);
362
363 { Link the program, this should be done after attaching all shaders
364 and before actually using the program.
365
366 @raises(EGLSLProgramLinkError If the program cannot be linked,
367 exception message contains precise description from OpenGL where
368 the error is.) }
369 procedure Link; overload; virtual;
370 procedure Link(Ignored: boolean); overload; deprecated 'use parameterless Link method';
371
372 { Enable (use) this program. Shortcut for @code(RenderContext.CurrentProgram := Self). }
373 procedure Enable;
374
375 { Disable this program (use the fixed function pipeline).
376 Shortcut for @code(RenderContext.CurrentProgram := nil). }
377 class procedure Disable;
378
379 { Override this to set uniform values, in particular to
380 bind the textures used by this shader, right after each @link(Enable)
381 call.
382
383 This is automatically called after every @link(Enable) by our renderer
384 (when it renders shapes) or TCastleScreenEffect (when it renders screen effects).
385 If you use this TGLSLProgram directly (if you call @link(Enable)
386 yourself), then it's your responsibility to call this method
387 explicitly, if you want shaders using it to work.
388
389 You can set any uniform values, and generally do
390 anything you want to be done each time this shader is enabled.
391 In particular, you can bind textures and set corresponding uniform
392 variables of them. Increase BoundTextureUnits appropriately.
393
394 Returns @false is some texture couldn't be bound. }
395 function SetupUniforms(var BoundTextureUnits: Cardinal): boolean; virtual;
396
397 { Returns multiline debug info about current program.
398 Reports whether shaders are supported,
399 names of active uniform and attribute variables etc.
400
401 @raises Exception If any OpenGL error will be detected. }
402 function DebugInfo: string;
403
404 { This is program info log, given to you from OpenGL after the program
405 is linked. }
406 function ProgramInfoLog: string;
407
408 { After the program is linked, you can check this.
409
410 Note that this is necessarily implemented in quite hacky way (by
411 looking at ProgramInfoLog), there is no way currently (AFAIK ?)
412 to get this information cleanly from OpenGL.
413 In case of doubts, we try to "trust" OpenGL to execute shader in hardware.
414 Return @false only when we see clear indication in ProgramInfoLog that
415 it'll run in software. }
416 function RunningInHardware: boolean;
417
418 { What to do when GLSL uniform variable is accessed (by @link(SetUniform)
419 or @link(Uniform)) but doesn't exist in the shader.
420 Note that OpenGL aggresively removes unused code and variables
421 from the shader when compiling/linking, so this also happens for
422 "declared but unused" variables.
423
424 This is only the default value, each @link(Uniform) method call
425 may explicitly use other TUniformMissing.
426
427 @seealso TUniformMissing }
428 property UniformMissing: TUniformMissing
429 read FUniformMissing write FUniformMissing
430 default umWarning;
431
432 { Get the uniform instance. It can be used to make repeated
433 @link(TGLSLUniform.SetValue) calls. You must link the program first.
434
435 If the uniform doesn't exist (or is unused), the action
436 we take depends on @link(UniformMissing) property
437 (by default -- umWarning).
438 The overloaded version with extra @code(AUniformMissing)
439 parameter follows this parameter value.
440
441 @groupBegin }
442 function Uniform(const AName: string): TGLSLUniform; overload;
443 function Uniform(const AName: string; const AUniformMissing: TUniformMissing): TGLSLUniform; overload;
444 { @groupEnd }
445
446 { Set appropriate uniform variable value.
447 The used type must match the type of this variable in GLSL program.
448
449 OpenGL forces some constraints on using this:
450
451 @unorderedList(
452 @item(This should be used only after linking, and re-linking clears
453 (sets to zero) all uniform variables values.)
454
455 @item(This GLSL program must be currently enabled for this to work.
456 So calling this automatically calls @link(Enable)
457 and sets @link(TRenderContext.CurrentProgram RenderContext.CurrentProgram).
458
459 This is required by OpenGL glUniform*
460 commands. glGetUniformLocation take program id as parameter, so they
461 can operate on any program. But glUniform* operate only on
462 active program.)
463
464 @item(Only @italic(active) uniforms variables may be set.
465 @italic(Active) means, quoting OpenGL manpages,
466 a variable that is determined during the link operation
467 that it may be accessed during program execution.
468 In other words, when linking GLSL program, unused variables
469 may be eliminated, and you cannot set them by SetUniform.
470
471 Call DebugInfo to see what uniform variables are considered
472 active for your shader.
473
474 You can change UniformMissing not to silently ignore setting
475 of inactive (or not existing) uniform values.)
476 )
477
478 This will make warning if the variable is not found within
479 the program and UniformMissing = umWarning.
480 The overloaded version with explicit AUniformMissing parameter uses that
481 to decide whether to show warning.
482
483 @groupBegin }
484 procedure SetUniform(const AName: string; const Value: boolean ; const AUniformMissing: TUniformMissing); overload;
485 procedure SetUniform(const AName: string; const Value: TGLint ; const AUniformMissing: TUniformMissing); overload;
486 procedure SetUniform(const AName: string; const Value: TVector2Integer; const AUniformMissing: TUniformMissing); overload;
487 procedure SetUniform(const AName: string; const Value: TVector3Integer; const AUniformMissing: TUniformMissing); overload;
488 procedure SetUniform(const AName: string; const Value: TVector4Integer; const AUniformMissing: TUniformMissing); overload;
489 procedure SetUniform(const AName: string; const Value: TGLfloat ; const AUniformMissing: TUniformMissing); overload;
490 procedure SetUniform(const AName: string; const Value: TVector2 ; const AUniformMissing: TUniformMissing); overload;
491 procedure SetUniform(const AName: string; const Value: TVector3 ; const AUniformMissing: TUniformMissing); overload;
492 procedure SetUniform(const AName: string; const Value: TVector4 ; const AUniformMissing: TUniformMissing); overload;
493 procedure SetUniform(const AName: string; const Value: TMatrix2 ; const AUniformMissing: TUniformMissing); overload;
494 procedure SetUniform(const AName: string; const Value: TMatrix3 ; const AUniformMissing: TUniformMissing); overload;
495 procedure SetUniform(const AName: string; const Value: TMatrix4 ; const AUniformMissing: TUniformMissing); overload;
496 procedure SetUniform(const AName: string; const Value: TBooleanList; const AUniformMissing: TUniformMissing); overload;
497 procedure SetUniform(const AName: string; const Value: TInt32List ; const AUniformMissing: TUniformMissing); overload;
498 procedure SetUniform(const AName: string; const Value: TSingleList ; const AUniformMissing: TUniformMissing); overload;
499 procedure SetUniform(const AName: string; const Value: TVector2List; const AUniformMissing: TUniformMissing); overload;
500 procedure SetUniform(const AName: string; const Value: TVector3List; const AUniformMissing: TUniformMissing); overload;
501 procedure SetUniform(const AName: string; const Value: TVector4List; const AUniformMissing: TUniformMissing); overload;
502 procedure SetUniform(const AName: string; const Value: TMatrix3List; const AUniformMissing: TUniformMissing); overload;
503 procedure SetUniform(const AName: string; const Value: TMatrix4List; const AUniformMissing: TUniformMissing); overload;
504
505 procedure SetUniform(const AName: string; const Value: boolean ); overload;
506 procedure SetUniform(const AName: string; const Value: TGLint ); overload;
507 procedure SetUniform(const AName: string; const Value: TVector2Integer); overload;
508 procedure SetUniform(const AName: string; const Value: TVector3Integer); overload;
509 procedure SetUniform(const AName: string; const Value: TVector4Integer); overload;
510 procedure SetUniform(const AName: string; const Value: TGLfloat ); overload;
511 procedure SetUniform(const AName: string; const Value: TVector2 ); overload;
512 procedure SetUniform(const AName: string; const Value: TVector3 ); overload;
513 procedure SetUniform(const AName: string; const Value: TVector4 ); overload;
514 procedure SetUniform(const AName: string; const Value: TMatrix2 ); overload;
515 procedure SetUniform(const AName: string; const Value: TMatrix3 ); overload;
516 procedure SetUniform(const AName: string; const Value: TMatrix4 ); overload;
517 procedure SetUniform(const AName: string; const Value: TBooleanList); overload;
518 procedure SetUniform(const AName: string; const Value: TInt32List ); overload;
519 procedure SetUniform(const AName: string; const Value: TSingleList ); overload;
520 procedure SetUniform(const AName: string; const Value: TVector2List); overload;
521 procedure SetUniform(const AName: string; const Value: TVector3List); overload;
522 procedure SetUniform(const AName: string; const Value: TVector4List); overload;
523 procedure SetUniform(const AName: string; const Value: TMatrix3List); overload;
524 procedure SetUniform(const AName: string; const Value: TMatrix4List); overload;
525 { @groupEnd }
526
527 { Get the attribute instance. It can be used to make repeated
528 @link(TGLSLAttribute.SetValue) and @link(TGLSLAttribute.EnableArray).
529
530 @raises(EGLSLAttributeNotFound If the variable is not found within
531 the program.
532
533 Note that this is only one of the many things that can
534 go wrong. And on most cases we don't raise any error,
535 instead OpenGL sets it's error state and you probably want to
536 call CheckGLErrors from time to time to catch them.) }
537 function Attribute(const AName: string): TGLSLAttribute;
538
539 { Get the attribute instance. It can be used to make repeated
540 @link(TGLSLAttribute.SetValue) and @link(TGLSLAttribute.EnableArray).
541
542 Returned attribute has @link(TGLSLAttribute.Location) equal to -1.
543 All the calls to @link(TGLSLAttribute.SetValue)
544 or @link(TGLSLAttribute.EnableArray) or @link(TGLSLAttribute.DisableArray)
545 methods are silently ignored. }
546 function AttributeOptional(const AName: string): TGLSLAttribute;
547
548 { Set attribute variable value.
549 The used type must match the type of this variable in GLSL program.
550
551 OpenGL forces some constraints on using this, see SetUniform.
552 In short: use this only after linking the program.
553 The program is automatically enabled (set as @link(TRenderContext.CurrentProgram RenderContext.CurrentProgram)) by this.
554 And note that attributes declared but not actually used in shader code
555 may be eliminated, use DebugInfo to see which attributes are actually
556 used (@italic(active) in OpenGL terminology).
557
558 These should not be often used. Usually, you should rather load
559 attribute arrays, by VertexAttribPointer. You should also get attribute
560 by the @link(Attribute) method, as TGLSLAttribute, and then call
561 @link(TGLSLAttribute.SetValue) or @link(TGLSLAttribute.EnableArray).
562
563 @raises(EGLSLAttributeNotFound If the variable is not found within
564 the program.
565
566 Note that this is only one of the many things that can
567 go wrong. And on most cases we don't raise any error,
568 instead OpenGL sets it's error state and you probably want to
569 call CheckGLErrors from time to time to catch them.)
570
571 @groupBegin }
572 procedure SetAttribute(const AName: string; const Value: TGLfloat); overload; deprecated 'use TGLSLAttribute.SetValue';
573 procedure SetAttribute(const AName: string; const Value: TVector2); overload; deprecated 'use TGLSLAttribute.SetValue';
574 procedure SetAttribute(const AName: string; const Value: TVector3); overload; deprecated 'use TGLSLAttribute.SetValue';
575 procedure SetAttribute(const AName: string; const Value: TVector4); overload; deprecated 'use TGLSLAttribute.SetValue';
576 procedure SetAttribute(const AName: string; const Value: TMatrix3); overload; deprecated 'use TGLSLAttribute.SetValue';
577 procedure SetAttribute(const AName: string; const Value: TMatrix4); overload; deprecated 'use TGLSLAttribute.SetValue';
578 {$ifndef OpenGLES}
579 procedure SetAttribute(const AName: string; const Value: TVector4Integer); overload; deprecated 'use TGLSLAttribute.SetValue';
580 procedure SetAttribute(const AName: string; const Value: TVector4Byte); overload; deprecated 'use TGLSLAttribute.SetValue';
581 procedure SetAttribute(const AName: string; const Value: TGLdouble); overload; deprecated 'use TGLSLAttribute.SetValue';
582 // Makes FPC errors: Error: Asm: Duplicate label, see https://bugs.freepascal.org/view.php?id=32188
583 // procedure SetAttribute(const AName: string; const Value: TVector2Double); deprecated 'use TGLSLAttribute.SetValue';
584 // procedure SetAttribute(const AName: string; const Value: TVector3Double); deprecated 'use TGLSLAttribute.SetValue';
585 // procedure SetAttribute(const AName: string; const Value: TVector4Double); deprecated 'use TGLSLAttribute.SetValue';
586 {$endif}
587 { @groupEnd }
588
589 {$ifdef FPC}
590 { Currently enabled GLSL program.
591 @nil if fixed-function pipeline should be used.
592 Setting this property encapsulates the OpenGL glUseProgram
593 (or equivalent ARB extension), additionally preventing redundant glUseProgram
594 calls. }
595 class property Current: TGLSLProgram read GetCurrent write SetCurrent; deprecated 'use RenderContext.CurrentProgram';
596 {$endif}
597 end;
598
599 TGLSLProgramList = {$ifdef FPC}specialize{$endif} TObjectList<TGLSLProgram>;
600
601 var
602 LogShaders: boolean;
603
604 {$ifdef FPC}
605 function GetCurrentProgram: TGLSLProgram;
606 deprecated 'use RenderContext.CurrentProgram';
607 procedure SetCurrentProgram(const Value: TGLSLProgram);
608 deprecated 'use RenderContext.CurrentProgram';
609
610 { Currently enabled GLSL program.
611 @nil if fixed-function pipeline should be used.
612 Setting this property encapsulates the OpenGL glUseProgram
613 (or equivalent ARB extension), additionally preventing redundant glUseProgram
614 calls.
615
616 @deprecated Use RenderContext.CurrentProgram }
617 property CurrentProgram: TGLSLProgram
618 read GetCurrentProgram write SetCurrentProgram;
619 {$endif FPC}
620
621 // @exclude User by RenderContext.SetCurrentProgram
622 procedure InternalSetCurrentProgram(const Value: TGLSLProgram);
623
624 var
625 { By default, TGLSLProgram automatically adds a #version and a few macros
626 to make GLSL shader code use a modern version, with only modern (not deprecated)
627 GLSL features.
628
629 Set this to @false to disable it -- useful to test
630 that shaders also work fine on older OpenGL(ES) versions than what you have.
631 Note that resulting shaders may not work in OpenGL "core" profile (only compatibility)
632 and some features (like shadow samplers on OpenGLES) may be missing.
633
634 @exclude }
635 InternalUpgradeGlslVersion: Boolean = true;
636
637 implementation
638
639 uses CastleStringUtils, CastleLog, CastleGLVersion, CastleRenderContext,
640 CastleInternalGLUtils, CastleApplicationProperties;
641
642 { Wrapper around glGetShaderInfoLog.
643 Based on Dean Ellis BasicShader.dpr, but somewhat fixed ? <> 0 not > 1. }
644 function GetShaderInfoLog(ShaderId: TGLuint): String;
645 var
646 Len, Len2: TGLint;
647 {$ifndef FPC}
648 AnsiResult: AnsiString;
649 {$endif}
650 begin
651 glGetShaderiv(ShaderId, GL_INFO_LOG_LENGTH, @Len);
652
653 if Len <> 0 then
654 begin
655 {$ifdef FPC}
656 SetLength(Result, Len);
657 glGetShaderInfoLog(ShaderId, Len, @Len2, PChar(Result));
658 {$else}
659 SetLength(AnsiResult, Len);
660 glGetShaderInfoLog(ShaderId, Len, @Len2, PAnsiChar(AnsiResult));
661 Result := String(AnsiResult);
662 {$endif}
663 StringReplaceAllVar(Result, #0, NL);
664 end else
665 Result := '';
666 end;
667
668 { Wrapper around glGetProgramInfoLog. }
669 function GetProgramInfoLog(ProgramId: TGLuint): String;
670 var
671 Len, Len2: TGLint;
672 {$ifndef FPC}
673 AnsiResult: AnsiString;
674 {$endif}
675 begin
676 glGetProgramiv(ProgramId, GL_INFO_LOG_LENGTH, @Len);
677
678 if Len <> 0 then
679 begin
680 {$ifdef FPC}
681 SetLength(Result, Len);
682 glGetProgramInfoLog(ProgramId, Len, @Len2, PChar(Result));
683 {$else}
684 SetLength(AnsiResult, Len);
685 glGetProgramInfoLog(ProgramId, Len, @Len2, PAnsiChar(AnsiResult));
686 Result := String(AnsiResult);
687 {$endif}
688 StringReplaceAllVar(Result, #0, NL);
689 end else
690 Result := '';
691 end;
692
693 function GetCurrentProgram: TGLSLProgram;
694 begin
695 Result := RenderContext.CurrentProgram;
696 end;
697
698 procedure SetCurrentProgram(const Value: TGLSLProgram);
699 begin
700 RenderContext.CurrentProgram := Value;
701 end;
702
703 procedure InternalSetCurrentProgram(const Value: TGLSLProgram);
704 begin
705 if Value <> nil then
706 begin
707 if Value.ProgramId = 0 then
708 begin
709 WritelnWarning('Trying to use a GLSL shader after the OpenGL context for which it was prepared closed; you have to create new TGLSLProgram instance');
710 glUseProgram(0);
711 Exit;
712 end;
713 if GLFeatures.Shaders then
714 glUseProgram(Value.ProgramId);
715 end else
716 begin
717 if GLFeatures.Shaders then
718 glUseProgram(0);
719 end;
720 end;
721
722 { TGLSLUniform --------------------------------------------------------------- }
723
724 class function TGLSLUniform.NotExisting: TGLSLUniform; {$ifdef FPC} static;{$endif}
725 const
726 R: TGLSLUniform = (Owner: nil; Name: ''; Location: -1);
727 begin
728 Result := R;
729 end;
730
731 procedure TGLSLUniform.SetValue(const Value: boolean);
732 begin
733 if Location = -1 then Exit; // ignore non-existing uniform here
734
735 { GLSL "bool" types are set using the "i" version. From manpage:
736
737 "Either the i or the f variants
738 may be used to provide values for uniform variables of type
739 bool, bvec2, bvec3, bvec4, or arrays of these. The uniform
740 variable will be set to false if the input value is 0 or 0.0f,
741 and it will be set to true otherwise.
742 "
743
744 Which means that I can simply call glUniform1i, with Ord(Value). }
745
746 Owner.Enable;
747 if GLFeatures.Shaders then
748 glUniform1i(Location, Ord(Value));
749 end;
750
751 procedure TGLSLUniform.SetValue(const Value: TGLint);
752 begin
753 if Location = -1 then Exit; // ignore non-existing uniform here
754 Owner.Enable;
755 if GLFeatures.Shaders then
756 glUniform1i(Location, Value);
757 end;
758
759 procedure TGLSLUniform.SetValue(const Value: TVector2Integer);
760 begin
761 if Location = -1 then Exit; // ignore non-existing uniform here
762 Owner.Enable;
763 if GLFeatures.Shaders then
764 glUniform2iv(Location, 1, @Value);
765 end;
766
767 procedure TGLSLUniform.SetValue(const Value: TVector3Integer);
768 begin
769 if Location = -1 then Exit; // ignore non-existing uniform here
770 Owner.Enable;
771 if GLFeatures.Shaders then
772 glUniform3iv(Location, 1, @Value);
773 end;
774
775 procedure TGLSLUniform.SetValue(const Value: TVector4Integer);
776 begin
777 if Location = -1 then Exit; // ignore non-existing uniform here
778 Owner.Enable;
779 if GLFeatures.Shaders then
780 glUniform4iv(Location, 1, @Value);
781 end;
782
783 procedure TGLSLUniform.SetValue(const Value: TGLfloat);
784 begin
785 if Location = -1 then Exit; // ignore non-existing uniform here
786 Owner.Enable;
787 if GLFeatures.Shaders then
788 glUniform1f(Location, Value);
789 end;
790
791 procedure TGLSLUniform.SetValue(const Value: TVector2);
792 begin
793 if Location = -1 then Exit; // ignore non-existing uniform here
794 Owner.Enable;
795 if GLFeatures.Shaders then
796 glUniform2fv(Location, 1, @Value);
797 end;
798
799 procedure TGLSLUniform.SetValue(const Value: TVector3);
800 begin
801 if Location = -1 then Exit; // ignore non-existing uniform here
802 Owner.Enable;
803 if GLFeatures.Shaders then
804 glUniform3fv(Location, 1, @Value);
805 end;
806
807 procedure TGLSLUniform.SetValue(const Value: TVector4);
808 begin
809 if Location = -1 then Exit; // ignore non-existing uniform here
810 Owner.Enable;
811 if GLFeatures.Shaders then
812 glUniform4fv(Location, 1, @Value);
813 end;
814
815 procedure TGLSLUniform.SetValue(const Value: TMatrix2);
816 begin
817 if Location = -1 then Exit; // ignore non-existing uniform here
818 Owner.Enable;
819 if GLFeatures.Shaders then
820 glUniformMatrix2fv(Location, 1, GL_FALSE, @Value);
821 end;
822
823 procedure TGLSLUniform.SetValue(const Value: TMatrix3);
824 begin
825 if Location = -1 then Exit; // ignore non-existing uniform here
826 Owner.Enable;
827 if GLFeatures.Shaders then
828 glUniformMatrix3fv(Location, 1, GL_FALSE, @Value);
829 end;
830
831 procedure TGLSLUniform.SetValue(const Value: TMatrix4);
832 begin
833 if Location = -1 then Exit; // ignore non-existing uniform here
834 Owner.Enable;
835 if GLFeatures.Shaders then
836 glUniformMatrix4fv(Location, 1, GL_FALSE, @Value);
837 end;
838
839 procedure TGLSLUniform.SetValue(const Value: TBooleanList);
840 var
841 Ints: TInt32List;
842 begin
843 if Location = -1 then Exit; // ignore non-existing uniform here
844
845 { We cannot pass Value.List, as Pascal booleans do not have 4 bytes
846 (well, actually I could change this by compiler directive or
847 by using LongBool for TBooleanList --- but for TBooleanList
848 this would enlarge it 4 times, not nice).
849
850 Unfortunately, there's no glUniform*ub (unsigned byte) or such function.
851
852 So convert to 32 ints. }
853 Ints := Value.ToInt32;
854 try
855 Owner.Enable;
856 if GLFeatures.Shaders then
857 glUniform1iv(Location, Value.Count, PGLInt(Ints.L));
858 finally FreeAndNil(Ints) end;
859 end;
860
861 procedure TGLSLUniform.SetValue(const Value: TInt32List);
862 begin
863 if Location = -1 then Exit; // ignore non-existing uniform here
864 Assert(SizeOf(Int32) = SizeOf(TGLint));
865 Owner.Enable;
866 if GLFeatures.Shaders then
867 glUniform1iv(Location, Value.Count, PGLInt(Value.L));
868 end;
869
870 procedure TGLSLUniform.SetValue(const Value: TSingleList);
871 begin
872 if Location = -1 then Exit; // ignore non-existing uniform here
873 Owner.Enable;
874 if GLFeatures.Shaders then
875 glUniform1fv(Location, Value.Count, PGLfloat(Value.L));
876 end;
877
878 procedure TGLSLUniform.SetValue(const Value: TVector2List);
879 begin
880 if Location = -1 then Exit; // ignore non-existing uniform here
881 Owner.Enable;
882 if GLFeatures.Shaders then
883 glUniform2fv(Location, Value.Count, PGLfloat(Value.L));
884 end;
885
886 procedure TGLSLUniform.SetValue(const Value: TVector3List);
887 begin
888 if Location = -1 then Exit; // ignore non-existing uniform here
889 Owner.Enable;
890 if GLFeatures.Shaders then
891 glUniform3fv(Location, Value.Count, PGLfloat(Value.L));
892 end;
893
894 procedure TGLSLUniform.SetValue(const Value: TVector4List);
895 begin
896 if Location = -1 then Exit; // ignore non-existing uniform here
897 Owner.Enable;
898 if GLFeatures.Shaders then
899 glUniform4fv(Location, Value.Count, PGLfloat(Value.L));
900 end;
901
902 procedure TGLSLUniform.SetValue(const Value: TMatrix3List);
903 begin
904 if Location = -1 then Exit; // ignore non-existing uniform here
905 Owner.Enable;
906 if GLFeatures.Shaders then
907 glUniformMatrix3fv(Location, Value.Count, GL_FALSE, PGLfloat(Value.L));
908 end;
909
910 procedure TGLSLUniform.SetValue(const Value: TMatrix4List);
911 begin
912 if Location = -1 then Exit; // ignore non-existing uniform here
913 Owner.Enable;
914 if GLFeatures.Shaders then
915 glUniformMatrix4fv(Location, Value.Count, GL_FALSE, PGLfloat(Value.L));
916 end;
917
918 { TGLSLAttribute ------------------------------------------------------------- }
919
920 procedure TGLSLAttribute.SetValue(const Value: TGLfloat);
921 begin
922 if Location = -1 then Exit; // ignore non-existing attribute here
923 Owner.Enable;
924 if GLFeatures.Shaders then
925 glVertexAttrib1f(Location, Value);
926 end;
927
928 procedure TGLSLAttribute.SetValue(const Value: TVector2);
929 begin
930 if Location = -1 then Exit; // ignore non-existing attribute here
931 Owner.Enable;
932 if GLFeatures.Shaders then
933 glVertexAttrib2fv(Location, @Value);
934 end;
935
936 procedure TGLSLAttribute.SetValue(const Value: TVector3);
937 begin
938 if Location = -1 then Exit; // ignore non-existing attribute here
939 Owner.Enable;
940 if GLFeatures.Shaders then
941 glVertexAttrib3fv(Location, @Value);
942 end;
943
944 procedure TGLSLAttribute.SetValue(const Value: TVector4);
945 begin
946 if Location = -1 then Exit; // ignore non-existing attribute here
947 Owner.Enable;
948 if GLFeatures.Shaders then
949 glVertexAttrib4fv(Location, @Value);
950 end;
951
952 procedure TGLSLAttribute.SetValue(const Value: TMatrix3);
953 begin
954 if Location = -1 then Exit; // ignore non-existing attribute here
955 Owner.Enable;
956 if GLFeatures.Shaders then
957 begin
958 glVertexAttrib3fv(Location , @Value.Data[0]);
959 glVertexAttrib3fv(Location + 1, @Value.Data[1]);
960 glVertexAttrib3fv(Location + 2, @Value.Data[2]);
961 end;
962 end;
963
964 procedure TGLSLAttribute.SetValue(const Value: TMatrix4);
965 begin
966 if Location = -1 then Exit; // ignore non-existing attribute here
967 Owner.Enable;
968 if GLFeatures.Shaders then
969 begin
970 glVertexAttrib4fv (Location , @Value.Data[0]);
971 glVertexAttrib4fv (Location + 1, @Value.Data[1]);
972 glVertexAttrib4fv (Location + 2, @Value.Data[2]);
973 glVertexAttrib4fv (Location + 3, @Value.Data[3]);
974 end;
975 end;
976
977 {$ifndef OpenGLES}
978 procedure TGLSLAttribute.SetValue(const Value: TVector4Integer);
979 begin
980 if Location = -1 then Exit; // ignore non-existing attribute here
981 Owner.Enable;
982 if GLFeatures.Shaders then
983 glVertexAttrib4iv(Location, @Value);
984 end;
985
986 procedure TGLSLAttribute.SetValue(const Value: TVector4Byte);
987 begin
988 if Location = -1 then Exit; // ignore non-existing attribute here
989 Owner.Enable;
990 if GLFeatures.Shaders then
991 glVertexAttrib4ubv(Location, @Value);
992 end;
993
994 procedure TGLSLAttribute.SetValue(const Value: TGLdouble);
995 begin
996 if Location = -1 then Exit; // ignore non-existing attribute here
997 Owner.Enable;
998 if GLFeatures.Shaders then
999 glVertexAttrib1d(Location, Value);
1000 end;
1001
1002 // Makes FPC errors: Error: Asm: Duplicate label, see https://bugs.freepascal.org/view.php?id=32188
1003 {
1004 procedure TGLSLAttribute.SetValue(const Value: TVector2Double);
1005 begin
1006 if Location = -1 then Exit; // ignore non-existing attribute here
1007 Owner.Enable;
1008 if GLFeatures.Shaders then
1009 glVertexAttrib2dv(Location, @Value);
1010 end;
1011
1012 procedure TGLSLAttribute.SetValue(const Value: TVector3Double);
1013 begin
1014 if Location = -1 then Exit; // ignore non-existing attribute here
1015 Owner.Enable;
1016 if GLFeatures.Shaders then
1017 glVertexAttrib3dv(Location, @Value);
1018 end;
1019
1020 procedure TGLSLAttribute.SetValue(const Value: TVector4Double);
1021 begin
1022 if Location = -1 then Exit; // ignore non-existing attribute here
1023 Owner.Enable;
1024 if GLFeatures.Shaders then
1025 glVertexAttrib4dv(Location, @Value);
1026 end;
1027 }
1028 {$endif}
1029
1030 procedure TGLSLAttribute.EnableArray(const Vao: TVertexArrayObject;
1031 const LocationOffset: TLocationOffset;
1032 const Size: TGLint; const AType: TGLenum; const Normalized: TGLboolean; const Stride: TGLsizei;
1033 const Ptr: PtrUInt);
1034 begin
1035 if Location = -1 then Exit; // ignore non-existing attribute here
1036 if GLFeatures.Shaders then
1037 begin
1038 RenderContext.CurrentVao := Vao;
1039 RenderContext.CurrentProgram := Owner;
1040
1041 LocationOffsetsToDisable[LocationOffset] := true;
1042 glEnableVertexAttribArray(Location + LocationOffset);
1043 glVertexAttribPointer (Location + LocationOffset, Size, AType, Normalized, Stride, Pointer(Ptr));
1044 end;
1045 end;
1046
1047 procedure TGLSLAttribute.EnableArraySingle(const Vao: TVertexArrayObject;
1048 const Stride: TGLsizei; const Ptr: PtrUInt);
1049 begin
1050 EnableArray(Vao, 0, 1, GL_FLOAT, GL_FALSE, Stride, Ptr);
1051 end;
1052
1053 procedure TGLSLAttribute.EnableArrayVector2(const Vao: TVertexArrayObject;
1054 const Stride: TGLsizei; const Ptr: PtrUInt);
1055 begin
1056 EnableArray(Vao, 0, 2, GL_FLOAT, GL_FALSE, Stride, Ptr);
1057 end;
1058
1059 procedure TGLSLAttribute.EnableArrayVector3(const Vao: TVertexArrayObject;
1060 const Stride: TGLsizei; const Ptr: PtrUInt);
1061 begin
1062 EnableArray(Vao, 0, 3, GL_FLOAT, GL_FALSE, Stride, Ptr);
1063 end;
1064
1065 procedure TGLSLAttribute.EnableArrayVector4(const Vao: TVertexArrayObject;
1066 const Stride: TGLsizei; const Ptr: PtrUInt);
1067 begin
1068 EnableArray(Vao, 0, 4, GL_FLOAT, GL_FALSE, Stride, Ptr);
1069 end;
1070
1071 procedure TGLSLAttribute.EnableArrayMatrix3(const Vao: TVertexArrayObject;
1072 const Stride: TGLsizei; const Ptr: PtrUInt);
1073 begin
1074 EnableArray(Vao, 0, 3, GL_FLOAT, GL_FALSE, Stride, Ptr);
1075 EnableArray(Vao, 1, 3, GL_FLOAT, GL_FALSE, Stride, Ptr + SizeOf(TVector3));
1076 EnableArray(Vao, 2, 3, GL_FLOAT, GL_FALSE, Stride, Ptr + SizeOf(TVector3) * 2);
1077 end;
1078
1079 procedure TGLSLAttribute.EnableArrayMatrix4(const Vao: TVertexArrayObject;
1080 const Stride: TGLsizei; const Ptr: PtrUInt);
1081 begin
1082 EnableArray(Vao, 0, 4, GL_FLOAT, GL_FALSE, Stride, Ptr);
1083 EnableArray(Vao, 1, 4, GL_FLOAT, GL_FALSE, Stride, Ptr + SizeOf(TVector4));
1084 EnableArray(Vao, 2, 4, GL_FLOAT, GL_FALSE, Stride, Ptr + SizeOf(TVector4) * 2);
1085 EnableArray(Vao, 3, 4, GL_FLOAT, GL_FALSE, Stride, Ptr + SizeOf(TVector4) * 3);
1086 end;
1087
1088 procedure TGLSLAttribute.DisableArray;
1089 var
1090 Offset: TLocationOffset;
1091 begin
1092 if Location = -1 then Exit; // ignore non-existing attribute here
1093
1094 if GLFeatures.Shaders then
1095 for Offset := Low(TLocationOffset) to High(TLocationOffset) do
1096 if LocationOffsetsToDisable[Offset] then
1097 glDisableVertexAttribArray(Location + Offset);
1098 end;
1099
1100 { TGLSLProgram --------------------------------------------------------------- }
1101
1102 constructor TGLSLProgram.Create;
1103 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1104 var
1105 ShaderType: TShaderType;
1106 {$endif CASTLE_COLLECT_SHADER_SOURCE}
1107 begin
1108 inherited;
1109
1110 if GLFeatures.Shaders then
1111 ProgramId := glCreateProgram();
1112
1113 { Program id = 0 means that an error occurred. glCreateProgram docs say
1114
1115 "This function returns 0 if an error occurs creating the program object."
1116
1117 Looking at glGetError, I don't see any error code there.
1118 So I just have to raise enigmatic error that creating GLSL program failed.
1119 }
1120
1121 if ProgramId = 0 then
1122 raise EGLSLError.Create('Cannot create GLSL shader program');
1123
1124 ApplicationProperties.OnGLContextCloseObject.Add({$ifdef FPC}@{$endif}OnGlContextClose);
1125
1126 ShaderIds := TGLuintList.Create;
1127
1128 FUniformMissing := umWarning;
1129
1130 FUniformLocations := TLocationCache.Create;
1131 FAttributeLocations := TLocationCache.Create;
1132
1133 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1134 for ShaderType := Low(TShaderType) to High(TShaderType) do
1135 FSource[ShaderType] := TStringList.Create;
1136 {$endif CASTLE_COLLECT_SHADER_SOURCE}
1137 end;
1138
1139 procedure TGLSLProgram.GLContextClose;
1140 begin
1141 { This is called from destructor,
1142 which may be called if exception is raised from constructor,
1143 so be careful to check here things -- e.g. check that
1144 ShaderIds was created.
1145
1146 Note that, if resources have already been freed, we try to not assume
1147 that GLFeatures is <> nil. So you can free TGLSLProgram even after
1148 context is closed.
1149 }
1150
1151 if ShaderIds <> nil then
1152 DetachAllShaders;
1153
1154 if ProgramId <> 0 then
1155 begin
1156 { ProgramId can be non-zero only if GLFeatures.Shaders,
1157 and right now GLFeatures must be <> nil because we must free while
1158 GL context is available. }
1159 Assert(GLFeatures.Shaders);
1160 glDeleteProgram(ProgramId);
1161 ProgramId := 0;
1162 end;
1163
1164 if FUniformLocations <> nil then
1165 FUniformLocations.Clear;
1166 if FAttributeLocations <> nil then
1167 FAttributeLocations.Clear;
1168 end;
1169
1170 procedure TGLSLProgram.OnGlContextClose(Sender: TObject);
1171 begin
1172 GLContextClose;
1173 end;
1174
1175 destructor TGLSLProgram.Destroy;
1176 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1177 var
1178 ShaderType: TShaderType;
1179 {$endif CASTLE_COLLECT_SHADER_SOURCE}
1180 begin
1181 ApplicationProperties.OnGLContextCloseObject.Remove({$ifdef FPC}@{$endif}OnGlContextClose);
1182 GLContextClose;
1183
1184 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1185 for ShaderType := Low(TShaderType) to High(TShaderType) do
1186 FreeAndNil(FSource[ShaderType]);
1187 {$endif}
1188
1189 FreeAndNil(ShaderIds);
1190 FreeAndNil(FUniformLocations);
1191 FreeAndNil(FAttributeLocations);
1192 FreeAndNil(FUniformReportedMissing);
1193
1194 inherited;
1195 end;
1196
1197 function TGLSLProgram.ProgramInfoLog: string;
1198 begin
1199 if GLFeatures.Shaders then
1200 Result := GetProgramInfoLog(ProgramId)
1201 else
1202 Result := '';
1203 end;
1204
1205 function TGLSLProgram.DebugInfo: string;
1206
1207 function GLShaderVariableTypeName(AType: TGLenum): string;
1208 begin
1209 case AType of
1210 GL_FLOAT: Result := 'FLOAT';
1211 GL_FLOAT_VEC2: Result := 'FLOAT_VEC2';
1212 GL_FLOAT_VEC3: Result := 'FLOAT_VEC3';
1213 GL_FLOAT_VEC4: Result := 'FLOAT_VEC4';
1214 GL_INT: Result := 'INT';
1215 GL_INT_VEC2: Result := 'INT_VEC2';
1216 GL_INT_VEC3: Result := 'INT_VEC3';
1217 GL_INT_VEC4: Result := 'INT_VEC4';
1218 GL_BOOL: Result := 'BOOL';
1219 GL_BOOL_VEC2: Result := 'BOOL_VEC2';
1220 GL_BOOL_VEC3: Result := 'BOOL_VEC3';
1221 GL_BOOL_VEC4: Result := 'BOOL_VEC4';
1222 GL_FLOAT_MAT2: Result := 'FLOAT_MAT2';
1223 GL_FLOAT_MAT3: Result := 'FLOAT_MAT3';
1224 GL_FLOAT_MAT4: Result := 'FLOAT_MAT4';
1225 {$ifndef OpenGLES}
1226 GL_FLOAT_MAT2x3: Result := 'FLOAT_MAT2x3';
1227 GL_FLOAT_MAT2x4: Result := 'FLOAT_MAT2x4';
1228 GL_FLOAT_MAT3x2: Result := 'FLOAT_MAT3x2';
1229 GL_FLOAT_MAT3x4: Result := 'FLOAT_MAT3x4';
1230 GL_FLOAT_MAT4x2: Result := 'FLOAT_MAT4x2';
1231 GL_FLOAT_MAT4x3: Result := 'FLOAT_MAT4x3';
1232 GL_SAMPLER_1D: Result := 'SAMPLER_1D';
1233 {$endif}
1234 GL_SAMPLER_2D: Result := 'SAMPLER_2D';
1235 {$ifndef OpenGLES} GL_SAMPLER_3D: Result := 'SAMPLER_3D'; {$endif}
1236 GL_SAMPLER_CUBE: Result := 'SAMPLER_CUBE';
1237 {$ifndef OpenGLES}
1238 GL_SAMPLER_1D_SHADOW: Result := 'SAMPLER_1D_SHADOW';
1239 GL_SAMPLER_2D_SHADOW: Result := 'SAMPLER_2D_SHADOW';
1240 GL_SAMPLER_2D_RECT: Result := 'SAMPLER_2D_RECT';
1241 GL_SAMPLER_2D_RECT_SHADOW: Result := 'SAMPLER_2D_RECT_SHADOW';
1242 GL_INT_SAMPLER_2D_RECT: Result := 'INT_SAMPLER_2D_RECT';
1243 GL_UNSIGNED_INT_SAMPLER_2D_RECT: Result := 'UNSIGNED_INT_SAMPLER_2D_RECT';
1244 GL_SAMPLER_2D_MULTISAMPLE: Result := 'SAMPLER_2D_MULTISAMPLE';
1245 {$endif}
1246 else Result := Format('Unrecognized uniform type "%d"', [AType]);
1247 end;
1248 end;
1249
1250 const
1251 SCannotGetCount = ' Cannot get variables count (probably buggy fglrx ('+
1252 'Radeon closed-source drivers) or Mesa)';
1253
1254 { Fills the UniformNames with the names (and properties)
1255 of all active uniform variables available by the program.
1256 The program must be previously linked to use this.
1257
1258 Quoting OpenGL manpage about what is @italic(active) uniform variable:
1259 A uniform variable (either built-in or user-defined) is
1260 considered active if it is determined during the link operation
1261 that it may be accessed during program execution.
1262
1263 You may want to clear UniformNames before calling this, as this doesn't
1264 clear them automatically, it only appends new names.
1265
1266 GetActiveUniforms was planned once to be public, but actually
1267 I think it fits better in DebugInfo }
1268 procedure GetActiveUniforms(UniformNames: TStringList);
1269 var
1270 I: Integer;
1271 UniformsCount, UniformMaxLength: TGLuint;
1272 ReturnedLength: TGLsizei;
1273 Size: TGLint;
1274 AType: TGLEnum;
1275 Name: AnsiString;
1276 ErrorCode: TGLenum;
1277 begin
1278 if GLFeatures.Shaders then
1279 begin
1280 glGetProgramiv(ProgramId, GL_ACTIVE_UNIFORMS, @UniformsCount);
1281
1282 { fglrx (Radeon closed-source OpenGL drivers) are buggy (that's not
1283 news, I know...) and they report GL_INVALID_ENUM on some queries
1284 here. We detect this, and still produce nice debug message, without
1285 raising any exception (after all, we have to workaround fglrx bugs,
1286 and try to run our program anyway...).
1287 For this we have to check first whether there are any OpenGL errors
1288 pending, and raise exceptions on them. }
1289 ErrorCode := glGetError();
1290 if ErrorCode = GL_INVALID_ENUM then
1291 begin
1292 UniformNames.Append(SCannotGetCount);
1293 Exit;
1294 end else
1295 if ErrorCode <> GL_NO_ERROR then
1296 raise EOpenGLError.Create(ErrorCode, 'GetActiveUniforms');
1297
1298 glGetProgramiv(ProgramId, GL_ACTIVE_UNIFORM_MAX_LENGTH, @UniformMaxLength);
1299
1300 for I := 0 to UniformsCount - 1 do
1301 begin
1302 SetLength(Name, UniformMaxLength);
1303 glGetActiveUniform(ProgramId, I, UniformMaxLength,
1304 {$ifndef USE_DGL}@{$endif} ReturnedLength,
1305 {$ifndef USE_DGL}@{$endif} Size,
1306 {$ifndef USE_DGL}@{$endif} AType,
1307 PAnsiCharOrNil(Name));
1308 SetLength(Name, ReturnedLength);
1309 UniformNames.Append(Format(' %d: Name: %s, type: %s, size: %d',
1310 [I, Name, GLShaderVariableTypeName(AType), Size]));
1311 end;
1312 end;
1313 end;
1314
1315 procedure GetActiveAttribs(AttribNames: TStringList);
1316 var
1317 I: Integer;
1318 AttribsCount, AttribMaxLength: TGLuint;
1319 ReturnedLength: TGLsizei;
1320 Size: TGLint;
1321 AType: TGLEnum;
1322 Name: AnsiString;
1323 ErrorCode: TGLenum;
1324 begin
1325 if GLFeatures.Shaders then
1326 begin
1327 glGetProgramiv(ProgramId, GL_ACTIVE_ATTRIBUTES, @AttribsCount);
1328
1329 ErrorCode := glGetError();
1330 if ErrorCode = GL_INVALID_ENUM then
1331 begin
1332 AttribNames.Append(SCannotGetCount);
1333 Exit;
1334 end else
1335 if ErrorCode <> GL_NO_ERROR then
1336 raise EOpenGLError.Create(ErrorCode, 'GetActiveAttribs');
1337
1338 glGetProgramiv(ProgramId, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, @AttribMaxLength);
1339
1340 for I := 0 to AttribsCount - 1 do
1341 begin
1342 SetLength(Name, AttribMaxLength);
1343 glGetActiveAttrib(ProgramId, I, AttribMaxLength,
1344 {$ifndef USE_DGL}@{$endif} ReturnedLength,
1345 {$ifndef USE_DGL}@{$endif} Size,
1346 {$ifndef USE_DGL}@{$endif} AType,
1347 PAnsiCharOrNil(Name));
1348 SetLength(Name, ReturnedLength);
1349 AttribNames.Append(Format(' %d: Name: %s, type: %s, size: %d',
1350 [I, Name, GLShaderVariableTypeName(AType), Size]));
1351 end;
1352 end;
1353 end;
1354
1355 function ShaderInfoLog(ShaderId: TGLuint): string;
1356 begin
1357 if GLFeatures.Shaders then
1358 Result := GetShaderInfoLog(ShaderId);
1359 end;
1360
1361 var
1362 S: TStringList;
1363 I: Integer;
1364 begin
1365 Result := 'GLSL program support: ' + BoolToStr(GLFeatures.Shaders, true);
1366
1367 CheckGLErrors('Check at the beginning of TGLSLProgram.DebugInfo');
1368
1369 S := TStringList.Create;
1370 try
1371 GetActiveUniforms(S);
1372 Result := Result + NL + 'Active uniforms:' + NL + S.Text;
1373
1374 S.Clear;
1375 GetActiveAttribs(S);
1376 Result := Result + NL + 'Active attribs:' + NL + S.Text ;
1377 finally FreeAndNil(S) end;
1378
1379 for I := 0 to ShaderIds.Count - 1 do
1380 begin
1381 Result := Result + NL + Format('Shader number %d (OpenGL id %d) log:',
1382 [I, ShaderIds[I]]) + NL +
1383 ShaderInfoLog(ShaderIds[I]) ;
1384 end;
1385
1386 Result := Result + NL + 'Program info log:' + NL + ProgramInfoLog ;
1387
1388 Result := Result + NL + 'Program detected as running in hardware: ' +
1389 BoolToStr(RunningInHardware, true) ;
1390 end;
1391
1392 procedure TGLSLProgram.AttachShader(const ShaderType: TShaderType; S: string);
1393 var
1394 AType: TGLenum;
1395
1396 { Some Nvidia drivers on Linux (like version 295.49
1397 in Debian testing on 2012-06-02) segfault when calling glCompileShader[ARB]
1398 with code like "const in gl_MaterialParameters material".
1399 Googling, at least Nvidia happens to sefault also on other pieces of GLSL.
1400
1401 Although our internal GLSL code avoids using such known buggy constructs,
1402 but user can always supply his own shader code.
1403 So we surround glCompileShader[ARB] in a safeguard, to raise nice
1404 EGLSLShaderCompileError (that will result in simple warning and fallback
1405 on fixed-function pipeline) instead of crash. }
1406 procedure ReportCompileAccessViolation;
1407 begin
1408 raise EGLSLShaderCompileError.CreateFmt('%s shader not compiled, segmentation fault in glCompileShader call. Buggy OpenGL GLSL compiler.',
1409 [ShaderTypeName[ShaderType]]);
1410 end;
1411
1412 procedure ReportCompileError(const CompileErrorMessage: String);
1413 var
1414 Message: String;
1415 begin
1416 Message := Format('%s shader not compiled:' + NL +
1417 '%s',
1418 [ShaderTypeName[ShaderType], CompileErrorMessage]);
1419
1420 Message := Message + NL +
1421 NL +
1422 'The shader source code is below:' + NL +
1423 '-------------------------------------------------------' + NL +
1424 S + NL +
1425 '-------------------------------------------------------';
1426
1427 raise EGLSLShaderCompileError.Create(Message);
1428 end;
1429
1430 { Based on Dean Ellis BasicShader.dpr }
1431 function CreateShader(const S: string): TGLuint;
1432 var
1433 SrcPtr: PGLChar;
1434 SrcLength: Cardinal;
1435 Compiled: TGLint;
1436 {$ifndef FPC}
1437 AnsiS: AnsiString;
1438 {$endif}
1439 begin
1440 Result := glCreateShader(AType);
1441 {$ifdef FPC}
1442 SrcPtr := PGLChar(S);
1443 SrcLength := Length(S);
1444 {$else}
1445 AnsiS := AnsiString(S);
1446 SrcPtr := PGLChar(AnsiS);
1447 SrcLength := Length(AnsiS);
1448 {$endif}
1449 glShaderSource(Result, 1, @SrcPtr, @SrcLength);
1450 try
1451 glCompileShader(Result);
1452 except
1453 on E: EAccessViolation do ReportCompileAccessViolation;
1454 end;
1455 glGetShaderiv(Result, GL_COMPILE_STATUS, @Compiled);
1456 { Although I generally avoid creating multiline exception messages,
1457 ShaderGetInfoLog naturally comes out multiline (it contains a
1458 couple of error messages) and it's best presented with line breaks.
1459 So a line break right before ShaderGetInfoLog contents looks good. }
1460 if Compiled <> Ord(GL_TRUE) then
1461 ReportCompileError(GetShaderInfoLog(Result));
1462 end;
1463
1464 const
1465 {$ifdef OpenGLES}
1466 GLES30CoreHeader: array [TShaderType] of String = (
1467 // vertex
1468 '#version 300 es' + NL +
1469 '#define CASTLE_GLSL_VERSION_UPGRADE' + NL +
1470 '#define attribute in' + NL +
1471 '#define varying out' + NL +
1472 '#define texture2D texture' + NL +
1473 '#define texture3D texture' + NL +
1474 '#define textureCube texture' + NL +
1475 '#define texture2DProj textureProj' + NL +
1476 '#define texture3DProj textureProj' + NL +
1477 { Otherwise each sampler2DShadow would have to contain precision specifier.
1478 EXT_shadow_samplers says that lowp is default, so presumably it is OK:
1479 https://registry.khronos.org/OpenGL/extensions/EXT/EXT_shadow_samplers.txt }
1480 'precision lowp sampler2DShadow;' + NL +
1481 { Otherwise each sampler3D would have to contain precision specifier.
1482 3D textures are part of OpenGLES 3.0 core, so it's OK to use sampler3D here.
1483 Testcase that this is needed: castle-model-viewer, compiled with OpenGLES,
1484 viewing demo-models/water/caustics/Barna29.x3dv . }
1485 'precision lowp sampler3D;' + NL,
1486
1487 // geometry - not supported by OpenGLES
1488 '#define CASTLE_GLSL_VERSION_UPGRADE' + NL,
1489
1490 // fragment
1491 '#version 300 es' + NL +
1492 '#define CASTLE_GLSL_VERSION_UPGRADE' + NL +
1493 '#define varying in' + NL +
1494 '#define texture2D texture' + NL +
1495 '#define texture3D texture' + NL +
1496 '#define textureCube texture' + NL +
1497 '#define texture2DProj textureProj' + NL +
1498 '#define texture3DProj textureProj' + NL +
1499 '#define gl_FragColor castle_FragColor' + NL +
1500 'out mediump vec4 castle_FragColor;' + NL +
1501 'precision lowp sampler2DShadow;' + NL +
1502 'precision lowp sampler3D;' + NL
1503 );
1504 {$else}
1505 GL31CoreHeader: array [TShaderType] of String = (
1506 // vertex
1507 '#version 140' + NL +
1508 '#define CASTLE_GLSL_VERSION_UPGRADE' + NL +
1509 '#define attribute in' + NL +
1510 '#define varying out' + NL +
1511 '#define texture2D texture' + NL +
1512 '#define texture3D texture' + NL +
1513 '#define textureCube texture' + NL +
1514 '#define texture2DProj textureProj' + NL +
1515 '#define texture3DProj textureProj' + NL,
1516
1517 // geometry
1518 '#version 150' + NL +
1519 '#define CASTLE_GLSL_VERSION_UPGRADE' + NL,
1520
1521 // fragment
1522 '#version 140' + NL +
1523 '#define CASTLE_GLSL_VERSION_UPGRADE' + NL +
1524 '#define varying in' + NL +
1525 '#define texture2D texture' + NL +
1526 '#define texture3D texture' + NL +
1527 '#define textureCube texture' + NL +
1528 '#define texture2DProj textureProj' + NL +
1529 '#define texture3DProj textureProj' + NL +
1530 '#define gl_FragColor castle_FragColor' + NL +
1531 'out mediump vec4 castle_FragColor;' + NL
1532 );
1533 {$endif}
1534
1535 { Does shader code Text has a line starting with LinePrefix. }
1536 function HasLine(const LinePrefix: String; const Text: String): Boolean;
1537 begin
1538 Result :=
1539 (Pos(#13 + LinePrefix, S) <> 0) or
1540 (Pos(#10 + LinePrefix, S) <> 0) or
1541 IsPrefix(LinePrefix, S, false);
1542 end;
1543
1544 const
1545 { FPC < 2.4.4 doesn't have it defined }
1546 GL_GEOMETRY_SHADER = $8DD9;
1547 var
1548 ShaderId: TGLuint;
1549 begin
1550 { When shaders not supported, TGLSLProgram does nothing, silently. }
1551 if not GLFeatures.Shaders then
1552 Exit;
1553
1554 { calculate AType }
1555 case ShaderType of
1556 stVertex:
1557 AType := GL_VERTEX_SHADER;
1558 stGeometry:
1559 begin
1560 AType := GL_GEOMETRY_SHADER;
1561 if not GLVersion.AtLeast(3, 2) then
1562 { raise an error if Shaders supported but not geometry shaders. }
1563 raise EGLSLShaderCompileError.Create('Geometry shaders not supported by your OpenGL version');
1564 end;
1565 stFragment:
1566 begin
1567 AType := GL_FRAGMENT_SHADER;
1568 {$ifdef OpenGLES}
1569 if (not HasLine('precision mediump float;', S)) and
1570 (not HasLine('precision lowp float;', S)) and
1571 (not HasLine('precision highp float;', S)) then
1572 S := 'precision mediump float;' + NL + S;
1573 {$endif}
1574 end;
1575 {$ifndef COMPILER_CASE_ANALYSIS}
1576 else raise EInternalError.Create('TGLSLProgram.AttachShader ShaderType?');
1577 {$endif}
1578 end;
1579
1580 { Add #version.
1581 Done after adding "precision ..." for OpenGLES fragment shader,
1582 as #version must be earlier. }
1583 if InternalUpgradeGlslVersion and
1584 GLFeatures. {$ifdef OpenGLES} VersionES_3_0 {$else} Version_3_1 {$endif} and
1585 (not HasLine('#version ', S)) then
1586 S := {$ifdef OpenGLES} GLES30CoreHeader {$else} GL31CoreHeader {$endif}
1587 [ShaderType] + S;
1588
1589 ShaderId := CreateShader(S);
1590 glAttachShader(ProgramId, ShaderId);
1591 ShaderIds.Add(ShaderId);
1592
1593 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1594 FSource[ShaderType].Add(S);
1595 {$endif CASTLE_COLLECT_SHADER_SOURCE}
1596 HasStage[ShaderType] := true;
1597 end;
1598
1599 procedure TGLSLProgram.AttachShader(const ShaderType: TShaderType;
1600 const Parts: TStrings);
1601 var
1602 I: Integer;
1603 {$ifdef OpenGLES}
1604 Concatenated: string;
1605 {$endif}
1606 begin
1607 {$ifdef OpenGLES}
1608 Concatenated := '';
1609 for I := 0 to Parts.Count - 1 do
1610 Concatenated := Concatenated + Parts[I] + NL ;
1611 if Trim(Concatenated) <> '' then
1612 AttachShader(ShaderType, Concatenated);
1613 {$else}
1614 for I := 0 to Parts.Count - 1 do
1615 AttachShader(ShaderType, Parts[I]);
1616 {$endif}
1617 end;
1618
1619 procedure TGLSLProgram.AttachVertexShader(const S: string);
1620 begin
1621 AttachShader(stVertex, S);
1622 end;
1623
1624 procedure TGLSLProgram.AttachFragmentShader(const S: string);
1625 begin
1626 AttachShader(stFragment, S);
1627 end;
1628
1629 procedure TGLSLProgram.AttachGeometryShader(const S: string);
1630 begin
1631 AttachShader(stGeometry, S);
1632 end;
1633
1634 procedure TGLSLProgram.SetTransformFeedbackVaryings(
1635 const Varyings: array of PAnsiChar; const IsSingleBufferMode: Boolean);
1636 var
1637 TransformFeedbackBufferMode, ErrorCode: TGLuint;
1638 VaryingLength: Cardinal;
1639 begin;
1640 VaryingLength := Length(Varyings);
1641 if VaryingLength > 0 then
1642 begin
1643 {$ifdef OpenGLES}
1644 if not (GLFeatures.VersionES_3_0) then
1645 raise EGLSLTransformFeedbackError.Create('OpenGL ES 2.0 doesn''t support Transform Feedback');
1646 {$else}
1647 if not (GLFeatures.Version_3_0 and GLFeatures.Shaders) then
1648 raise EGLSLTransformFeedbackError.Create('Transform feedback not supported by your OpenGL(ES) version');
1649 {$endif}
1650 if IsSingleBufferMode then
1651 TransformFeedbackBufferMode := GL_INTERLEAVED_ATTRIBS
1652 else
1653 TransformFeedbackBufferMode := GL_SEPARATE_ATTRIBS;
1654 glTransformFeedbackVaryings(ProgramId, VaryingLength, @Varyings[0], TransformFeedbackBufferMode);
1655 ErrorCode := glGetError();
1656 if ErrorCode = GL_INVALID_VALUE then
1657 begin
1658 raise EGLSLTransformFeedbackError.Create('Error occured after setting transform feedback varyings');
1659 end;
1660 end;
1661 end;
1662
1663 procedure TGLSLProgram.DetachAllShaders;
1664 var
1665 I: Integer;
1666 ShaderType: TShaderType;
1667 begin
1668 for I := 0 to ShaderIds.Count - 1 do
1669 begin
1670 { ShaderIds can be non-empty only if GLFeatures.Shaders,
1671 and right now GLFeatures must be <> nil because we must free while
1672 GL context is available. }
1673 Assert(GLFeatures.Shaders);
1674 glDetachShader(ProgramId, ShaderIds[I]);
1675 glDeleteShader(ShaderIds[I]);
1676 end;
1677
1678 ShaderIds.Count := 0;
1679
1680 for ShaderType := Low(TShaderType) to High(TShaderType) do
1681 begin
1682 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1683 FSource[ShaderType].Clear;
1684 {$endif CASTLE_COLLECT_SHADER_SOURCE}
1685 HasStage[ShaderType] := false;
1686 end;
1687 end;
1688
1689 procedure TGLSLProgram.Link;
1690
1691 { Outputs shader source code, if collected.
1692 Returns empty string if not collected.
1693 If collected, this is multiline string that *starts* with newline,
1694 and does not end with newline. }
1695 function LogShaderCode: String;
1696 {$ifdef CASTLE_COLLECT_SHADER_SOURCE}
1697 var
1698 ShaderType: TShaderType;
1699 I: Integer;
1700 begin
1701 Result := NL + Format('Shader "%s" source code:', [Name]) + NL;
1702 for ShaderType := Low(TShaderType) to High(TShaderType) do
1703 for I := 0 to FSource[ShaderType].Count - 1 do
1704 Result := Result + Format(
1705 '%s [%d] -------------------------------------------------------' + NL +
1706 '%s' + NL,
1707 [ ShaderTypeName[ShaderType], I, FSource[ShaderType][I] ] );
1708 Result := Result +
1709 'End of shader source code -------------------------------------------------------';
1710 {$else}
1711 begin
1712 Result := '';
1713 {$endif CASTLE_COLLECT_SHADER_SOURCE}
1714 end;
1715
1716 procedure ReportLinkError(const LinkErrorMessage: String);
1717 begin
1718 raise EGLSLProgramLinkError.Create(
1719 Format('Shader "%s" not linked:', [Name]) + NL +
1720 LinkErrorMessage +
1721 LogShaderCode);
1722 end;
1723
1724 var
1725 Linked: TGLuint;
1726 begin
1727 if GLFeatures.Shaders then
1728 begin
1729 { Produce clear error messages, without waiting for OpenGL errors,
1730 if required shaders are not attached. }
1731 if not HasStage[stVertex] then
1732 raise EGLSLProgramLinkError.Create('Vertex shader not attached');
1733 if FragmentShaderRequired and (not HasStage[stFragment]) then
1734 raise EGLSLProgramLinkError.Create('Fragment shader not attached');
1735
1736 glLinkProgram(ProgramId);
1737 glGetProgramiv(ProgramId, GL_LINK_STATUS, @Linked);
1738
1739 if Linked <> Ord(GL_TRUE) then
1740 // raises exception
1741 ReportLinkError(GetProgramInfoLog(ProgramId));
1742
1743 if LogShaders then
1744 WritelnLogMultiline('GLSL',
1745 Format('Shader "%s" successfully linked:', [Name]) + NL +
1746 'Information:' + NL +
1747 DebugInfo +
1748 LogShaderCode);
1749 end;
1750 end;
1751
1752 procedure TGLSLProgram.Link(Ignored: boolean);
1753 begin
1754 Link;
1755 end;
1756
1757 function TGLSLProgram.RunningInHardware: boolean;
1758 begin
1759 { This is good at least for capturing shaders running in software on
1760 Radeon X300/X550/X1050 Series (crypto on ii.324), Linux fglrx. }
1761
1762 Result := Pos('shader will run in software due to the', ProgramInfoLog) = 0;
1763 end;
1764
1765 procedure TGLSLProgram.Enable;
1766 begin
1767 RenderContext.CurrentProgram := Self;
1768 end;
1769
1770 class procedure TGLSLProgram.Disable;
1771 begin
1772 RenderContext.CurrentProgram := nil;
1773 end;
1774
1775 function TGLSLProgram.SetupUniforms(var BoundTextureUnits: Cardinal): boolean;
1776 begin
1777 Result := true;
1778 end;
1779
1780 function TGLSLProgram.Uniform(const AName: string): TGLSLUniform;
1781 begin
1782 Result := Uniform(AName, UniformMissing);
1783 end;
1784
1785 function TGLSLProgram.Uniform(const AName: string; const AUniformMissing: TUniformMissing): TGLSLUniform;
1786
1787 procedure ReportUniformMissing;
1788
1789 function ErrMessage: string;
1790 begin
1791 Result := Format('Uniform variable "%s" not found (or not used) in the shader source code', [AName]);
1792 end;
1793
1794 begin
1795 if FUniformReportedMissing = nil then
1796 begin
1797 FUniformReportedMissing := TStringList.Create;
1798 FUniformReportedMissing.CaseSensitive := true; // GLSL uniform names are case-sensitive
1799 end;
1800 // don't spam the log with warning "Uniform variable "%s" not found (or not used)"... every frame
1801 if FUniformReportedMissing.IndexOf(AName) <> -1 then
1802 Exit;
1803 FUniformReportedMissing.Add(AName);
1804
1805 case AUniformMissing of
1806 umWarning : WritelnWarning('GLSL', ErrMessage);
1807 // This was implemented in the past, but was not useful - we converted it to warnings anyway
1808 //uaException: raise EGLSLUniformMissing.Create(ErrMessage);
1809 umIgnore : ;
1810 {$ifndef COMPILER_CASE_ANALYSIS}
1811 else raise EInternalError.Create('AUniformMissing? in TGLSLProgram.UniformMissing');
1812 {$endif}
1813 end;
1814 end;
1815
1816 begin
1817 Result.Owner := Self;
1818 Result.Name := AName;
1819
1820 if not FUniformLocations.TryGetValue(AName, Result.Location) then
1821 begin
1822 if GLFeatures.Shaders then
1823 Result.Location := glGetUniformLocation(ProgramId, PAnsiCharOrNil(AName))
1824 else
1825 Result.Location := -1;
1826
1827 {$ifdef CASTLE_LOG_GET_LOCATIONS}
1828 WritelnLog('Doing (potentially expensive) glGetUniformLocation: ' + AName);
1829 {$endif}
1830 FUniformLocations.Add(AName, Result.Location);
1831 end;
1832
1833 if Result.Location = -1 then
1834 ReportUniformMissing;
1835 end;
1836
1837 procedure TGLSLProgram.SetUniform(const AName: string; const Value: boolean; const AUniformMissing: TUniformMissing);
1838 begin
1839 Uniform(AName, AUniformMissing).SetValue(Value);
1840 end;
1841
1842 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TGLint; const AUniformMissing: TUniformMissing);
1843 begin
1844 Uniform(AName, AUniformMissing).SetValue(Value);
1845 end;
1846
1847 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector2Integer; const AUniformMissing: TUniformMissing);
1848 begin
1849 Uniform(AName, AUniformMissing).SetValue(Value);
1850 end;
1851
1852 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector3Integer; const AUniformMissing: TUniformMissing);
1853 begin
1854 Uniform(AName, AUniformMissing).SetValue(Value);
1855 end;
1856
1857 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector4Integer; const AUniformMissing: TUniformMissing);
1858 begin
1859 Uniform(AName, AUniformMissing).SetValue(Value);
1860 end;
1861
1862 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TGLfloat; const AUniformMissing: TUniformMissing);
1863 begin
1864 Uniform(AName, AUniformMissing).SetValue(Value);
1865 end;
1866
1867 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector2; const AUniformMissing: TUniformMissing);
1868 begin
1869 Uniform(AName, AUniformMissing).SetValue(Value);
1870 end;
1871
1872 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector3; const AUniformMissing: TUniformMissing);
1873 begin
1874 Uniform(AName, AUniformMissing).SetValue(Value);
1875 end;
1876
1877 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector4; const AUniformMissing: TUniformMissing);
1878 begin
1879 Uniform(AName, AUniformMissing).SetValue(Value);
1880 end;
1881
1882 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix2; const AUniformMissing: TUniformMissing);
1883 begin
1884 Uniform(AName, AUniformMissing).SetValue(Value);
1885 end;
1886
1887 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix3; const AUniformMissing: TUniformMissing);
1888 begin
1889 Uniform(AName, AUniformMissing).SetValue(Value);
1890 end;
1891
1892 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix4; const AUniformMissing: TUniformMissing);
1893 begin
1894 Uniform(AName, AUniformMissing).SetValue(Value);
1895 end;
1896
1897 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TBooleanList; const AUniformMissing: TUniformMissing);
1898 begin
1899 Uniform(AName, AUniformMissing).SetValue(Value);
1900 end;
1901
1902 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TInt32List; const AUniformMissing: TUniformMissing);
1903 begin
1904 Uniform(AName, AUniformMissing).SetValue(Value);
1905 end;
1906
1907 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TSingleList; const AUniformMissing: TUniformMissing);
1908 begin
1909 Uniform(AName, AUniformMissing).SetValue(Value);
1910 end;
1911
1912 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector2List; const AUniformMissing: TUniformMissing);
1913 begin
1914 Uniform(AName, AUniformMissing).SetValue(Value);
1915 end;
1916
1917 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector3List; const AUniformMissing: TUniformMissing);
1918 begin
1919 Uniform(AName, AUniformMissing).SetValue(Value);
1920 end;
1921
1922 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector4List; const AUniformMissing: TUniformMissing);
1923 begin
1924 Uniform(AName, AUniformMissing).SetValue(Value);
1925 end;
1926
1927 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix3List; const AUniformMissing: TUniformMissing);
1928 begin
1929 Uniform(AName, AUniformMissing).SetValue(Value);
1930 end;
1931
1932 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix4List; const AUniformMissing: TUniformMissing);
1933 begin
1934 Uniform(AName, AUniformMissing).SetValue(Value);
1935 end;
1936
1937 procedure TGLSLProgram.SetUniform(const AName: string; const Value: boolean);
1938 begin
1939 SetUniform(AName, Value, UniformMissing);
1940 end;
1941
1942 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TGLint);
1943 begin
1944 SetUniform(AName, Value, UniformMissing);
1945 end;
1946
1947 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector2Integer);
1948 begin
1949 SetUniform(AName, Value, UniformMissing);
1950 end;
1951
1952 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector3Integer);
1953 begin
1954 SetUniform(AName, Value, UniformMissing);
1955 end;
1956
1957 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector4Integer);
1958 begin
1959 SetUniform(AName, Value, UniformMissing);
1960 end;
1961
1962 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TGLfloat);
1963 begin
1964 SetUniform(AName, Value, UniformMissing);
1965 end;
1966
1967 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector2);
1968 begin
1969 SetUniform(AName, Value, UniformMissing);
1970 end;
1971
1972 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector3);
1973 begin
1974 SetUniform(AName, Value, UniformMissing);
1975 end;
1976
1977 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector4);
1978 begin
1979 SetUniform(AName, Value, UniformMissing);
1980 end;
1981
1982 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix2);
1983 begin
1984 SetUniform(AName, Value, UniformMissing);
1985 end;
1986
1987 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix3);
1988 begin
1989 SetUniform(AName, Value, UniformMissing);
1990 end;
1991
1992 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix4);
1993 begin
1994 SetUniform(AName, Value, UniformMissing);
1995 end;
1996
1997 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TBooleanList);
1998 begin
1999 SetUniform(AName, Value, UniformMissing);
2000 end;
2001
2002 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TInt32List);
2003 begin
2004 SetUniform(AName, Value, UniformMissing);
2005 end;
2006
2007 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TSingleList);
2008 begin
2009 SetUniform(AName, Value, UniformMissing);
2010 end;
2011
2012 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector2List);
2013 begin
2014 SetUniform(AName, Value, UniformMissing);
2015 end;
2016
2017 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector3List);
2018 begin
2019 SetUniform(AName, Value, UniformMissing);
2020 end;
2021
2022 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TVector4List);
2023 begin
2024 SetUniform(AName, Value, UniformMissing);
2025 end;
2026
2027 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix3List);
2028 begin
2029 SetUniform(AName, Value, UniformMissing);
2030 end;
2031
2032 procedure TGLSLProgram.SetUniform(const AName: string; const Value: TMatrix4List);
2033 begin
2034 SetUniform(AName, Value, UniformMissing);
2035 end;
2036
2037 function TGLSLProgram.AttributeOptional(const AName: string): TGLSLAttribute;
2038 begin
2039 Result.Owner := Self;
2040 Result.Name := AName;
2041
2042 if not FAttributeLocations.TryGetValue(AName, Result.Location) then
2043 begin
2044 if GLFeatures.Shaders then
2045 Result.Location := glGetAttribLocation(ProgramId, PAnsiCharOrNil(AName))
2046 else
2047 Result.Location := -1;
2048
2049 {$ifdef CASTLE_LOG_GET_LOCATIONS}
2050 WritelnLog('Doing (potentially expensive) glGetAttribLocation: ' + AName);
2051 {$endif}
2052 FAttributeLocations.Add(AName, Result.Location);
2053 end;
2054 end;
2055
2056 function TGLSLProgram.Attribute(const AName: string): TGLSLAttribute;
2057 begin
2058 Result := AttributeOptional(AName);
2059 if Result.Location = -1 then
2060 raise EGLSLAttributeNotFound.CreateFmt('Attribute variable "%s" not found', [AName]);
2061 end;
2062
2063 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TGLfloat);
2064 begin
2065 Attribute(AName).SetValue(Value);
2066 end;
2067
2068 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector2);
2069 begin
2070 Attribute(AName).SetValue(Value);
2071 end;
2072
2073 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector3);
2074 begin
2075 Attribute(AName).SetValue(Value);
2076 end;
2077
2078 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector4);
2079 begin
2080 Attribute(AName).SetValue(Value);
2081 end;
2082
2083 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TMatrix3);
2084 begin
2085 Attribute(AName).SetValue(Value);
2086 end;
2087
2088 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TMatrix4);
2089 begin
2090 Attribute(AName).SetValue(Value);
2091 end;
2092
2093 {$ifndef OpenGLES}
2094 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector4Integer);
2095 begin
2096 Attribute(AName).SetValue(Value);
2097 end;
2098
2099 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector4Byte);
2100 begin
2101 Attribute(AName).SetValue(Value);
2102 end;
2103
2104 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TGLdouble);
2105 begin
2106 Attribute(AName).SetValue(Value);
2107 end;
2108
2109 // Makes FPC errors: Error: Asm: Duplicate label, see https://bugs.freepascal.org/view.php?id=32188
2110 {
2111 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector2Double);
2112 begin
2113 Attribute(AName).SetValue(Value);
2114 end;
2115
2116 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector3Double);
2117 begin
2118 Attribute(AName).SetValue(Value);
2119 end;
2120
2121 procedure TGLSLProgram.SetAttribute(const AName: string; const Value: TVector4Double);
2122 begin
2123 Attribute(AName).SetValue(Value);
2124 end;
2125 }
2126 {$endif}
2127
2128 class function TGLSLProgram.GetCurrent: TGLSLProgram;
2129 begin
2130 Result := RenderContext.CurrentProgram;
2131 end;
2132
2133 class procedure TGLSLProgram.SetCurrent(const Value: TGLSLProgram);
2134 begin
2135 RenderContext.CurrentProgram := Value;
2136 end;
2137
2138 end.