Debian Codegraph @

src/scene/castlerendererinternalshader_texture.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 texture and texture coordinates. }
18
19 {$ifdef read_interface}
20
21 //type
22 { Setup the necessary shader things to pass texture coordinates. }
23 TTextureCoordinateShader = class
24 private
25 TextureUnit: Cardinal;
26 HasMatrixTransform: boolean;
27
28 { Name of texture coordinate varying vec4 vector. }
29 class function CoordName(const TexUnit: Cardinal): String;
30 { Name of texture matrix mat4 uniform. }
31 class function MatrixName(const TexUnit: Cardinal): String;
32 public
33 { Update Hash for this texture shader. }
34 procedure Prepare(var Hash: TShaderCodeHash); virtual;
35 procedure Enable(const MainTextureMapping: Integer; const MultiTextureColor: TCastleColor;
36 var TextureApply, TextureColorDeclare,
37 TextureCoordInitialize, TextureCoordMatrix,
38 TextureAttributeDeclare, TextureVaryingDeclareVertex, TextureVaryingDeclareFragment, TextureUniformsDeclare,
39 GeometryVertexDeclare, GeometryVertexSet, GeometryVertexZero, GeometryVertexAdd: String); virtual;
40 end;
41
42 { Setup the necessary shader things to query a texture using texture coordinates. }
43 TTextureShader = class(TTextureCoordinateShader)
44 private
45 TextureType: TTextureType;
46 Node: TAbstractSingleTextureNode;
47 Env: TTextureEnv;
48 Shader: TShader;
49
50 { Uniform to set for this texture. May be empty. }
51 UniformName: String;
52 UniformValue: Integer;
53
54 class var TextureEnvWarningDone: Boolean;
55
56 { Mix texture colors into fragment color, based on TTextureEnv specification. }
57 class function TextureEnvMix(const AEnv: TTextureEnv; const MultiTextureColor: TCastleColor;
58 const FragmentColor, CurrentTexture: String;
59 const ATextureUnit: Cardinal): String;
60 public
61 { Update Hash for this texture shader. }
62 procedure Prepare(var Hash: TShaderCodeHash); override;
63 procedure Enable(const MainTextureMapping: Integer; const MultiTextureColor: TCastleColor;
64 var TextureApply, TextureColorDeclare,
65 TextureCoordInitialize, TextureCoordMatrix,
66 TextureAttributeDeclare, TextureVaryingDeclareVertex, TextureVaryingDeclareFragment, TextureUniformsDeclare,
67 GeometryVertexDeclare, GeometryVertexSet, GeometryVertexZero, GeometryVertexAdd: String); override;
68 end;
69
70 TTextureCoordinateShaderList = {$ifdef FPC}specialize{$endif} TObjectList<TTextureCoordinateShader>;
71
72 {$endif read_interface}
73
74 {$ifdef read_implementation}
75
76 { TTextureCoordinateShader --------------------------------------------------- }
77
78 class function TTextureCoordinateShader.CoordName(const TexUnit: Cardinal): String;
79 begin
80 Result := Format('castle_TexCoord%d', [TexUnit]);
81 end;
82
83 class function TTextureCoordinateShader.MatrixName(const TexUnit: Cardinal): String;
84 begin
85 Result := Format('castle_TextureMatrix%d', [TexUnit]);
86 end;
87
88 procedure TTextureCoordinateShader.Prepare(var Hash: TShaderCodeHash);
89 var
90 IntHash: UInt32;
91 begin
92 {$include norqcheckbegin.inc}
93 IntHash :=
94 1 +
95 971 * Ord(HasMatrixTransform);
96 Hash.AddInteger(977 * (TextureUnit + 1) * IntHash);
97 {$include norqcheckend.inc}
98 end;
99
100 procedure TTextureCoordinateShader.Enable(const MainTextureMapping: Integer; const MultiTextureColor: TCastleColor;
101 var TextureApply, TextureColorDeclare,
102 TextureCoordInitialize, TextureCoordMatrix,
103 TextureAttributeDeclare, TextureVaryingDeclareVertex, TextureVaryingDeclareFragment, TextureUniformsDeclare,
104 GeometryVertexDeclare, GeometryVertexSet, GeometryVertexZero, GeometryVertexAdd: String);
105 var
106 TexCoordName, TexMatrixName: String;
107 begin
108 TexCoordName := CoordName(TextureUnit);
109 TexMatrixName := MatrixName(TextureUnit);
110
111 TextureCoordInitialize := TextureCoordInitialize +
112 Format('%s = castle_MultiTexCoord%d;' + NL,
113 [TexCoordName, TextureUnit]);
114 TextureAttributeDeclare := TextureAttributeDeclare +
115 Format('attribute vec4 castle_MultiTexCoord%d;' + NL, [TextureUnit]);
116 TextureVaryingDeclareVertex := TextureVaryingDeclareVertex + Format(
117 'varying vec4 %s;' + NL, [TexCoordName]);
118 TextureVaryingDeclareFragment := TextureVaryingDeclareFragment + Format(
119 '#ifdef HAS_GEOMETRY_SHADER' + NL +
120 ' #define %s %0:s_geoshader' + NL +
121 '#endif' + NL +
122 'varying vec4 %0:s;' + NL, [TexCoordName]);
123
124 if HasMatrixTransform then
125 TextureCoordMatrix := TextureCoordMatrix + Format('%s = %s * %0:s;' + NL,
126 [TexCoordName, TexMatrixName]);
127
128 GeometryVertexDeclare := GeometryVertexDeclare + Format(
129 'in vec4 %s[CASTLE_GEOMETRY_INPUT_SIZE];' + NL +
130 'out vec4 %0:s_geoshader;', [TexCoordName]);
131 GeometryVertexSet := GeometryVertexSet +
132 Format('%s_geoshader = %0:s[index];' + NL, [TexCoordName]);
133 GeometryVertexZero := GeometryVertexZero + Format('%s_geoshader = vec4(0.0);'
134 + NL, [TexCoordName]);
135 { NVidia will warn here "... might be used before being initialized".
136 Which is of course true --- but we depend that author will always call
137 geometryVertexZero() before geometryVertexAdd(). }
138 GeometryVertexAdd := GeometryVertexAdd +
139 Format('%s_geoshader += %0:s[index] * scale;' + NL, [TexCoordName]);
140 end;
141
142 { TTextureShader ------------------------------------------------------------- }
143
144 procedure TTextureShader.Prepare(var Hash: TShaderCodeHash);
145 var
146 IntHash: UInt32;
147 begin
148 inherited;
149
150 {$include norqcheckbegin.inc}
151 IntHash :=
152 1 +
153 181 * Ord(TextureType) +
154 Env.Hash;
155 Hash.AddInteger(179 * (TextureUnit + 1) * IntHash);
156 { Don't directly add Node to the Hash, it would prevent a lot of sharing.
157 Node is only used to get effects. }
158 Hash.AddEffects(Node.FdEffects);
159 {$include norqcheckend.inc}
160 end;
161
162 class function TTextureShader.TextureEnvMix(const AEnv: TTextureEnv; const MultiTextureColor: TCastleColor;
163 const FragmentColor, CurrentTexture: String;
164 const ATextureUnit: Cardinal): String;
165
166 procedure Warn(const S: String; const Args: array of const);
167 begin
168 if not TextureEnvWarningDone then
169 begin
170 TextureEnvWarningDone := true;
171 WritelnWarning('MultiTexture mixing', Format(S, Args));
172 end;
173 end;
174
175 { GLSL code to express MultiTextureColor value. }
176 function MultiTextureColorStr: String;
177 begin
178 Result := FormatDot('vec4(%f, %f, %f, %f)', [
179 MultiTextureColor.X,
180 MultiTextureColor.Y,
181 MultiTextureColor.Z,
182 MultiTextureColor.W
183 ]);
184 end;
185
186 type
187 TChannels = (chAll, chRgb, chAlpha);
188
189 { GLSL code to update FragmentColor based on given Combine operation. }
190 function CombineCode(const Combine: TCombine;
191 const Source: TColorSource;
192 const SourceArgument: TTextureEnvArgument;
193 const Channels: TChannels): String;
194
195 { GLSL code to express given TColorSource value. }
196 function SourceStr(const Source: TColorSource): String;
197 begin
198 case Source of
199 csCurrentTexture : Result := CurrentTexture;
200 csPreviousTexture: Result := FragmentColor;
201 csMaterial : Result := 'vec4(0.8, 0.8, 0.8, 1.0)'; // just Material.diffuseColor default
202 csConstant : Result := MultiTextureColorStr;
203 {$ifndef COMPILER_CASE_ANALYSIS}
204 else raise EInternalError.Create('SourceStr:TColorSource?');
205 {$endif}
206 end;
207 end;
208
209 var
210 FragmentColorCh, CurrentTextureCh, Arg2Ch, ChannelsStr, ChannelsFromScalar: String;
211 Arg2: String;
212 begin
213 { calculate Arg2, GLSL code that says "what is coming from MultiTexture.source" }
214 Arg2 := SourceStr(Source);
215
216 { calculate ChannelsStr, ChannelsFromScalar }
217 case Channels of
218 chAll :
219 begin
220 ChannelsStr := ''; // set all RGBA of FragmentColor
221 ChannelsFromScalar := 'vec4';
222 end;
223 chRgb :
224 begin
225 ChannelsStr := '.rgb'; // set only RGB of FragmentColor
226 ChannelsFromScalar := 'vec3';
227 end;
228 chAlpha:
229 begin
230 ChannelsStr := '.a'; // set only alpha of FragmentColor
231 ChannelsFromScalar := '';
232 end;
233 {$ifndef COMPILER_CASE_ANALYSIS}
234 else raise EInternalError.Create('Channels?');
235 {$endif}
236 end;
237
238 FragmentColorCh := FragmentColor + ChannelsStr;
239 CurrentTextureCh := CurrentTexture + ChannelsStr;
240 Arg2Ch := Arg2 + ChannelsStr;
241
242 { By default, set up simplest modulate operation.
243 The "case" below may override this to something better. }
244 Result := FragmentColorCh + ' *= ' + CurrentTextureCh + ';';
245
246 case Combine of
247 coModulate:
248 if Arg2 = FragmentColor then
249 // optimize GLSL code
250 Result := FragmentColorCh + ' *= ' + CurrentTextureCh + ';'
251 else
252 Result := FragmentColorCh + ' = ' + CurrentTextureCh + ' * ' + Arg2Ch + ';';
253 coReplace:
254 begin
255 if SourceArgument = ta0 then
256 { mode is SELECTARG2 }
257 Result := FragmentColorCh + ' = ' + Arg2Ch + ';'
258 else
259 { assume CurrentTextureArgument = ta0, mode = REPLACE or SELECTARG1 }
260 Result := FragmentColorCh + ' = ' + CurrentTextureCh + ';';
261 end;
262 coAddSigned:
263 Result := FragmentColorCh + ' = ' + CurrentTextureCh + ' + ' + Arg2Ch +
264 ' - ' + ChannelsFromScalar + '(0.5);';
265 coAdd:
266 if Arg2 = FragmentColor then
267 // optimize GLSL code
268 Result := FragmentColorCh + ' += ' + CurrentTextureCh + ';'
269 else
270 Result := FragmentColorCh + ' = ' + CurrentTextureCh + ' + ' + Arg2Ch + ';';
271 coSubtract:
272 Result := FragmentColorCh + ' = ' + CurrentTextureCh + ' - ' + Arg2Ch + ';';
273 coBlend:
274 Result := FragmentColorCh + ' = mix(' + FragmentColorCh + ', ' +
275 CurrentTextureCh + ', ' + SourceStr(AEnv.BlendAlphaSource) + '.a);';
276 coDot3Rgb,
277 coDot3Rgba:
278 Result := FragmentColorCh + ' = ' + ChannelsFromScalar + '(dot(' +
279 '2 * (' + CurrentTexture + '.rgb - vec3(0.5)), ' +
280 '2 * (' + Arg2 + '.rgb - vec3(0.5))));';
281 else
282 Warn('Not supported in GLSL pipeline: combine value %d', [Ord(Combine)]);
283 end;
284 end;
285
286 begin
287 if AEnv.Disabled then Exit('');
288
289 { Note that we ignore AEnv.CurrentTextureArgument.
290 Which is OK -- it is always ta0 in practice, except for X3D "SELECTARG2" mode
291 (which for us is a special case of coReplace, detected looking at AEnv.SourceArgument).
292
293 We know that AEnv.SourceArgument is always ta1, except
294 - it is taNone in case of X3D "REPLACE" mode (eqivalent "SELECTARG1")
295 - it is ta0 in case of X3D "SELECTARG2" mode
296
297 So, while we don't handle all *theoretically possible* cases of
298 AEnv.CurrentTextureArgument and AEnv.SourceArgument, we don't need to.
299 We detect and handle SELECTARG2 specially, in other cases
300 we assume
301 - AEnv.CurrentTextureArgument = ta0,
302 - AEnv.SourceArgument = ta1,
303 and this is enough to cover all *actually possible* (set by CastleRendererInternalTextureEnv)
304 cases.
305 }
306
307 if (AEnv.Combine [cRGB] = AEnv.Combine [cAlpha]) and
308 (AEnv.Source [cRGB] = AEnv.Source [cAlpha]) and
309 (AEnv.SourceArgument[cRGB] = AEnv.SourceArgument[cAlpha]) then
310 begin
311 { Do the operation on whole RGBA. }
312 Result := CombineCode(AEnv.Combine[cRGB], AEnv.Source[cRGB], AEnv.SourceArgument[cRGB], chAll) + NL;
313 end else
314 begin
315 Result :=
316 CombineCode(AEnv.Combine[cRGB] , AEnv.Source[cRGB ], AEnv.SourceArgument[cRGB] , chRgb) + NL +
317 CombineCode(AEnv.Combine[cAlpha], AEnv.Source[cAlpha], AEnv.SourceArgument[cAlpha], chAlpha) + NL;
318 end;
319
320 if AEnv.Scale[cRGB] = AEnv.Scale[cAlpha] then
321 begin
322 { Do the scaling on whole RGBA. }
323 if AEnv.Scale[cRGB] <> 1 then
324 Result := Result + FragmentColor + ' *= ' + FloatToStrDot(AEnv.Scale[cRGB]) + ';' + NL;
325 end else
326 begin
327 if AEnv.Scale[cRGB] <> 1 then
328 Result := Result + FragmentColor + '.rgb *= ' + FloatToStrDot(AEnv.Scale[cRGB]) + ';' + NL;
329 if AEnv.Scale[cAlpha] <> 1 then
330 Result := Result + FragmentColor + '.a *= ' + FloatToStrDot(AEnv.Scale[cAlpha]) + ';' + NL;
331 end;
332
333 case AEnv.TextureFunction of
334 tfComplement : Result := Result + FragmentColor + '.rgb = vec3(1.0) - ' + FragmentColor + '.rgb;' + NL;
335 tfAlphaReplicate: Result := Result + FragmentColor + '.rgb = vec3(' + FragmentColor + '.a);' + NL;
336 else ;
337 end;
338 end;
339
340 procedure TTextureShader.Enable(const MainTextureMapping: Integer; const MultiTextureColor: TCastleColor;
341 var TextureApply, TextureColorDeclare,
342 TextureCoordInitialize, TextureCoordMatrix,
343 TextureAttributeDeclare, TextureVaryingDeclareVertex, TextureVaryingDeclareFragment, TextureUniformsDeclare,
344 GeometryVertexDeclare, GeometryVertexSet, GeometryVertexZero, GeometryVertexAdd: String);
345 const
346 SamplerFromTextureType: array [TTextureType] of string =
347 ('sampler2D', 'samplerCube', 'sampler3D', '');
348 var
349 TextureSampleCall, TexCoordName: String;
350 Code: TShaderSource;
351 SamplerType: String;
352 begin
353 inherited;
354
355 if TextureType <> ttShader then
356 begin
357 UniformName := Format('castle_texture_%d', [TextureUnit]);
358 UniformValue := TextureUnit;
359 end else
360 UniformName := '';
361
362 if MainTextureMapping <> -1 then
363 TexCoordName := CoordName(MainTextureMapping)
364 else
365 TexCoordName := CoordName(TextureUnit);
366
367 SamplerType := SamplerFromTextureType[TextureType];
368
369 if TextureColorDeclare = '' then
370 TextureColorDeclare := 'vec4 texture_color;' + NL;
371 case TextureType of
372 tt2D:
373 { texture2DProj reasoning:
374 Most of the time, 'texture2D(%s, %s.st)' would be enough.
375 But we may get 4D tex coords (that is, with last component <> 1)
376 - through TextureCoordinate4D
377 - through projected texture mapping, when using perspective light
378 (spot light) or perspective viewpoint.
379
380 TextureUnit = 0 check reasoning:
381 Even when HAS_TEXTURE_COORD_SHIFT is defined (PLUG_texture_coord_shift
382 was used), use it only for 0th texture unit. Parallax bump mapping
383 calculates the shift, assuming that transformations to tangent space
384 follow 0th texture coordinates. Also, for parallax bump mapping,
385 we have to assume the 0th texture has simple 2D coords (not 4D). }
386 if TextureUnit = 0 then
387 TextureSampleCall := NL+
388 '#ifdef HAS_TEXTURE_COORD_SHIFT' +NL+
389 ' texture2D(%0:s, texture_coord_shifted(%1:s.st))' +NL+
390 '#else' +NL+
391 ' texture2DProj(%0:s, %1:s)' +NL+
392 '#endif' + NL else
393 TextureSampleCall := 'texture2DProj(%0:s, %1:s)';
394 ttCubeMap : TextureSampleCall := 'textureCube(%s, %s.xyz)';
395 { For 3D textures, remember we may get 4D tex coords
396 through TextureCoordinate4D, so we have to use texture3DProj }
397 tt3D : TextureSampleCall := 'texture3DProj(%s, %s)';
398 ttShader : TextureSampleCall := 'vec4(1.0, 0.0, 1.0, 1.0)';
399 {$ifndef COMPILER_CASE_ANALYSIS}
400 else raise EInternalError.Create('TShader.EnableTexture:TextureType?');
401 {$endif}
402 end;
403
404 Code := TShaderSource.Create;
405 try
406 if TextureType <> ttShader then
407 begin
408 { Optimization to not call castle_texture_color_to_linear when not needed.
409 Although it should do nothing when ColorSpaceLinear=false,
410 but to make sure it takes zero time we just not call it at all. }
411 if Shader.ColorSpaceLinear then
412 TextureSampleCall := 'castle_texture_color_to_linear(' + TextureSampleCall + ')';
413 Code[stFragment].Add(Format(
414 'texture_color = ' + TextureSampleCall + ';' +NL+
415 '/* PLUG: texture_color (texture_color, %0:s, %1:s) */' +NL,
416 [UniformName, TexCoordName]))
417 end else
418 Code[stFragment].Add(Format(
419 'texture_color = ' + TextureSampleCall + ';' +NL+
420 '/* PLUG: texture_color (texture_color, %0:s) */' +NL,
421 [TexCoordName]));
422
423 Shader.EnableEffects(Node.FdEffects, Code, true);
424
425 { Add generated Code to Shader.Source. Code[stFragment][0] for texture
426 is a little special, we add it to TextureApply that
427 will be directly placed within the source. }
428 TextureApply := TextureApply + Code[stFragment][0];
429 Shader.Source.Append(Code, stFragment);
430 finally FreeAndNil(Code) end;
431
432 TextureApply := TextureApply + TextureEnvMix(Env, MultiTextureColor,
433 'fragment_color', 'texture_color', TextureUnit) + NL;
434
435 if TextureType <> ttShader then
436 TextureUniformsDeclare := TextureUniformsDeclare + Format('uniform %s %s;' + NL,
437 [SamplerType, UniformName]);
438 end;
439
440 {$endif read_implementation}