Debian Codegraph @

src/scene/castlerendererinternalshader_light.inc

raw
1 {%MainUnit castlerendererinternalshader.pas}
2 {
3 Copyright 2010-2024 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 { Generating shader code for lights. }
18
19 {$ifdef read_interface}
20
21 //type
22 TLightingModel = (lmPhong, lmPhysical, lmUnlit);
23
24 TLightUniforms = class
25 Number: Cardinal;
26 ShaderProgram: TGLSLProgram;
27
28 { Current values provided to OpenGL(ES) for these uniforms.
29
30 Note that they are initially filled with zero.
31
32 This is correct, as OpenGL and OpenGLES docs say:
33 """
34 All active uniform variables defined in a program object
35 are initialized to 0 when the program object is linked successfully.
36 """
37
38 https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml
39 https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glUniform.xhtml
40 }
41 Position: TVector3;
42 Radius: Single;
43 SpotCosCutoff: Single;
44 SpotBeamWidth: Single;
45 SpotDirection: TVector3;
46 SpotExponent: Single;
47 SpotCutoff: Single;
48 Attenuation: TVector3;
49 AmbientColor, Color: TVector3;
50
51 procedure SetUniform(const NamePattern: String;
52 var CurrentValue: Single; const NewValue: Single); overload;
53 procedure SetUniform(const NamePattern: String;
54 var CurrentValue: TVector3; const NewValue: TVector3); overload;
55 procedure SetUniform(const NamePattern: String;
56 var CurrentValue: TVector4; const NewValue: TVector4); overload;
57 end;
58
59 TLightUniformsList = {$ifdef FPC}specialize{$endif} TObjectList<TLightUniforms>;
60
61 { Manage GLSL defines for TLightShader. }
62 TLightDefine = (
63 ldTypePositional,
64 ldTypeSpot,
65 ldTypeEnvironment,
66 ldTypePunctual,
67 ldHasAttenuation,
68 ldHasRadius,
69 ldHasAmbient,
70 ldHasSpecular,
71 ldHasBeamWidth,
72 ldHasSpotExponent);
73
74 { Generating shader code to handle a single light. }
75 TLightShader = class
76 private
77 Number: Cardinal;
78 Node: TAbstractLightNode;
79 Light: PLightInstance;
80 Shader: TShader;
81 { Code calculated (on demand, when method called) using above vars. }
82 FCode: TShaderSource;
83 { Calculated by Prepare. Stored as TLightDefine array,
84 since TLightShader.Prepare is executed very often and must be fast.
85 Only TLightShader.Code actually changes it to a string. }
86 Defines: array [0..9] of TLightDefine;
87 DefinesCount: Cardinal;
88 public
89 RenderingCamera: TRenderingCamera; //< Set this after construction.
90 LightingModel: TLightingModel;
91 destructor Destroy; override;
92 { Prepare some stuff for Code generation, update Hash for this light shader. }
93 procedure Prepare(var Hash: TShaderCodeHash; const LightNumber: Cardinal);
94 function Code: TShaderSource;
95 procedure SetUniformsOnce(AProgram: TX3DShaderProgram);
96 procedure SetDynamicUniforms(AProgram: TX3DShaderProgram);
97 end;
98
99 TLightShaders = class({$ifdef FPC}specialize{$endif} TObjectList<TLightShader>)
100 private
101 function Find(const Node: TAbstractLightNode; out Shader: TLightShader): boolean;
102 end;
103
104 {$endif read_interface}
105
106 {$ifdef read_implementation}
107
108 { TLightUniforms ------------------------------------------------------- }
109
110 procedure TLightUniforms.SetUniform(const NamePattern: String;
111 var CurrentValue: Single; const NewValue: Single);
112 begin
113 if CurrentValue <> NewValue then
114 begin
115 ShaderProgram.SetUniform(Format(NamePattern, [Number]), NewValue);
116 CurrentValue := NewValue;
117 end;
118 end;
119
120 procedure TLightUniforms.SetUniform(const NamePattern: String;
121 var CurrentValue: TVector3; const NewValue: TVector3);
122 begin
123 if not TVector3.PerfectlyEquals(CurrentValue, NewValue) then
124 begin
125 ShaderProgram.SetUniform(Format(NamePattern, [Number]), NewValue);
126 CurrentValue := NewValue;
127 end;
128 end;
129
130 procedure TLightUniforms.SetUniform(const NamePattern: String;
131 var CurrentValue: TVector4; const NewValue: TVector4);
132 begin
133 if not TVector4.PerfectlyEquals(CurrentValue, NewValue) then
134 begin
135 ShaderProgram.SetUniform(Format(NamePattern, [Number]), NewValue);
136 CurrentValue := NewValue;
137 end;
138 end;
139
140 { TLightShader --------------------------------------------------------------- }
141
142 destructor TLightShader.Destroy;
143 begin
144 FreeAndNil(FCode);
145 inherited;
146 end;
147
148 const
149 LightDefines: array [TLightDefine] of record
150 Name: String;
151 Hash: UInt32;
152 end =
153 ( (Name: 'LIGHT%d_TYPE_POSITIONAL' ; Hash: 107; ),
154 (Name: 'LIGHT%d_TYPE_SPOT' ; Hash: 109; ),
155 (Name: 'LIGHT%d_TYPE_ENVIRONMENT' ; Hash: 421; ),
156 (Name: 'LIGHT%d_TYPE_PUNCTUAL' ; Hash: 443; ),
157 (Name: 'LIGHT%d_HAS_ATTENUATION' ; Hash: 113; ),
158 (Name: 'LIGHT%d_HAS_RADIUS' ; Hash: 127; ),
159 (Name: 'LIGHT%d_HAS_AMBIENT' ; Hash: 131; ),
160 (Name: 'LIGHT%d_HAS_SPECULAR' ; Hash: 137; ),
161 (Name: 'LIGHT%d_HAS_BEAM_WIDTH' ; Hash: 139; ),
162 (Name: 'LIGHT%d_HAS_SPOT_EXPONENT'; Hash: 149; )
163 );
164
165 procedure TLightShader.Prepare(var Hash: TShaderCodeHash; const LightNumber: Cardinal);
166
167 procedure Define(const D: TLightDefine);
168 begin
169 Assert(DefinesCount <= High(Defines), 'Too many light #defines, increase High(TLightShader.Defines)');
170 Defines[DefinesCount] := D;
171 Inc(DefinesCount);
172 Hash.AddInteger(LightDefines[D].Hash * (LightNumber + 1));
173 end;
174
175 begin
176 DefinesCount := 0;
177 Hash.AddInteger(101);
178
179 if Node is TAbstractPositionalLightNode then
180 begin
181 Define(ldTypePositional);
182 if Node is TSpotLightNode_1 then
183 begin
184 Define(ldTypeSpot);
185 Define(ldHasSpotExponent);
186 end else
187 if Node is TSpotLightNode then
188 begin
189 Define(ldTypeSpot);
190 Define(ldHasBeamWidth);
191 end;
192
193 if TAbstractPositionalLightNode(Node).HasAttenuation then
194 Define(ldHasAttenuation);
195
196 if TAbstractPositionalLightNode(Node).HasRadius then
197 Define(ldHasRadius);
198 end;
199 if Node.FdAmbientIntensity.Value <> 0 then
200 Define(ldHasAmbient);
201 if (Shader.Material is TPhongMaterialInfo) and
202 (not TPhongMaterialInfo(Shader.Material).SpecularColor.IsPerfectlyZero) then
203 Define(ldHasSpecular);
204 if Node is TAbstractPunctualLightNode then
205 Define(ldTypePunctual);
206 if Node is TEnvironmentLightNode then
207 Define(ldTypeEnvironment);
208 end;
209
210 function TLightShader.Code: TShaderSource;
211
212 { Convert Defines list into a string of GLSL code. }
213 function DefinesStr: String;
214 var
215 I: Integer;
216 begin
217 Result := '';
218 for I := 0 to DefinesCount - 1 do
219 Result := Result + '#define ' + Format(LightDefines[Defines[I]].Name, [Number]) + NL;
220 end;
221
222 const
223 TemplateLight: array [TLightingModel] of String = (
224 {$I lighting_model_phong_add_light.glsl.inc},
225 {$I lighting_model_physical_add_light.glsl.inc},
226 {$I lighting_model_unlit_add_light.glsl.inc}
227 );
228 var
229 LightShader: String;
230 LightingStage: TShaderType;
231 begin
232 if FCode = nil then
233 begin
234 FCode := TShaderSource.Create;
235
236 LightShader := TemplateLight[LightingModel];
237 LightShader := StringReplace(LightShader,
238 '<Light>', IntToStr(Number), [rfReplaceAll]);
239
240 if Shader.PhongShading then
241 LightingStage := stFragment
242 else
243 LightingStage := stVertex;
244 FCode[LightingStage].Add(DefinesStr + LightShader);
245
246 if Node <> nil then
247 Shader.EnableEffects(Node.FdEffects, FCode);
248 end;
249
250 Result := FCode;
251 end;
252
253 procedure TLightShader.SetUniformsOnce(AProgram: TX3DShaderProgram);
254
255 procedure SetEnvironmentLightUniforms(const EnvLight: TEnvironmentLightNode);
256 begin
257 if EnvLight.FdDiffuseTexture.Value <> nil then
258 AProgram.UniformsTextures.Add(EnvLight.FdDiffuseTexture);
259 if EnvLight.FdSpecularTexture.Value <> nil then
260 AProgram.UniformsTextures.Add(EnvLight.FdSpecularTexture);
261 end;
262
263 begin
264 if Node is TEnvironmentLightNode then
265 SetEnvironmentLightUniforms(TEnvironmentLightNode(Node));
266 end;
267
268 procedure TLightShader.SetDynamicUniforms(AProgram: TX3DShaderProgram);
269 var
270 Uniforms: TLightUniforms;
271 Color3, AmbientColor3: TVector3;
272 Position: TVector4;
273 LiPos: TAbstractPositionalLightNode;
274 LiSpot1: TSpotLightNode_1;
275 LiSpot: TSpotLightNode;
276 LightToEyeSpace: PMatrix4;
277 begin
278 while Number >= AProgram.FLightUniformsList.Count do
279 begin
280 Uniforms := TLightUniforms.Create;
281 Uniforms.Number := AProgram.FLightUniformsList.Count;
282 Uniforms.ShaderProgram := AProgram;
283 AProgram.FLightUniformsList.Add(Uniforms);
284 end;
285 Uniforms := AProgram.FLightUniformsList[Number];
286
287 { calculate Color3 = light color * light intensity }
288 Color3 := Node.FdColor.Value * Node.FdIntensity.Value;
289
290 { calculate AmbientColor3 = light color * light ambient intensity }
291 AmbientColor3 := Node.FdColor.Value * Node.FdAmbientIntensity.Value;
292
293 if Node is TAbstractPunctualLightNode then
294 begin
295 if Light^.WorldCoordinates then
296 LightToEyeSpace := @RenderingCamera.Matrix
297 else
298 LightToEyeSpace := @Shader.SceneModelView;
299
300 { This is incorrect, at least on Linux x86_64 and Darwin x86_64
301 (works OK on Darwin i386), with FPC 3.0.2.
302 Possibly TGenericMatrix4.Multiply has then equal addresses
303 for Result and argument, although I didn't manage to "catch it red-handed"
304 (it seems that merely adding a check to TGenericMatrix4.Multiply
305 about it, disables this optimization, so everything is OK then). }
306 // Position := Light^.Position;
307 // Position := LightToEyeSpace^ * Position;
308 Position := LightToEyeSpace^ * Light^.Position;
309
310 { Note that we cut off last component of Node.Position,
311 we don't need it. #defines tell the shader whether we deal with directional
312 or positional light. }
313 Uniforms.SetUniform('castle_LightSource%dPosition', Uniforms.Position,
314 Position.XYZ);
315
316 if Node is TAbstractPositionalLightNode then
317 begin
318 LiPos := TAbstractPositionalLightNode(Node);
319
320 if LiPos.HasRadius then
321 begin
322 Uniforms.SetUniform('castle_LightSource%dRadius', Uniforms.Radius,
323 Approximate3DScale(LightToEyeSpace^) * Light^.Radius);
324 end;
325
326 if LiPos is TSpotLightNode_1 then
327 begin
328 LiSpot1 := TSpotLightNode_1(Node);
329 Uniforms.SetUniform('castle_LightSource%dSpotCosCutoff', Uniforms.SpotCosCutoff,
330 LiSpot1.SpotCosCutoff);
331 Uniforms.SetUniform('castle_LightSource%dSpotDirection', Uniforms.SpotDirection,
332 LightToEyeSpace^.MultDirection(Light^.Direction));
333 Uniforms.SetUniform('castle_LightSource%dSpotExponent', Uniforms.SpotExponent,
334 LiSpot1.SpotExponent);
335 end else
336 if LiPos is TSpotLightNode then
337 begin
338 LiSpot := TSpotLightNode(Node);
339 Uniforms.SetUniform('castle_LightSource%dSpotCosCutoff', Uniforms.SpotCosCutoff,
340 LiSpot.SpotCosCutoff);
341 Uniforms.SetUniform('castle_LightSource%dSpotDirection', Uniforms.SpotDirection,
342 LightToEyeSpace^.MultDirection(Light^.Direction));
343 Uniforms.SetUniform('castle_LightSource%dBeamWidth', Uniforms.SpotBeamWidth,
344 LiSpot.FdBeamWidth.Value);
345 Uniforms.SetUniform('castle_LightSource%dSpotCutoff', Uniforms.SpotCutoff,
346 LiSpot.FdCutOffAngle.Value);
347 end;
348
349 if LiPos.HasAttenuation then
350 Uniforms.SetUniform('castle_LightSource%dAttenuation', Uniforms.Attenuation,
351 LiPos.FdAttenuation.Value);
352 end;
353 end;
354
355 if Node.FdAmbientIntensity.Value <> 0 then
356 Uniforms.SetUniform('castle_LightSource%dAmbientColor', Uniforms.AmbientColor, AmbientColor3);
357
358 Uniforms.SetUniform('castle_LightSource%dColor', Uniforms.Color, Color3);
359 end;
360
361 { TLightShaders -------------------------------------------------------------- }
362
363 function TLightShaders.Find(const Node: TAbstractLightNode; out Shader: TLightShader): boolean;
364 var
365 I: Integer;
366 begin
367 for I := 0 to Count - 1 do
368 if Items[I].Node = Node then
369 begin
370 Shader := Items[I];
371 Exit(true);
372 end;
373 Shader := nil;
374 Result := false;
375 end;
376
377 {$endif read_implementation}