| 1 |
{ |
| 2 |
Copyright 2010-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 |
{ Setting up OpenGL shaders (TShader). Internal for CastleRenderer. @exclude } |
| 17 |
unit CastleRendererInternalShader; |
| 18 |
|
| 19 |
{$I castleconf.inc} |
| 20 |
|
| 21 |
interface |
| 22 |
|
| 23 |
uses Generics.Collections, |
| 24 |
CastleVectors, CastleGLShaders, CastleColors, |
| 25 |
X3DTime, X3DFields, X3DNodes, CastleUtils, CastleBoxes, |
| 26 |
CastleRendererInternalTextureEnv, CastleStringUtils, CastleRenderOptions, |
| 27 |
CastleShapes, CastleRectangles, CastleTransform, CastleInternalGeometryArrays; |
| 28 |
|
| 29 |
{$define read_interface} |
| 30 |
|
| 31 |
type |
| 32 |
TShader = class; |
| 33 |
TShaderSource = class; |
| 34 |
TX3DShaderProgram = class; |
| 35 |
|
| 36 |
TTextureType = (tt2D, ttCubeMap, tt3D, ttShader); |
| 37 |
|
| 38 |
TTexGenerationComponent = (tgEye, tgObject); |
| 39 |
TTexGenerationComplete = (tgSphere, tgNormal, tgReflection, tgcMirrorPlane); |
| 40 |
TTexComponent = 0..3; |
| 41 |
|
| 42 |
TFogCoordinateSource = ( |
| 43 |
{ Fog is determined by depth (distance to camera). } |
| 44 |
fcDepth, |
| 45 |
{ Fog is determined by explicit coordinate (per-vertex castle_FogCoord attribute). } |
| 46 |
fcPassedCoordinate); |
| 47 |
|
| 48 |
TBoundingBoxEvent = function: TBox3D of object; |
| 49 |
|
| 50 |
{ GLSL program that may be used by the X3D renderer. |
| 51 |
Provides some extra features, above the standard TGLSLProgram, |
| 52 |
but does not require to link the shader using TShader algorithm. } |
| 53 |
TX3DShaderProgramBase = class(TGLSLProgram) |
| 54 |
public |
| 55 |
{ Uniforms initialized after linking. |
| 56 |
Initializing them only once after linking allows the mesh renderer to go fast. } |
| 57 |
UniformCastle_ModelViewMatrix, |
| 58 |
UniformCastle_ProjectionMatrix, |
| 59 |
UniformCastle_NormalMatrix, |
| 60 |
UniformCastle_MaterialDiffuseAlpha, |
| 61 |
UniformCastle_MaterialBaseAlpha, |
| 62 |
UniformCastle_MaterialEmissiveAlpha, |
| 63 |
UniformCastle_MaterialShininess, |
| 64 |
UniformCastle_MaterialEmissive, |
| 65 |
UniformCastle_MaterialAmbient, |
| 66 |
UniformCastle_MaterialSpecular, |
| 67 |
UniformCastle_MaterialMetallic, |
| 68 |
UniformCastle_MaterialRoughness, |
| 69 |
UniformCastle_GlobalAmbient, |
| 70 |
UniformCastle_UnlitColor: TGLSLUniform; |
| 71 |
|
| 72 |
{ Attributes initialized after linking. |
| 73 |
Initializing them only once after linking allows the mesh renderer to go fast. } |
| 74 |
AttributeCastle_Vertex, |
| 75 |
AttributeCastle_Normal, |
| 76 |
AttributeCastle_Tangent, |
| 77 |
AttributeCastle_ColorPerVertex, |
| 78 |
AttributeCastle_FogCoord: TGLSLAttribute; |
| 79 |
|
| 80 |
procedure Link; override; |
| 81 |
end; |
| 82 |
|
| 83 |
{$I castlerendererinternalshader_hash.inc} |
| 84 |
{$I castlerendererinternalshader_light.inc} |
| 85 |
{$I castlerendererinternalshader_texture.inc} |
| 86 |
{$I castlerendererinternalshader_shadowmap.inc} |
| 87 |
{$I castlerendererinternalshader_mirrorplane.inc} |
| 88 |
{$I castlerendererinternalshader_surfacetexture.inc} |
| 89 |
{$I castlerendererinternalshader_bumpmapping.inc} |
| 90 |
|
| 91 |
{ GLSL program integrated with VRML/X3D and TShader. |
| 92 |
Allows to bind uniform values from VRML/X3D fields, |
| 93 |
and to observe VRML/X3D events and automatically update uniform values. |
| 94 |
Also allows to initialize and check program by TShader.LinkProgram, |
| 95 |
and get a hash of it by TShader.CodeHash. } |
| 96 |
TX3DShaderProgram = class(TX3DShaderProgramBase) |
| 97 |
private |
| 98 |
{ Events where we registered our EventReceive method. } |
| 99 |
EventsObserved: TX3DEventList; |
| 100 |
|
| 101 |
{ Current state of lights uniforms for this shader. } |
| 102 |
FLightUniformsList: TLightUniformsList; |
| 103 |
|
| 104 |
{ Set uniform variable from VRML/X3D field value. |
| 105 |
Uniform name is contained in UniformName. UniformValue indicates |
| 106 |
uniform type and new value (UniformValue.Name is not used). |
| 107 |
|
| 108 |
Do not pass here SFNode / MFNode fields (these should be added to |
| 109 |
UniformsTextures). |
| 110 |
|
| 111 |
@raises(EGLSLUniformInvalid When uniform variable name |
| 112 |
or type are invalid. |
| 113 |
|
| 114 |
Caller should always catch this and change into WritelnWarning. |
| 115 |
|
| 116 |
X3D spec "OpenGL shading language (GLSL) binding" says |
| 117 |
"If the name is not available as a uniform variable in the |
| 118 |
provided shader source, the values of the node shall be ignored" |
| 119 |
(although it says when talking about "Vertex attributes", |
| 120 |
seems they mixed attributes and uniforms meaning in spec?). |
| 121 |
|
| 122 |
So invalid uniform names should be always catched. |
| 123 |
We also catch type mismatches.) } |
| 124 |
procedure SetUniformFromField(const UniformName: String; |
| 125 |
const UniformValue: TX3DField; |
| 126 |
const AUniformMissing: TUniformMissing; |
| 127 |
const EnableDisable: boolean); |
| 128 |
|
| 129 |
procedure EventReceive(const Event: TX3DEvent; const Value: TX3DField; |
| 130 |
const Time: TX3DTime); |
| 131 |
|
| 132 |
{ Set uniform shader variable from VRML/X3D field (exposed or not). |
| 133 |
We also start observing an exposed field or eventIn, |
| 134 |
and will automatically update uniform value when we receive an event. } |
| 135 |
procedure BindNonTextureUniform( |
| 136 |
const FieldOrEvent: TX3DInterfaceDeclaration; |
| 137 |
const AUniformMissing: TUniformMissing; |
| 138 |
const EnableDisable: boolean); |
| 139 |
protected |
| 140 |
{ Nodes that have interface declarations with textures for this shader. } |
| 141 |
UniformsTextures: TX3DFieldList; |
| 142 |
public |
| 143 |
constructor Create; |
| 144 |
destructor Destroy; override; |
| 145 |
|
| 146 |
{ Set and observe uniform variables from given Node.InterfaceDeclarations. |
| 147 |
|
| 148 |
Non-texture fields are set immediately. |
| 149 |
Non-texture fields, and also events, become observed by this shader, |
| 150 |
and automatically updated when changed. |
| 151 |
|
| 152 |
Texture fields have to be updated by descendant (like TX3DGLSLProgram), |
| 153 |
using the UniformsTextures list. These methods add fields to this list. |
| 154 |
@groupBegin } |
| 155 |
procedure BindUniforms(const Node: TX3DNode; const EnableDisable: boolean); overload; |
| 156 |
procedure BindUniforms(const Nodes: TX3DNodeList; const EnableDisable: boolean); overload; |
| 157 |
{ @groupEnd } |
| 158 |
end; |
| 159 |
|
| 160 |
TShaderSource = class |
| 161 |
private |
| 162 |
FSource: array [TShaderType] of TCastleStringList; |
| 163 |
function GetSource(const AType: TShaderType): TCastleStringList; |
| 164 |
public |
| 165 |
constructor Create; |
| 166 |
destructor Destroy; override; |
| 167 |
property Source [const AType: TShaderType]: TCastleStringList read GetSource; default; |
| 168 |
|
| 169 |
{ Append AppendCode to our code. |
| 170 |
Has some special features: |
| 171 |
|
| 172 |
- Doesn't use AppendCode[DontAppendFirstPart][0] |
| 173 |
(we use this for now only with texture and light shaders, |
| 174 |
which treat AppendCode[stVertex / stFragment][0] specially). |
| 175 |
|
| 176 |
- Doesn't add anything to given type, if it's already empty. |
| 177 |
For our internal base shaders, vertex and fragment are never empty. |
| 178 |
When they are empty, this means that user assigned ComposedShader, |
| 179 |
but depends on fixed-function pipeline to do part of the job. } |
| 180 |
procedure Append(AppendCode: TShaderSource; const DontAppendFirstPart: TShaderType); |
| 181 |
end; |
| 182 |
|
| 183 |
TDynamicUniform = class abstract |
| 184 |
public |
| 185 |
Name: String; |
| 186 |
{ Declaration to put at the top of the shader code. |
| 187 |
Must end with newline. May be empty if you do it directly yourself. } |
| 188 |
Declaration: String; |
| 189 |
procedure SetUniform(AProgram: TX3DShaderProgram); virtual; abstract; |
| 190 |
end; |
| 191 |
|
| 192 |
TDynamicUniformSingle = class(TDynamicUniform) |
| 193 |
public |
| 194 |
Value: Single; |
| 195 |
procedure SetUniform(AProgram: TX3DShaderProgram); override; |
| 196 |
end; |
| 197 |
|
| 198 |
TDynamicUniformVec3 = class(TDynamicUniform) |
| 199 |
public |
| 200 |
Value: TVector3; |
| 201 |
procedure SetUniform(AProgram: TX3DShaderProgram); override; |
| 202 |
end; |
| 203 |
|
| 204 |
TDynamicUniformVec4 = class(TDynamicUniform) |
| 205 |
public |
| 206 |
Value: TVector4; |
| 207 |
procedure SetUniform(AProgram: TX3DShaderProgram); override; |
| 208 |
end; |
| 209 |
|
| 210 |
TDynamicUniformMat4 = class(TDynamicUniform) |
| 211 |
public |
| 212 |
Value: TMatrix4; |
| 213 |
procedure SetUniform(AProgram: TX3DShaderProgram); override; |
| 214 |
end; |
| 215 |
|
| 216 |
TDynamicUniformInteger = class(TDynamicUniform) |
| 217 |
public |
| 218 |
Value: Integer; |
| 219 |
procedure SetUniform(AProgram: TX3DShaderProgram); override; |
| 220 |
end; |
| 221 |
|
| 222 |
TDynamicUniformList = {$ifdef FPC}specialize{$endif} TObjectList<TDynamicUniform>; |
| 223 |
|
| 224 |
{ Possible ways to implement clip planes. } |
| 225 |
TClipPlaneAlgorithm = ( |
| 226 |
{$ifndef OpenGLES} |
| 227 |
{ Use glClipPlane, glEnable(GL_CLIP_PLANE*) calls. |
| 228 |
|
| 229 |
These are deprecated in newer OpenGL versions. |
| 230 |
|
| 231 |
The only thing GLSL needs to do is to set gl_ClipVertex |
| 232 |
to a vertex position in eye space. This way it will work both when |
| 233 |
shaders are used for rendering and when not. |
| 234 |
} |
| 235 |
cpFixedFunction, |
| 236 |
|
| 237 |
{ Vertex shader must calculate gl_ClipDistance[] for each plane. |
| 238 |
The clipping must also be enabled by glEnable(GL_CLIP_DISTANCE*). |
| 239 |
|
| 240 |
This works in new OpenGL >= 3.1 without deprecated stuff. |
| 241 |
|
| 242 |
This requires |
| 243 |
- OpenGL >= 3.0 (for "glEnable with GL_CLIP_DISTANCE*" in OpenGL API), |
| 244 |
- and again OpenGL >= 3.0 (for GLSL >= 1.30 that includes "gl_ClipDistance" |
| 245 |
built-in). |
| 246 |
- we actuallly bump it to 3.1, so that CastleGLShaders will add a #version, |
| 247 |
which is required for gl_ClipDistance access. |
| 248 |
|
| 249 |
See |
| 250 |
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/gl_ClipDistance.xhtml |
| 251 |
https://www.khronos.org/registry/OpenGL/specs/gl/GLSLangSpec.1.40.pdf , |
| 252 |
https://www.gamedev.net/forums/topic/625559-gl_clipvertex-alternative/ } |
| 253 |
cpClipDistance, |
| 254 |
{$endif} |
| 255 |
|
| 256 |
{ We pass the necessary information and do discard in fragment shader. |
| 257 |
|
| 258 |
This works everywhere where we have shaders, |
| 259 |
including in OpenGLES 2 |
| 260 |
(without EXT_clip_cull_distance.txt, which is only since OpenGLES 3). |
| 261 |
So we write to varying castle_ClipDistance[] (exactly like gl_ClipDistance) |
| 262 |
and then we discard in fragment shader fragments with distance < 0. |
| 263 |
} |
| 264 |
cpDiscard |
| 265 |
); |
| 266 |
|
| 267 |
{ Create appropriate shader and at the same time set OpenGL parameters |
| 268 |
for fixed-function rendering. Once everything is set up, |
| 269 |
you can create TX3DShaderProgram instance |
| 270 |
and initialize it by LinkProgram here, then enable it if you want. |
| 271 |
Or you can simply allow the fixed-function pipeline to work. |
| 272 |
|
| 273 |
This is used internally by TRenderer. It isn't supposed to be used |
| 274 |
directly by other code. } |
| 275 |
TShader = class |
| 276 |
private |
| 277 |
{ When adding new field, remember to clear it in Clear method. } |
| 278 |
{ List of effect nodes that determine uniforms of our program. } |
| 279 |
UniformsNodes: TX3DNodeList; |
| 280 |
TextureCoordGen, FragmentEnd: String; |
| 281 |
ClipPlanesCount: Cardinal; |
| 282 |
FShadowSampling: TShadowSampling; |
| 283 |
Source: TShaderSource; |
| 284 |
PlugIdentifiers: Cardinal; |
| 285 |
LightShaders: TLightShaders; |
| 286 |
TextureShaders: TTextureCoordinateShaderList; |
| 287 |
ShadowMapShaders: TShadowMapShaderList; |
| 288 |
FCodeHash: TShaderCodeHash; |
| 289 |
CodeHashFinalized: boolean; |
| 290 |
SelectedNode: TComposedShaderNode; |
| 291 |
WarnMissingPlugs: boolean; |
| 292 |
FShapeRequiresShaders: boolean; |
| 293 |
FBumpMappingShader: TBumpMappingShader; |
| 294 |
FSurfaceTextureShaders: TSurfaceTextureShaderList; |
| 295 |
FFogEnabled: boolean; |
| 296 |
FFogType: TFogType; |
| 297 |
FFogColor: TVector3; |
| 298 |
FFogVisibilityRange: Single; |
| 299 |
FFogCoordinateSource: TFogCoordinateSource; |
| 300 |
HasGeometryMain: boolean; |
| 301 |
TextureMatrix: TCardinalList; |
| 302 |
NeedsCameraInverseMatrix: Boolean; |
| 303 |
NeedsMirrorPlaneTexCoords: Boolean; |
| 304 |
NeedsNormalsForTexGen: Boolean; |
| 305 |
FPhongShading: boolean; |
| 306 |
FLightingModel: TLightingModel; |
| 307 |
FAlphaTest: Boolean; |
| 308 |
UsesShadowMaps: Boolean; |
| 309 |
|
| 310 |
{ We have to optimize the most often case of TShader usage, |
| 311 |
when the shader is not needed or is already prepared. |
| 312 |
|
| 313 |
- Enabling shader features should not do anything time-consuming, |
| 314 |
as it's done every frame. This means that we cannot construct |
| 315 |
complete shader source code on the fly, as this would mean |
| 316 |
slowdown at every frame for every shape. |
| 317 |
So enabling a feature merely records the demand for this feature. |
| 318 |
|
| 319 |
- It must also set ShapeRequiresShaders := true, if needed. |
| 320 |
- It must also update FCodeHash, if needed (if final shader code or |
| 321 |
uniform value changes). Can be done immediately, or inside |
| 322 |
CodeHashFinalize (the latter is more comfortable if it may change |
| 323 |
repeatedly and you don't want temporary values to be added to hash). |
| 324 |
- Actually adding this feature to shader source may be done at LinkProgram. |
| 325 |
} |
| 326 |
AppearanceEffects: TMFNode; |
| 327 |
GroupEffects: TX3DNodeList; |
| 328 |
Lighting: Boolean; |
| 329 |
ColorPerVertexType: TColorPerVertexType; |
| 330 |
ColorPerVertexMode: TColorMode; |
| 331 |
|
| 332 |
FShapeBoundingBoxInWorldKnown: Boolean; |
| 333 |
FShapeBoundingBoxInWorld: TBox3D; |
| 334 |
|
| 335 |
FClipPlaneAlgorithm: TClipPlaneAlgorithm; |
| 336 |
|
| 337 |
procedure EnableEffects(Effects: TMFNode; |
| 338 |
const Code: TShaderSource = nil; |
| 339 |
const ForwardDeclareInFinalShader: boolean = false); overload; |
| 340 |
procedure EnableEffects(Effects: TX3DNodeList; |
| 341 |
const Code: TShaderSource = nil; |
| 342 |
const ForwardDeclareInFinalShader: boolean = false); overload; |
| 343 |
|
| 344 |
{ Special form of Plug. It inserts the PlugValue source code directly |
| 345 |
at the position of given plug comment (no function call |
| 346 |
or anything is added). It also assumes that PlugName occurs only once |
| 347 |
in the Code, for speed. |
| 348 |
|
| 349 |
Returns if plug code was inserted (always @true when |
| 350 |
InsertAtBeginIfNotFound). } |
| 351 |
function PlugDirectly(Code: TCastleStringList; |
| 352 |
const CodeIndex: Cardinal; |
| 353 |
const PlugName, PlugValue: String; |
| 354 |
const InsertAtBeginIfNotFound: boolean): boolean; |
| 355 |
|
| 356 |
{ Make symbol DefineName to be defined for all GLSL parts of |
| 357 |
Source[ShaderType]. } |
| 358 |
procedure Define(const DefineName: String; const ShaderType: TShaderType; |
| 359 |
const PlugEarly: Boolean = false); |
| 360 |
|
| 361 |
function DeclareShadowFunctions: String; |
| 362 |
public |
| 363 |
{ Material parameters for current shape. |
| 364 |
Must be set before EnableLight, and be constant later. } |
| 365 |
Material: TMaterialInfo; |
| 366 |
|
| 367 |
{ Uniforms that will be set on this shader every frame (not just once after linking). } |
| 368 |
DynamicUniforms: TDynamicUniformList; |
| 369 |
|
| 370 |
{ We require a callback, instead of always requiring TBox3D result, because |
| 371 |
in many cases, we will not need to call it (so we don't need to recalculate |
| 372 |
TShape.LocalBoundingBox every frame for a changing shape). |
| 373 |
|
| 374 |
Should return bbox in scene coordinate system (not in world coordinate system). |
| 375 |
|
| 376 |
Use ShapeBoundingBoxInWorld to get the box easily. } |
| 377 |
ShapeBoundingBoxInSceneEvent: TBoundingBoxEvent; |
| 378 |
|
| 379 |
{ Camera * scene transformation (without the shape transformation). |
| 380 |
|
| 381 |
In case GLFeatures.EnableFixedFunction = true, these are also the contents |
| 382 |
of current OpenGL modelview matrix, |
| 383 |
at TRenderer.RenderShapeClipPlanes and earlier. |
| 384 |
At TRenderer.RenderShapeCreateMeshRenderer and later, |
| 385 |
the OpenGL modelview matrix contains also shape transformation, |
| 386 |
so it's different than SceneModelView. } |
| 387 |
SceneModelView: TMatrix4; |
| 388 |
|
| 389 |
{ Scene transformation (without the shape transformation). } |
| 390 |
SceneTransform: TMatrix4; |
| 391 |
|
| 392 |
{ Assign this if you used EnableTexGen with tgMirrorPlane |
| 393 |
to setup correct uniforms. } |
| 394 |
MirrorPlaneUniforms: TMirrorPlaneUniforms; |
| 395 |
|
| 396 |
RenderingCamera: TRenderingCamera; //< Set this after construction. |
| 397 |
|
| 398 |
MainTextureMapping: Integer; |
| 399 |
|
| 400 |
ColorSpaceLinear: Boolean; |
| 401 |
|
| 402 |
{ In case MultiTexture is used to render this, this is MultiTexture.color+alpha value. } |
| 403 |
MultiTextureColor: TCastleColor; |
| 404 |
|
| 405 |
constructor Create; |
| 406 |
destructor Destroy; override; |
| 407 |
|
| 408 |
{ Detect PLUG_xxx functions within PlugValue, |
| 409 |
look for matching @code(/* PLUG: xxx ...*/) declarations in both CompleteCode |
| 410 |
and the final shader source. |
| 411 |
|
| 412 |
For every plug declaration, |
| 413 |
@unorderedList( |
| 414 |
@item(insert the appropriate call to the plug function,) |
| 415 |
@item(and insert forward declaration of the plug function.) |
| 416 |
) |
| 417 |
|
| 418 |
Also, always insert the PlugValue (which should be variable and functions |
| 419 |
declarations) as another part of the CompleteCode. |
| 420 |
|
| 421 |
EffectPartType determines which type of CompleteCode is used. |
| 422 |
|
| 423 |
When CompleteCode = nil then we assume code of the final shader |
| 424 |
(private Source field). |
| 425 |
|
| 426 |
ForwardDeclareInFinalShader should be used only when Code is not nil. |
| 427 |
It means that forward declarations for Code[0] will be inserted |
| 428 |
into final shader code, not into Code[0]. This is useful if your |
| 429 |
Code[0] is special, and it will be pasted directly (not as plug) |
| 430 |
into final shader code. |
| 431 |
|
| 432 |
Inserts calls right before the magic @code(/* PLUG ...*/) comments, |
| 433 |
this way many Plug calls that defined the same PLUG_xxx function |
| 434 |
will be called in the same order. |
| 435 |
|
| 436 |
Doesn't do anything if in the final shader given type (EffectPartType) |
| 437 |
has empty code. This indicates that we used ComposedShader, and this type |
| 438 |
has no source code (so it should be done by fixed-function pipeline). |
| 439 |
Adding our own plug would be bad in this case, as we would create shader |
| 440 |
without main(). } |
| 441 |
procedure Plug(const EffectPartType: TShaderType; PlugValue: String; |
| 442 |
CompleteCode: TShaderSource = nil; |
| 443 |
const ForwardDeclareInFinalShader: boolean = false); |
| 444 |
|
| 445 |
{ Add fragment and vertex shader code, link. |
| 446 |
@raises EGLSLError In case of troubles with linking. } |
| 447 |
procedure LinkProgram(AProgram: TX3DShaderProgram; |
| 448 |
const ShapeNiceName: String); |
| 449 |
|
| 450 |
{ Add a fallback vertex + fragment shader code and link. |
| 451 |
Use this when normal LinkProgram failed, but you want to have |
| 452 |
*any* shader anyway. |
| 453 |
@raises EGLSLError In case of troubles with linking. } |
| 454 |
procedure LinkFallbackProgram(AProgram: TX3DShaderProgram); |
| 455 |
|
| 456 |
{ Calculate the hash of all the current TShader settings, |
| 457 |
that is the hash of GLSL program code initialized by this shader |
| 458 |
LinkProgram. You should use this only when the GLSL program source |
| 459 |
is completely initialized (all TShader settings are set). |
| 460 |
|
| 461 |
It can be used to decide when the shader GLSL program needs |
| 462 |
to be regenerated, shared etc. } |
| 463 |
function CodeHash: TShaderCodeHash; |
| 464 |
|
| 465 |
procedure EnableTexture(const TextureUnit: Cardinal; |
| 466 |
const TextureType: TTextureType; const Node: TAbstractSingleTextureNode; |
| 467 |
const Env: TTextureEnv); |
| 468 |
procedure EnableTexGen(const TextureUnit: Cardinal; |
| 469 |
const Generation: TTexGenerationComponent; const Component: TTexComponent; |
| 470 |
const Plane: TVector4); overload; |
| 471 |
procedure EnableTexGen(const TextureUnit: Cardinal; |
| 472 |
const Generation: TTexGenerationComplete; |
| 473 |
const TransformToWorldSpace: boolean = false); overload; |
| 474 |
{ Disable fixed-function texgen of given texture unit. |
| 475 |
Guarantees to also set active texture unit to TexUnit (if multi-texturing |
| 476 |
available at all). } |
| 477 |
procedure DisableTexGen(const TextureUnit: Cardinal); |
| 478 |
procedure EnableTextureTransform(const TextureUnit: Cardinal; |
| 479 |
const Matrix: TMatrix4); |
| 480 |
{ Enable clip plane. |
| 481 |
|
| 482 |
The Plane equation must be given in "scene coordinates". |
| 483 |
IOW, with shape transformation matrix (from X3D Transform nodes) applied, |
| 484 |
but scene matrix (TCastleScene transformation) not applied, |
| 485 |
and "camera matrix" not applied. |
| 486 |
|
| 487 |
The ClipPlaneIndex must always be one more than previous one |
| 488 |
on this TShape instance, since it's creation or Initialize call. |
| 489 |
So you can only call EnableClipPlane with successive integers, from 0. } |
| 490 |
procedure EnableClipPlane(const ClipPlaneIndex: Cardinal; |
| 491 |
const Plane: TVector4); |
| 492 |
procedure DisableClipPlane(const ClipPlaneIndex: Cardinal); |
| 493 |
procedure EnableAlphaTest(const AlphaCutoff: Single); |
| 494 |
procedure EnableBumpMapping(const BumpMapping: TBumpMapping; |
| 495 |
const NormalMapTextureUnit, NormalMapTextureCoordinatesId: Cardinal; |
| 496 |
const NormalMapScale: Single; |
| 497 |
const HeightMapInAlpha: boolean; const HeightMapScale: Single); |
| 498 |
{ Enable surface texture. |
| 499 |
"Surface texture" is a term for a texture that |
| 500 |
doesn't contribute main color (so it is not Material.diffuseTexture, |
| 501 |
PhysicalMaterial.baseTexture, UnlitMaterial.emissiveTexture), |
| 502 |
and is specified in a special material slot (in CommonSurfaceShader |
| 503 |
or in new Material / PhysicalMaterial / UnlitMaterial xxxTexture fields |
| 504 |
in X3D 4.0). } |
| 505 |
procedure EnableSurfaceTexture(const SurfaceTexture: TSurfaceTexture; |
| 506 |
const TextureUnit, TextureCoordinatesId: Cardinal; |
| 507 |
const UniformTextureName, PlugCode: String); |
| 508 |
{ Enable light source. Remember to set MaterialXxx before calling this. } |
| 509 |
procedure EnableLight(const Number: Cardinal; Light: PLightInstance); |
| 510 |
procedure EnableFog(const FogType: TFogType; |
| 511 |
const FogCoordinateSource: TFogCoordinateSource; |
| 512 |
const FogColor: TVector3; const FogVisibilityRange: Single); |
| 513 |
{ Modify some fog parameters, relevant only if fog already enabled. |
| 514 |
Used by FogCoordinate, that changes some fog settings, |
| 515 |
but does not change fog color. } |
| 516 |
procedure ModifyFog(const FogType: TFogType; |
| 517 |
const FogCoordinateSource: TFogCoordinateSource; |
| 518 |
const FogVisibilityRange: Single); |
| 519 |
function EnableCustomShaderCode(const Shaders: TMFNode; |
| 520 |
out Node: TComposedShaderNode): boolean; |
| 521 |
procedure EnableAppearanceEffects(Effects: TMFNode); |
| 522 |
procedure EnableGroupEffects(Effects: TX3DNodeList); |
| 523 |
procedure EnableLighting; |
| 524 |
procedure EnableColorPerVertex(const AMode: TColorMode; const AColorType: TColorPerVertexType); |
| 525 |
procedure EnableShadowMap(const TextureUnit: Cardinal; |
| 526 |
const ShadowMap: TGeneratedShadowMapNode); |
| 527 |
|
| 528 |
property ShadowSampling: TShadowSampling |
| 529 |
read FShadowSampling write FShadowSampling; |
| 530 |
property ShapeRequiresShaders: boolean read FShapeRequiresShaders |
| 531 |
write FShapeRequiresShaders; |
| 532 |
property LightingModel: TLightingModel |
| 533 |
read FLightingModel write FLightingModel; |
| 534 |
|
| 535 |
{ Clear instance, bringing it to the state after creation. |
| 536 |
You must call Intialize afterwards. } |
| 537 |
procedure Clear; |
| 538 |
|
| 539 |
{ Initialize the instance and PhongShading. |
| 540 |
For now, PhongShading must be set early (and cannot be changed later), |
| 541 |
as it determines the initial shader templates that may be used before linking. } |
| 542 |
procedure Initialize(const APhongShading: boolean); |
| 543 |
|
| 544 |
property PhongShading: boolean read FPhongShading; |
| 545 |
|
| 546 |
{ Set uniforms that should be set each time before using shader |
| 547 |
(because changes to their values may happen at any time, |
| 548 |
and they do not cause rebuilding the shader). } |
| 549 |
procedure SetDynamicUniforms(AProgram: TX3DShaderProgram); |
| 550 |
|
| 551 |
{ Add a screen effect GLSL code. } |
| 552 |
procedure AddScreenEffectCode(const Depth: boolean); |
| 553 |
|
| 554 |
{ Shader needs normals, for lighting calculation or tex coord generation. } |
| 555 |
function NeedsNormals: Boolean; |
| 556 |
|
| 557 |
{ Current shape bbox, in world coordinates. } |
| 558 |
function ShapeBoundingBoxInWorld: TBox3D; |
| 559 |
|
| 560 |
{ Is alpha testing enabled by EnableAlphaTest. } |
| 561 |
property AlphaTest: Boolean read FAlphaTest; |
| 562 |
end; |
| 563 |
|
| 564 |
{ Derive UniformMissing behavior for fields within given node. |
| 565 |
Accepts Node = @nil too. } |
| 566 |
function UniformMissingFromNode(const Node: TX3DNode): TUniformMissing; |
| 567 |
|
| 568 |
{ Find PLUG_xxx function inside PlugValue. |
| 569 |
Returns xxx (the part after PLUG_), |
| 570 |
and DeclaredParameters (of this plug function). Or '' if not found. |
| 571 |
|
| 572 |
This is public in this unit for the sake of testing. } |
| 573 |
function FindPlugName(const PlugValue: String; |
| 574 |
out DeclaredParameters: String): String; |
| 575 |
|
| 576 |
{$undef read_interface} |
| 577 |
|
| 578 |
implementation |
| 579 |
|
| 580 |
uses SysUtils, StrUtils, |
| 581 |
{$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif} |
| 582 |
CastleGLUtils, CastleLog, CastleGLVersion, CastleInternalScreenEffects, |
| 583 |
CastleScreenEffects, CastleInternalX3DLexer, CastleInternalGLUtils; |
| 584 |
|
| 585 |
{$define read_implementation} |
| 586 |
{$I castlerendererinternalshader_hash.inc} |
| 587 |
{$I castlerendererinternalshader_light.inc} |
| 588 |
{$I castlerendererinternalshader_texture.inc} |
| 589 |
{$I castlerendererinternalshader_shadowmap.inc} |
| 590 |
{$I castlerendererinternalshader_mirrorplane.inc} |
| 591 |
{$I castlerendererinternalshader_surfacetexture.inc} |
| 592 |
{$I castlerendererinternalshader_bumpmapping.inc} |
| 593 |
|
| 594 |
{$ifndef OpenGLES} |
| 595 |
var |
| 596 |
{ By default (when this is false), |
| 597 |
desktop OpenGL either use gl_ClipVertex or gl_ClipDistance. |
| 598 |
Set this to true to implement clip planes without any built-in GLSL |
| 599 |
variables. This makes no practical sense on desktop OpenGL (is slower), |
| 600 |
but allows to test this GLSL code on desktop OpenGL. |
| 601 |
|
| 602 |
This is a global variable only to silence compiler warnings about |
| 603 |
unreachable code, in practice we use this as a constant. } |
| 604 |
ForceOpenGLESClipPlanes: Boolean = false; |
| 605 |
{$endif} |
| 606 |
|
| 607 |
function UniformMissingFromNode(const Node: TX3DNode): TUniformMissing; |
| 608 |
begin |
| 609 |
if Node is TEffectNode then |
| 610 |
Result := TEffectNode(Node).UniformMissing |
| 611 |
else |
| 612 |
if Node is TComposedShaderNode then |
| 613 |
Result := TComposedShaderNode(Node).UniformMissing |
| 614 |
else |
| 615 |
Result := umWarning; |
| 616 |
end; |
| 617 |
|
| 618 |
{ String helpers ------------------------------------------------------------- } |
| 619 |
|
| 620 |
{ MoveTo do not warn about incorrect PLUG_ declarations, only return @false |
| 621 |
on them. That's because FindPlugName should just ignore them. |
| 622 |
But we log them --- maybe they will be useful |
| 623 |
in case there's some problem with FindPlugName. |
| 624 |
|
| 625 |
Testcase: opening |
| 626 |
castle-model-viewer-mobile/data/demo/teapot (fresnel and toon shader).x3dv |
| 627 |
in castle-model-viewer-mobile. |
| 628 |
} |
| 629 |
|
| 630 |
function MoveToOpeningParen(const S: String; var P: Integer): boolean; |
| 631 |
begin |
| 632 |
Result := true; |
| 633 |
repeat |
| 634 |
Inc(P); |
| 635 |
|
| 636 |
if P > Length(S) then |
| 637 |
begin |
| 638 |
WritelnLog('VRML/X3D', 'PLUG declaration unexpected end (no opening parenthesis "(") '); |
| 639 |
Exit(false); |
| 640 |
end; |
| 641 |
|
| 642 |
if (S[P] <> '(') and |
| 643 |
not CharInSet(S[P], WhiteSpaces) then |
| 644 |
begin |
| 645 |
WritelnLog('VRML/X3D', Format('PLUG declaration unexpected character "%s" (expected opening parenthesis "(") in "%s"', |
| 646 |
[S[P], S])); |
| 647 |
Exit(false); |
| 648 |
end; |
| 649 |
until S[P] = '('; |
| 650 |
end; |
| 651 |
|
| 652 |
function MoveToMatchingParen(const S: String; var P: Integer): boolean; |
| 653 |
var |
| 654 |
ParenLevel: Cardinal; |
| 655 |
begin |
| 656 |
Result := true; |
| 657 |
ParenLevel := 1; |
| 658 |
|
| 659 |
repeat |
| 660 |
Inc(P); |
| 661 |
if P > Length(S) then |
| 662 |
begin |
| 663 |
WritelnLog('VRML/X3D', 'PLUG declaration unexpected end (no closing parenthesis ")")'); |
| 664 |
Exit(false); |
| 665 |
end; |
| 666 |
|
| 667 |
if S[P] = '(' then |
| 668 |
Inc(ParenLevel) else |
| 669 |
if S[P] = ')' then |
| 670 |
Dec(ParenLevel); |
| 671 |
until ParenLevel = 0; |
| 672 |
end; |
| 673 |
|
| 674 |
function FindPlugName(const PlugValue: String; |
| 675 |
out DeclaredParameters: String): String; |
| 676 |
const |
| 677 |
PlugPrefix = 'PLUG_'; |
| 678 |
IdentifierChars = ['0'..'9', 'a'..'z', 'A'..'Z', '_']; |
| 679 |
var |
| 680 |
P, PBegin, DPBegin, DPEnd, SearchStart: Integer; |
| 681 |
begin |
| 682 |
SearchStart := 1; |
| 683 |
repeat |
| 684 |
P := PosEx(PlugPrefix, PlugValue, SearchStart); |
| 685 |
if P = 0 then Exit(''); |
| 686 |
|
| 687 |
{ if code below will decide that it's an incorrect PLUG_ definition, |
| 688 |
it will do Continue, and we will search again from the next position. } |
| 689 |
SearchStart := P + Length(PlugPrefix); |
| 690 |
|
| 691 |
{ There must be whitespace before PLUG_ } |
| 692 |
if (P > 1) and (not CharInSet(PlugValue[P - 1], WhiteSpaces)) then Continue; |
| 693 |
P := P + Length(PlugPrefix); |
| 694 |
PBegin := P; |
| 695 |
{ There must be at least one identifier char after PLUG_ } |
| 696 |
if (P > Length(PlugValue)) or |
| 697 |
(not CharInSet(PlugValue[P], IdentifierChars)) then Continue; |
| 698 |
repeat |
| 699 |
Inc(P); |
| 700 |
until (P > Length(PlugValue)) or (not CharInSet(PlugValue[P], IdentifierChars)); |
| 701 |
{ Skip whitespace after PLUG_xxx and before "(". } |
| 702 |
while (P <= Length(PlugValue)) and CharInSet(PlugValue[P], WhiteSpaces) do |
| 703 |
Inc(P); |
| 704 |
{ There must be "(" now } |
| 705 |
if (P > Length(PlugValue)) or (PlugValue[P] <> '(') then |
| 706 |
Continue; |
| 707 |
|
| 708 |
// Trim needed, because P may include some trailing whitespace |
| 709 |
Result := Trim(CopyPos(PlugValue, PBegin, P - 1)); |
| 710 |
|
| 711 |
DPBegin := P - 1; |
| 712 |
if not MoveToOpeningParen(PlugValue, DPBegin) then Continue; |
| 713 |
DPEnd := DPBegin; |
| 714 |
if not MoveToMatchingParen(PlugValue, DPEnd) then Continue; |
| 715 |
|
| 716 |
DeclaredParameters := CopyPos(PlugValue, DPBegin, DPEnd); |
| 717 |
{ if you managed to get here, then we have correct Result and DeclaredParameters } |
| 718 |
Exit; |
| 719 |
until false; |
| 720 |
end; |
| 721 |
|
| 722 |
{ In OpenGL, each part (separate compilation) has to declare it's variables |
| 723 |
(uniforms, attributes etc.). It also has to declare the used procedures |
| 724 |
from other compilation units. |
| 725 |
|
| 726 |
In OpenGLES, all parts are glued into one, and their declarations cannot |
| 727 |
be repeated (or there will be compilation error). |
| 728 |
The used procedures may be declated (a forward declaration), |
| 729 |
but the forward declarations cannot be repeated (although it may depend |
| 730 |
on mobile GPU). |
| 731 |
|
| 732 |
This function wraps a declaration in suitable #ifdef |
| 733 |
such that it will only be declared once. |
| 734 |
The given Name is anything unique -- usually the variable or procedure name. |
| 735 |
|
| 736 |
Declaration should not (but may) end with newline. |
| 737 |
The result always ends with newline. } |
| 738 |
function DeclareOnce(const Name: String; const Declaration: String): String; |
| 739 |
begin |
| 740 |
{$ifndef OpenGLES} |
| 741 |
Result := Declaration + NL; |
| 742 |
{$else} |
| 743 |
Result := |
| 744 |
'#ifndef ' + Name + '_defined' + NL + |
| 745 |
'#define ' + Name + '_defined' + NL + |
| 746 |
Declaration + NL + |
| 747 |
'#endif' + NL; |
| 748 |
{$endif} |
| 749 |
end; |
| 750 |
|
| 751 |
{ TShaderSource -------------------------------------------------------------- } |
| 752 |
|
| 753 |
constructor TShaderSource.Create; |
| 754 |
var |
| 755 |
SourceType: TShaderType; |
| 756 |
begin |
| 757 |
inherited; |
| 758 |
for SourceType := Low(SourceType) to High(SourceType) do |
| 759 |
FSource[SourceType] := TCastleStringList.Create; |
| 760 |
end; |
| 761 |
|
| 762 |
destructor TShaderSource.Destroy; |
| 763 |
var |
| 764 |
SourceType: TShaderType; |
| 765 |
begin |
| 766 |
for SourceType := Low(SourceType) to High(SourceType) do |
| 767 |
FreeAndNil(FSource[SourceType]); |
| 768 |
inherited; |
| 769 |
end; |
| 770 |
|
| 771 |
function TShaderSource.GetSource(const AType: TShaderType): TCastleStringList; |
| 772 |
begin |
| 773 |
Result := FSource[AType]; |
| 774 |
end; |
| 775 |
|
| 776 |
procedure TShaderSource.Append(AppendCode: TShaderSource; const DontAppendFirstPart: TShaderType); |
| 777 |
var |
| 778 |
T: TShaderType; |
| 779 |
I: Integer; |
| 780 |
begin |
| 781 |
for T := Low(T) to High(T) do |
| 782 |
if Source[T].Count <> 0 then |
| 783 |
for I := Iff(T = DontAppendFirstPart, 1, 0) to AppendCode[T].Count - 1 do |
| 784 |
Source[T].Add(AppendCode[T][I]); |
| 785 |
end; |
| 786 |
|
| 787 |
{ TX3DShaderProgramBase ------------------------------------------------------ } |
| 788 |
|
| 789 |
procedure TX3DShaderProgramBase.Link; |
| 790 |
begin |
| 791 |
inherited; |
| 792 |
|
| 793 |
UniformCastle_ModelViewMatrix := Uniform('castle_ModelViewMatrix' , umIgnore); |
| 794 |
UniformCastle_ProjectionMatrix := Uniform('castle_ProjectionMatrix' , umIgnore); |
| 795 |
UniformCastle_NormalMatrix := Uniform('castle_NormalMatrix' , umIgnore); |
| 796 |
UniformCastle_MaterialDiffuseAlpha := Uniform('castle_MaterialDiffuseAlpha' , umIgnore); |
| 797 |
UniformCastle_MaterialBaseAlpha := Uniform('castle_MaterialBaseAlpha' , umIgnore); |
| 798 |
UniformCastle_MaterialEmissiveAlpha := Uniform('castle_MaterialEmissiveAlpha', umIgnore); |
| 799 |
UniformCastle_MaterialShininess := Uniform('castle_MaterialShininess' , umIgnore); |
| 800 |
UniformCastle_MaterialEmissive := Uniform('castle_MaterialEmissive' , umIgnore); |
| 801 |
UniformCastle_MaterialAmbient := Uniform('castle_MaterialAmbient' , umIgnore); |
| 802 |
UniformCastle_MaterialSpecular := Uniform('castle_MaterialSpecular' , umIgnore); |
| 803 |
UniformCastle_MaterialMetallic := Uniform('castle_MaterialMetallic' , umIgnore); |
| 804 |
UniformCastle_MaterialRoughness := Uniform('castle_MaterialRoughness' , umIgnore); |
| 805 |
UniformCastle_GlobalAmbient := Uniform('castle_GlobalAmbient' , umIgnore); |
| 806 |
UniformCastle_UnlitColor := Uniform('castle_UnlitColor' , umIgnore); |
| 807 |
|
| 808 |
AttributeCastle_Vertex := AttributeOptional('castle_Vertex'); |
| 809 |
AttributeCastle_Normal := AttributeOptional('castle_Normal'); |
| 810 |
AttributeCastle_Tangent := AttributeOptional('castle_Tangent'); |
| 811 |
AttributeCastle_ColorPerVertex := AttributeOptional('castle_ColorPerVertex'); |
| 812 |
AttributeCastle_FogCoord := AttributeOptional('castle_FogCoord'); |
| 813 |
end; |
| 814 |
|
| 815 |
{ TX3DShaderProgram ------------------------------------------------------- } |
| 816 |
|
| 817 |
constructor TX3DShaderProgram.Create; |
| 818 |
begin |
| 819 |
inherited; |
| 820 |
EventsObserved := TX3DEventList.Create(false); |
| 821 |
UniformsTextures := TX3DFieldList.Create(false); |
| 822 |
FLightUniformsList := TLightUniformsList.Create(true); |
| 823 |
end; |
| 824 |
|
| 825 |
destructor TX3DShaderProgram.Destroy; |
| 826 |
var |
| 827 |
I: Integer; |
| 828 |
begin |
| 829 |
if EventsObserved <> nil then |
| 830 |
begin |
| 831 |
for I := 0 to EventsObserved.Count - 1 do |
| 832 |
EventsObserved[I].RemoveNotification({$ifdef FPC}@{$endif}EventReceive); |
| 833 |
FreeAndNil(EventsObserved); |
| 834 |
end; |
| 835 |
FreeAndNil(UniformsTextures); |
| 836 |
FreeAndNil(FLightUniformsList); |
| 837 |
inherited; |
| 838 |
end; |
| 839 |
|
| 840 |
procedure TX3DShaderProgram.BindNonTextureUniform( |
| 841 |
const FieldOrEvent: TX3DInterfaceDeclaration; |
| 842 |
const AUniformMissing: TUniformMissing; |
| 843 |
const EnableDisable: boolean); |
| 844 |
var |
| 845 |
UniformField: TX3DField; |
| 846 |
UniformEvent, ObservedEvent: TX3DEvent; |
| 847 |
begin |
| 848 |
UniformField := FieldOrEvent.Field; |
| 849 |
UniformEvent := FieldOrEvent.Event; |
| 850 |
|
| 851 |
{ Set initial value for this GLSL uniform variable, |
| 852 |
from X3D field or exposedField } |
| 853 |
|
| 854 |
if UniformField <> nil then |
| 855 |
{ Ok, we have a field with a value (interface declarations with |
| 856 |
fields inside ComposedShader / Effect always have a value). |
| 857 |
So set GLSL uniform variable from this field. } |
| 858 |
SetUniformFromField(UniformField.X3DName, UniformField, AUniformMissing, EnableDisable); |
| 859 |
|
| 860 |
{ Allow future changing of this GLSL uniform variable, |
| 861 |
from VRML eventIn or exposedField } |
| 862 |
|
| 863 |
{ calculate ObservedEvent } |
| 864 |
ObservedEvent := nil; |
| 865 |
if (UniformField <> nil) and UniformField.Exposed then |
| 866 |
ObservedEvent := UniformField.ExposedEvents[false] else |
| 867 |
if (UniformEvent <> nil) and UniformEvent.InEvent then |
| 868 |
ObservedEvent := UniformEvent; |
| 869 |
|
| 870 |
if ObservedEvent <> nil then |
| 871 |
begin |
| 872 |
ObservedEvent.AddNotification({$ifdef FPC}@{$endif}EventReceive); |
| 873 |
EventsObserved.Add(ObservedEvent); |
| 874 |
end; |
| 875 |
end; |
| 876 |
|
| 877 |
procedure TX3DShaderProgram.SetUniformFromField( |
| 878 |
const UniformName: String; const UniformValue: TX3DField; |
| 879 |
const AUniformMissing: TUniformMissing; |
| 880 |
const EnableDisable: Boolean); |
| 881 |
var |
| 882 |
TempF: TSingleList; |
| 883 |
TempVec2f: TVector2List; |
| 884 |
TempVec3f: TVector3List; |
| 885 |
TempVec4f: TVector4List; |
| 886 |
TempMat3f: TMatrix3List; |
| 887 |
TempMat4f: TMatrix4List; |
| 888 |
begin |
| 889 |
{ program must be active to set uniform values. } |
| 890 |
if EnableDisable then |
| 891 |
Enable; |
| 892 |
|
| 893 |
if UniformValue is TSFBool then |
| 894 |
SetUniform(UniformName, TSFBool(UniformValue).Value, AUniformMissing) else |
| 895 |
if UniformValue is TSFLong then |
| 896 |
{ Handling of SFLong also takes care of SFInt32. } |
| 897 |
SetUniform(UniformName, TSFLong(UniformValue).Value, AUniformMissing) else |
| 898 |
if UniformValue is TSFVec2f then |
| 899 |
SetUniform(UniformName, TSFVec2f(UniformValue).Value, AUniformMissing) else |
| 900 |
|
| 901 |
(* |
| 902 |
{ Old approach: Check TSFColor first, otherwise TSFVec3f would also catch and handle |
| 903 |
TSFColor. And we don't want this: for GLSL, color is passed |
| 904 |
as vec4 (so says the spec, I guess that the reason is that for GLSL most |
| 905 |
input/output colors are vec4). |
| 906 |
|
| 907 |
New approach: That's just nonsense in X3D spec. |
| 908 |
We now pass SFColor as vec3, it can fallback TSFVec3f clause. } |
| 909 |
|
| 910 |
// if UniformValue is TSFColor then |
| 911 |
// SetUniform(UniformName, Vector4(TSFColor(UniformValue).Value, 1.0), AUniformMissing) else |
| 912 |
*) |
| 913 |
|
| 914 |
if UniformValue is TSFVec3f then |
| 915 |
SetUniform(UniformName, TSFVec3f(UniformValue).Value, AUniformMissing) else |
| 916 |
if UniformValue is TSFVec4f then |
| 917 |
SetUniform(UniformName, TSFVec4f(UniformValue).Value, AUniformMissing) else |
| 918 |
if UniformValue is TSFRotation then |
| 919 |
SetUniform(UniformName, TSFRotation(UniformValue).Value, AUniformMissing) else |
| 920 |
if UniformValue is TSFMatrix3f then |
| 921 |
SetUniform(UniformName, TSFMatrix3f(UniformValue).Value, AUniformMissing) else |
| 922 |
if UniformValue is TSFMatrix4f then |
| 923 |
SetUniform(UniformName, TSFMatrix4f(UniformValue).Value, AUniformMissing) else |
| 924 |
if UniformValue is TSFFloat then |
| 925 |
SetUniform(UniformName, TSFFloat(UniformValue).Value, AUniformMissing) else |
| 926 |
if UniformValue is TSFDouble then |
| 927 |
{ SFDouble also takes care of SFTime } |
| 928 |
SetUniform(UniformName, TSFDouble(UniformValue).Value, AUniformMissing) else |
| 929 |
|
| 930 |
{ Double-precision vector and matrix types. |
| 931 |
|
| 932 |
Note that X3D spec specifies only mapping for SF/MFVec3d, 4d |
| 933 |
(not specifying any mapping for SF/MFVec2d, and all matrix types). |
| 934 |
And it specifies that they map to types float3, float4 --- |
| 935 |
which are not valid types in GLSL? |
| 936 |
|
| 937 |
So I simply ignore non-sensible specification, and take |
| 938 |
the reasonable approach: support all double-precision vectors and matrices, |
| 939 |
just like single-precision. } |
| 940 |
if UniformValue is TSFVec2d then |
| 941 |
SetUniform(UniformName, Vector2(TSFVec2d(UniformValue).Value), AUniformMissing) else |
| 942 |
if UniformValue is TSFVec3d then |
| 943 |
SetUniform(UniformName, Vector3(TSFVec3d(UniformValue).Value), AUniformMissing) else |
| 944 |
if UniformValue is TSFVec4d then |
| 945 |
SetUniform(UniformName, Vector4(TSFVec4d(UniformValue).Value), AUniformMissing) else |
| 946 |
if UniformValue is TSFMatrix3d then |
| 947 |
SetUniform(UniformName, Matrix3(TSFMatrix3d(UniformValue).Value), AUniformMissing) else |
| 948 |
if UniformValue is TSFMatrix4d then |
| 949 |
SetUniform(UniformName, Matrix4(TSFMatrix4d(UniformValue).Value), AUniformMissing) else |
| 950 |
|
| 951 |
{ Now repeat this for array types } |
| 952 |
if UniformValue is TMFBool then |
| 953 |
SetUniform(UniformName, TMFBool(UniformValue).Items, AUniformMissing) else |
| 954 |
if UniformValue is TMFLong then |
| 955 |
SetUniform(UniformName, TMFLong(UniformValue).Items, AUniformMissing) else |
| 956 |
if UniformValue is TMFVec2f then |
| 957 |
SetUniform(UniformName, TMFVec2f(UniformValue).Items, AUniformMissing) else |
| 958 |
(* Old approach: follow X3D spec, and map MFColor to vec4[]. |
| 959 |
New approach: ignore nonsense X3D spec, and map MFColor to vec3[]. |
| 960 |
Just allow TMFColor to fallback to TMFVec3f. |
| 961 |
if UniformValue is TMFColor then |
| 962 |
begin |
| 963 |
TempVec4f := TMFColor(UniformValue).Items.ToVector4(1.0); |
| 964 |
try |
| 965 |
SetUniform(UniformName, TempVec4f, AUniformMissing); |
| 966 |
finally FreeAndNil(TempVec4f) end; |
| 967 |
end else |
| 968 |
*) |
| 969 |
if UniformValue is TMFVec3f then |
| 970 |
SetUniform(UniformName, TMFVec3f(UniformValue).Items, AUniformMissing) else |
| 971 |
if UniformValue is TMFVec4f then |
| 972 |
SetUniform(UniformName, TMFVec4f(UniformValue).Items, AUniformMissing) else |
| 973 |
if UniformValue is TMFRotation then |
| 974 |
SetUniform(UniformName, TMFRotation(UniformValue).Items, AUniformMissing) else |
| 975 |
if UniformValue is TMFMatrix3f then |
| 976 |
SetUniform(UniformName, TMFMatrix3f(UniformValue).Items, AUniformMissing) else |
| 977 |
if UniformValue is TMFMatrix4f then |
| 978 |
SetUniform(UniformName, TMFMatrix4f(UniformValue).Items, AUniformMissing) else |
| 979 |
if UniformValue is TMFFloat then |
| 980 |
SetUniform(UniformName, TMFFloat(UniformValue).Items, AUniformMissing) else |
| 981 |
if UniformValue is TMFDouble then |
| 982 |
begin |
| 983 |
TempF := TMFDouble(UniformValue).Items.ToSingle; |
| 984 |
try |
| 985 |
SetUniform(UniformName, TempF, AUniformMissing); |
| 986 |
finally FreeAndNil(TempF) end; |
| 987 |
end else |
| 988 |
if UniformValue is TMFVec2d then |
| 989 |
begin |
| 990 |
TempVec2f := TMFVec2d(UniformValue).Items.ToVector2; |
| 991 |
try |
| 992 |
SetUniform(UniformName, TempVec2f, AUniformMissing); |
| 993 |
finally FreeAndNil(TempVec2f) end; |
| 994 |
end else |
| 995 |
if UniformValue is TMFVec3d then |
| 996 |
begin |
| 997 |
TempVec3f := TMFVec3d(UniformValue).Items.ToVector3; |
| 998 |
try |
| 999 |
SetUniform(UniformName, TempVec3f, AUniformMissing); |
| 1000 |
finally FreeAndNil(TempVec3f) end; |
| 1001 |
end else |
| 1002 |
if UniformValue is TMFVec4d then |
| 1003 |
begin |
| 1004 |
TempVec4f := TMFVec4d(UniformValue).Items.ToVector4; |
| 1005 |
try |
| 1006 |
SetUniform(UniformName, TempVec4f, AUniformMissing); |
| 1007 |
finally FreeAndNil(TempVec4f) end; |
| 1008 |
end else |
| 1009 |
if UniformValue is TMFMatrix3d then |
| 1010 |
begin |
| 1011 |
TempMat3f := TMFMatrix3d(UniformValue).Items.ToMatrix3; |
| 1012 |
try |
| 1013 |
SetUniform(UniformName, TempMat3f, AUniformMissing); |
| 1014 |
finally FreeAndNil(TempMat3f) end; |
| 1015 |
end else |
| 1016 |
if UniformValue is TMFMatrix4d then |
| 1017 |
begin |
| 1018 |
TempMat4f := TMFMatrix4d(UniformValue).Items.ToMatrix4; |
| 1019 |
try |
| 1020 |
SetUniform(UniformName, TempMat4f, AUniformMissing); |
| 1021 |
finally FreeAndNil(TempMat4f) end; |
| 1022 |
end else |
| 1023 |
|
| 1024 |
(* |
| 1025 |
if (UniformValue is TSFNode) or |
| 1026 |
(UniformValue is TMFNode) then |
| 1027 |
begin |
| 1028 |
{ Nothing to do, these will be set by TGLSLRenderer.Enable. |
| 1029 |
Right now, these are never passed here. } |
| 1030 |
end else |
| 1031 |
*) |
| 1032 |
|
| 1033 |
{ TODO: other field types, full list is in X3D spec in |
| 1034 |
"OpenGL shading language (GLSL) binding". |
| 1035 |
Remaining: |
| 1036 |
SF/MFImage } |
| 1037 |
WritelnWarning('VRML/X3D', 'Setting uniform GLSL variable from X3D field type "' + UniformValue.X3DType + '" not supported'); |
| 1038 |
|
| 1039 |
if EnableDisable then |
| 1040 |
{ TODO: this should restore previously bound program } |
| 1041 |
Disable; |
| 1042 |
end; |
| 1043 |
|
| 1044 |
procedure TX3DShaderProgram.EventReceive( |
| 1045 |
const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime); |
| 1046 |
var |
| 1047 |
UniformName: String; |
| 1048 |
Scene: TX3DEventsEngine; |
| 1049 |
begin |
| 1050 |
if Event.ParentExposedField = nil then |
| 1051 |
UniformName := Event.X3DName |
| 1052 |
else |
| 1053 |
UniformName := Event.ParentExposedField.X3DName; |
| 1054 |
|
| 1055 |
SetUniformFromField(UniformName, Value, UniformMissingFromNode(Event.ParentNode as TX3DNode), true); |
| 1056 |
|
| 1057 |
{ Although ExposedEvents implementation already sends notification |
| 1058 |
about changes to Scene, we can also get here |
| 1059 |
by eventIn invocation (which doesn't trigger |
| 1060 |
Scene.InternalChangedField, since it doesn't change a field...). |
| 1061 |
So we should explicitly do VisibleChangeHere here, to make sure |
| 1062 |
it gets called when uniform changed. } |
| 1063 |
if Event.ParentNode <> nil then |
| 1064 |
begin |
| 1065 |
Scene := (Event.ParentNode as TX3DNode).Scene; |
| 1066 |
if Scene <> nil then |
| 1067 |
Scene.VisibleChangeHere([vcVisibleGeometry, vcVisibleNonGeometry]); |
| 1068 |
end; |
| 1069 |
end; |
| 1070 |
|
| 1071 |
procedure TX3DShaderProgram.BindUniforms(const Node: TX3DNode; |
| 1072 |
const EnableDisable: boolean); |
| 1073 |
var |
| 1074 |
I: Integer; |
| 1075 |
IDecl: TX3DInterfaceDeclaration; |
| 1076 |
begin |
| 1077 |
Assert(Node.HasInterfaceDeclarations <> []); |
| 1078 |
Assert(Node.InterfaceDeclarations <> nil); |
| 1079 |
for I := 0 to Node.InterfaceDeclarations.Count - 1 do |
| 1080 |
begin |
| 1081 |
IDecl := Node.InterfaceDeclarations[I]; |
| 1082 |
if (IDecl.Field <> nil) and |
| 1083 |
((IDecl.Field is TSFNode) or |
| 1084 |
(IDecl.Field is TMFNode)) then |
| 1085 |
UniformsTextures.Add(IDecl.Field) |
| 1086 |
else |
| 1087 |
BindNonTextureUniform(IDecl, UniformMissingFromNode(Node), EnableDisable); |
| 1088 |
end; |
| 1089 |
end; |
| 1090 |
|
| 1091 |
procedure TX3DShaderProgram.BindUniforms(const Nodes: TX3DNodeList; |
| 1092 |
const EnableDisable: boolean); |
| 1093 |
var |
| 1094 |
I: Integer; |
| 1095 |
begin |
| 1096 |
for I := 0 to Nodes.Count - 1 do |
| 1097 |
BindUniforms(Nodes[I], EnableDisable); |
| 1098 |
end; |
| 1099 |
|
| 1100 |
{ TDynamicUniformSingle ------------------------------------------------------ } |
| 1101 |
|
| 1102 |
procedure TDynamicUniformSingle.SetUniform(AProgram: TX3DShaderProgram); |
| 1103 |
begin |
| 1104 |
AProgram.SetUniform(Name, Value); |
| 1105 |
end; |
| 1106 |
|
| 1107 |
{ TDynamicUniformVec3 -------------------------------------------------------- } |
| 1108 |
|
| 1109 |
procedure TDynamicUniformVec3.SetUniform(AProgram: TX3DShaderProgram); |
| 1110 |
begin |
| 1111 |
AProgram.SetUniform(Name, Value); |
| 1112 |
end; |
| 1113 |
|
| 1114 |
{ TDynamicUniformVec4 -------------------------------------------------------- } |
| 1115 |
|
| 1116 |
procedure TDynamicUniformVec4.SetUniform(AProgram: TX3DShaderProgram); |
| 1117 |
begin |
| 1118 |
AProgram.SetUniform(Name, Value); |
| 1119 |
end; |
| 1120 |
|
| 1121 |
{ TDynamicUniformMat4 -------------------------------------------------------- } |
| 1122 |
|
| 1123 |
procedure TDynamicUniformMat4.SetUniform(AProgram: TX3DShaderProgram); |
| 1124 |
begin |
| 1125 |
AProgram.SetUniform(Name, Value); |
| 1126 |
end; |
| 1127 |
|
| 1128 |
{ TDynamicUniformInteger -------------------------------------------------------- } |
| 1129 |
|
| 1130 |
procedure TDynamicUniformInteger.SetUniform(AProgram: TX3DShaderProgram); |
| 1131 |
begin |
| 1132 |
AProgram.SetUniform(Name, Value); |
| 1133 |
end; |
| 1134 |
|
| 1135 |
{ TShader ---------------------------------------------------------------- } |
| 1136 |
|
| 1137 |
function InsertIntoString(const Base: String; const P: Integer; const S: String): String; |
| 1138 |
begin |
| 1139 |
Result := Copy(Base, 1, P - 1) + S + SEnding(Base, P); |
| 1140 |
end; |
| 1141 |
|
| 1142 |
const |
| 1143 |
DefaultVertexShader: array [ { phong shading } boolean ] of string = ( |
| 1144 |
{$I main_shading_gouraud.vs.inc}, |
| 1145 |
{$I main_shading_phong.vs.inc} |
| 1146 |
); |
| 1147 |
DefaultFragmentShader: array [ { phong shading } boolean ] of string = ( |
| 1148 |
{$I main_shading_gouraud.fs.inc}, |
| 1149 |
{$I main_shading_phong.fs.inc} |
| 1150 |
); |
| 1151 |
DefaultGeometryShader = {$I geometry_shader_utils.gs.inc}; |
| 1152 |
|
| 1153 |
// TODO: fix this to pass color in new shaders (not using deprecated gl_FrontColor, gl_BackColor) |
| 1154 |
(* |
| 1155 |
GeometryShaderPassColors = |
| 1156 |
'#version 150 compatibility' +NL+ |
| 1157 |
|
| 1158 |
'void PLUG_geometry_vertex_set(const int index)' +NL+ |
| 1159 |
'{' +NL+ |
| 1160 |
' gl_FrontColor = gl_in[index].gl_FrontColor;' +NL+ |
| 1161 |
' gl_BackColor = gl_in[index].gl_BackColor;' +NL+ |
| 1162 |
'}' +NL+ |
| 1163 |
|
| 1164 |
'void PLUG_geometry_vertex_zero()' +NL+ |
| 1165 |
'{' +NL+ |
| 1166 |
' gl_FrontColor = vec4(0.0);' +NL+ |
| 1167 |
' gl_BackColor = vec4(0.0);' +NL+ |
| 1168 |
'}' +NL+ |
| 1169 |
|
| 1170 |
'void PLUG_geometry_vertex_add(const int index, const float scale)' +NL+ |
| 1171 |
'{' +NL+ |
| 1172 |
' gl_FrontColor += gl_in[index].gl_FrontColor * scale;' +NL+ |
| 1173 |
' gl_BackColor += gl_in[index].gl_BackColor * scale;' +NL+ |
| 1174 |
'}' +NL; |
| 1175 |
*) |
| 1176 |
|
| 1177 |
constructor TShader.Create; |
| 1178 |
begin |
| 1179 |
inherited; |
| 1180 |
Source := TShaderSource.Create; |
| 1181 |
LightShaders := TLightShaders.Create; |
| 1182 |
TextureShaders := TTextureCoordinateShaderList.Create; |
| 1183 |
ShadowMapShaders := TShadowMapShaderList.Create; |
| 1184 |
UniformsNodes := TX3DNodeList.Create(false); |
| 1185 |
DynamicUniforms := TDynamicUniformList.Create(true); |
| 1186 |
TextureMatrix := TCardinalList.Create; |
| 1187 |
|
| 1188 |
WarnMissingPlugs := true; |
| 1189 |
end; |
| 1190 |
|
| 1191 |
destructor TShader.Destroy; |
| 1192 |
begin |
| 1193 |
FreeAndNil(UniformsNodes); |
| 1194 |
FreeAndNil(LightShaders); |
| 1195 |
FreeAndNil(TextureShaders); |
| 1196 |
FreeAndNil(ShadowMapShaders); |
| 1197 |
FreeAndNil(Source); |
| 1198 |
FreeAndNil(DynamicUniforms); |
| 1199 |
FreeAndNil(TextureMatrix); |
| 1200 |
inherited; |
| 1201 |
end; |
| 1202 |
|
| 1203 |
procedure TShader.Clear; |
| 1204 |
var |
| 1205 |
ShaderType: TShaderType; |
| 1206 |
begin |
| 1207 |
for ShaderType := Low(TShaderType) to High(TShaderType) do |
| 1208 |
Source[ShaderType].Clear; |
| 1209 |
|
| 1210 |
WarnMissingPlugs := true; |
| 1211 |
HasGeometryMain := false; |
| 1212 |
|
| 1213 |
{ The rest of fields just restored to default clear state. |
| 1214 |
Note: use "Count := 0" instead of "Clear", this allows to keep Capacity of TList<T>.Clear, |
| 1215 |
which will hopefully avoid some resizing and make it faster. } |
| 1216 |
UniformsNodes.Count := 0; |
| 1217 |
TextureCoordGen := ''; |
| 1218 |
ClipPlanesCount := 0; |
| 1219 |
FragmentEnd := ''; |
| 1220 |
FShadowSampling := Low(TShadowSampling); |
| 1221 |
PlugIdentifiers := 0; |
| 1222 |
LightShaders.Count := 0; |
| 1223 |
TextureShaders.Count := 0; |
| 1224 |
ShadowMapShaders.Count := 0; |
| 1225 |
FCodeHash.Clear; |
| 1226 |
CodeHashFinalized := false; |
| 1227 |
SelectedNode := nil; |
| 1228 |
FShapeRequiresShaders := false; |
| 1229 |
FBumpMappingShader.Clear; |
| 1230 |
FSurfaceTextureShaders.Clear; |
| 1231 |
FFogEnabled := false; |
| 1232 |
{ No need to reset, will be set when FFogEnabled := true |
| 1233 |
FFogType := Low(TFogType); |
| 1234 |
FFogCoordinateSource := Low(TFogCoordinateSource); } |
| 1235 |
AppearanceEffects := nil; |
| 1236 |
GroupEffects := nil; |
| 1237 |
Lighting := false; |
| 1238 |
ColorPerVertexType := ctNone; |
| 1239 |
ColorPerVertexMode := cmReplace; |
| 1240 |
FPhongShading := false; |
| 1241 |
ShapeBoundingBoxInSceneEvent := nil; |
| 1242 |
FShapeBoundingBoxInWorldKnown := false; |
| 1243 |
Material := nil; |
| 1244 |
DynamicUniforms.Count := 0; |
| 1245 |
TextureMatrix.Count := 0; |
| 1246 |
NeedsCameraInverseMatrix := false; |
| 1247 |
NeedsMirrorPlaneTexCoords := false; |
| 1248 |
NeedsNormalsForTexGen := false; |
| 1249 |
RenderingCamera := nil; |
| 1250 |
FLightingModel := lmPhong; |
| 1251 |
MainTextureMapping := -1; |
| 1252 |
ColorSpaceLinear := false; |
| 1253 |
MultiTextureColor := White; |
| 1254 |
FAlphaTest := false; |
| 1255 |
UsesShadowMaps := false; |
| 1256 |
end; |
| 1257 |
|
| 1258 |
procedure TShader.Initialize(const APhongShading: boolean); |
| 1259 |
begin |
| 1260 |
FPhongShading := APhongShading; |
| 1261 |
FCodeHash.AddInteger(Ord(PhongShading) * 877); |
| 1262 |
|
| 1263 |
Source[stVertex].Count := 1; |
| 1264 |
Source[stVertex][0] := DefaultVertexShader[PhongShading]; |
| 1265 |
Source[stFragment].Count := 1; |
| 1266 |
Source[stFragment][0] := DefaultFragmentShader[PhongShading]; |
| 1267 |
Source[stGeometry].Count := 1; |
| 1268 |
Source[stGeometry][0] := DefaultGeometryShader; |
| 1269 |
end; |
| 1270 |
|
| 1271 |
procedure TShader.Plug(const EffectPartType: TShaderType; PlugValue: String; |
| 1272 |
CompleteCode: TShaderSource; const ForwardDeclareInFinalShader: boolean); |
| 1273 |
|
| 1274 |
function FindPlugOccurrence(const CommentBegin, Code: String; |
| 1275 |
const CodeSearchBegin: Integer; out PBegin, PEnd: Integer): boolean; |
| 1276 |
begin |
| 1277 |
Result := false; |
| 1278 |
PBegin := PosEx(CommentBegin, Code, CodeSearchBegin); |
| 1279 |
if PBegin <> 0 then |
| 1280 |
begin |
| 1281 |
PEnd := PosEx('*/', Code, PBegin + Length(CommentBegin)); |
| 1282 |
Result := PEnd <> 0; |
| 1283 |
if not Result then |
| 1284 |
WritelnWarning('VRML/X3D', Format('Plug comment "%s" not properly closed, treating like not declared', |
| 1285 |
[CommentBegin])); |
| 1286 |
end; |
| 1287 |
end; |
| 1288 |
|
| 1289 |
procedure InsertIntoCode(Code: TCastleStringList; |
| 1290 |
const CodeIndex, P: Integer; const S: String); |
| 1291 |
begin |
| 1292 |
Code[CodeIndex] := InsertIntoString(Code[CodeIndex], P, S); |
| 1293 |
end; |
| 1294 |
|
| 1295 |
var |
| 1296 |
PlugName, ProcedureName, PlugForwardDeclaration: String; |
| 1297 |
|
| 1298 |
function LookForPlugDeclaration(CodeForPlugDeclaration: TCastleStringList): boolean; |
| 1299 |
var |
| 1300 |
AnyOccurrencesInThisCodeIndex: boolean; |
| 1301 |
PBegin, PEnd, CodeSearchBegin, CodeIndex: Integer; |
| 1302 |
CommentBegin, Parameters, Declaration: String; |
| 1303 |
begin |
| 1304 |
CommentBegin := '/* PLUG: ' + PlugName + ' '; |
| 1305 |
Result := false; |
| 1306 |
for CodeIndex := 0 to CodeForPlugDeclaration.Count - 1 do |
| 1307 |
begin |
| 1308 |
CodeSearchBegin := 1; |
| 1309 |
AnyOccurrencesInThisCodeIndex := false; |
| 1310 |
while FindPlugOccurrence(CommentBegin, CodeForPlugDeclaration[CodeIndex], |
| 1311 |
CodeSearchBegin, PBegin, PEnd) do |
| 1312 |
begin |
| 1313 |
Parameters := Trim(CopyPos(CodeForPlugDeclaration[CodeIndex], PBegin + Length(CommentBegin), PEnd - 1)); |
| 1314 |
Declaration := ProcedureName + Parameters + ';' + NL; |
| 1315 |
InsertIntoCode(CodeForPlugDeclaration, CodeIndex, PBegin, Declaration); |
| 1316 |
|
| 1317 |
{ do not find again the same plug comment by FindPlugOccurrence } |
| 1318 |
CodeSearchBegin := PEnd + Length(Declaration); |
| 1319 |
|
| 1320 |
AnyOccurrencesInThisCodeIndex := true; |
| 1321 |
Result := true; |
| 1322 |
end; |
| 1323 |
|
| 1324 |
if AnyOccurrencesInThisCodeIndex then |
| 1325 |
begin |
| 1326 |
{ added "plugged_x" function must be forward declared first. |
| 1327 |
Otherwise it could be defined after it is needed, or inside different |
| 1328 |
compilation unit. } |
| 1329 |
if ForwardDeclareInFinalShader and (CodeIndex = 0) then |
| 1330 |
PlugDirectly(Source[EffectPartType], CodeIndex, '/* PLUG-DECLARATIONS */', PlugForwardDeclaration, true) else |
| 1331 |
PlugDirectly(CodeForPlugDeclaration, CodeIndex, '/* PLUG-DECLARATIONS */', PlugForwardDeclaration, true); |
| 1332 |
end; |
| 1333 |
end; |
| 1334 |
end; |
| 1335 |
|
| 1336 |
var |
| 1337 |
Code: TCastleStringList; |
| 1338 |
PlugDeclaredParameters: String; |
| 1339 |
AnyOccurrences: boolean; |
| 1340 |
begin |
| 1341 |
if CompleteCode = nil then |
| 1342 |
CompleteCode := Source; |
| 1343 |
Code := CompleteCode[EffectPartType]; |
| 1344 |
|
| 1345 |
{ if the final shader code is empty (on this type) then don't insert anything |
| 1346 |
(avoid creating shader without main()). |
| 1347 |
|
| 1348 |
For geometry shaders (EffectPartType = stGeometry), |
| 1349 |
this check actually does nothing. Geometry shaders always have at least |
| 1350 |
our code defining geometry_xxx functions, so they are never empty. } |
| 1351 |
if Source[EffectPartType].Count = 0 then |
| 1352 |
Exit; |
| 1353 |
|
| 1354 |
HasGeometryMain := HasGeometryMain or |
| 1355 |
( (EffectPartType = stGeometry) and (Pos('main()', PlugValue) <> 0) ); |
| 1356 |
|
| 1357 |
repeat |
| 1358 |
PlugName := FindPlugName(PlugValue, PlugDeclaredParameters); |
| 1359 |
if PlugName = '' then Break; |
| 1360 |
|
| 1361 |
{ When using some special plugs, we need to do define some symbols. } |
| 1362 |
if PlugName = 'texture_coord_shift' then |
| 1363 |
PlugDirectly(Source[stFragment], 0, '/* PLUG-DECLARATIONS */', |
| 1364 |
'#define HAS_TEXTURE_COORD_SHIFT', false); |
| 1365 |
if PlugName = 'texture_apply' then |
| 1366 |
WritelnWarning('Using PLUG_texture_apply is deprecated. Upgrade to ' + |
| 1367 |
'1. PLUG_main_texture_apply (to do something after main texture application; but remember that it happens *before* lighting application in case of Phong shading), ' + |
| 1368 |
'2. or PLUG_fragment_modify (to do final fragment color adjustment)'); |
| 1369 |
|
| 1370 |
{ PlugName is not needed below to make this unique, |
| 1371 |
but it makes reading shader code easier. } |
| 1372 |
ProcedureName := 'plugged_' + IntToStr(PlugIdentifiers) + '_' + PlugName; |
| 1373 |
StringReplaceAllVar(PlugValue, 'PLUG_' + PlugName, ProcedureName, false); |
| 1374 |
Inc(PlugIdentifiers); |
| 1375 |
|
| 1376 |
PlugForwardDeclaration := DeclareOnce(ProcedureName, |
| 1377 |
'void ' + ProcedureName + PlugDeclaredParameters + ';'); |
| 1378 |
|
| 1379 |
AnyOccurrences := LookForPlugDeclaration(Code); |
| 1380 |
{ If the plug declaration not found in Code, then try to find it in |
| 1381 |
the final shader. This happens if your Code is special for given |
| 1382 |
light/texture effect, and you try to use a plug that |
| 1383 |
is not special to the light/texture effect. For example, |
| 1384 |
using PLUG_vertex_object_space inside a X3DTextureNode.effects. } |
| 1385 |
if (not AnyOccurrences) and |
| 1386 |
(Code <> Source[EffectPartType]) then |
| 1387 |
AnyOccurrences := LookForPlugDeclaration(Source[EffectPartType]); |
| 1388 |
|
| 1389 |
if (not AnyOccurrences) and WarnMissingPlugs then |
| 1390 |
WritelnWarning('VRML/X3D', Format('Plug name "%s" not declared (in shader type "%s")', |
| 1391 |
[PlugName, ShaderTypeName[EffectPartType]])); |
| 1392 |
until false; |
| 1393 |
|
| 1394 |
{ regardless if any (and how many) plug points were found, |
| 1395 |
always insert PlugValue into Code } |
| 1396 |
Code.Add(PlugValue); |
| 1397 |
end; |
| 1398 |
|
| 1399 |
function TShader.PlugDirectly(Code: TCastleStringList; |
| 1400 |
const CodeIndex: Cardinal; |
| 1401 |
const PlugName, PlugValue: String; |
| 1402 |
const InsertAtBeginIfNotFound: boolean): boolean; |
| 1403 |
var |
| 1404 |
P: Integer; |
| 1405 |
begin |
| 1406 |
Result := false; |
| 1407 |
|
| 1408 |
if CodeIndex < Code.Count then |
| 1409 |
begin |
| 1410 |
P := Pos(PlugName, Code[CodeIndex]); |
| 1411 |
if P <> 0 then |
| 1412 |
begin |
| 1413 |
Code[CodeIndex] := InsertIntoString(Code[CodeIndex], P, PlugValue + NL); |
| 1414 |
Result := true; |
| 1415 |
end else |
| 1416 |
if InsertAtBeginIfNotFound then |
| 1417 |
begin |
| 1418 |
Code[CodeIndex] := PlugValue + NL + Code[CodeIndex]; |
| 1419 |
Result := true; |
| 1420 |
end; |
| 1421 |
end; |
| 1422 |
|
| 1423 |
if (not Result) and WarnMissingPlugs then |
| 1424 |
WritelnWarning('VRML/X3D', Format('Plug point "%s" not found', [PlugName])); |
| 1425 |
end; |
| 1426 |
|
| 1427 |
procedure TShader.Define(const DefineName: String; const ShaderType: TShaderType; |
| 1428 |
const PlugEarly: Boolean = false); |
| 1429 |
var |
| 1430 |
Declaration, PlugComment: String; |
| 1431 |
Code: TCastleStringList; |
| 1432 |
{$ifndef OpenGLES} |
| 1433 |
I: Integer; |
| 1434 |
{$endif} |
| 1435 |
begin |
| 1436 |
Declaration := '#define ' + DefineName; |
| 1437 |
Code := Source[ShaderType]; |
| 1438 |
PlugComment := Iff(PlugEarly, '/* PLUG-DECLARATIONS-EARLY */', '/* PLUG-DECLARATIONS */'); |
| 1439 |
|
| 1440 |
{$ifdef OpenGLES} |
| 1441 |
{ Do not add it to all Source[stXxx], as then GLSL compiler |
| 1442 |
will say "COLOR_PER_VERTEX macro redefinition", |
| 1443 |
because we glue all parts for OpenGLES. } |
| 1444 |
if Code.Count > 0 then |
| 1445 |
PlugDirectly(Code, 0, PlugComment, Declaration, true); |
| 1446 |
{$else} |
| 1447 |
for I := 0 to Code.Count - 1 do |
| 1448 |
PlugDirectly(Code, I, PlugComment, Declaration, true); |
| 1449 |
{$endif} |
| 1450 |
end; |
| 1451 |
|
| 1452 |
procedure TShader.EnableEffects(Effects: TMFNode; |
| 1453 |
const Code: TShaderSource; |
| 1454 |
const ForwardDeclareInFinalShader: boolean); |
| 1455 |
begin |
| 1456 |
EnableEffects(Effects.InternalItems, Code, ForwardDeclareInFinalShader); |
| 1457 |
end; |
| 1458 |
|
| 1459 |
procedure TShader.EnableEffects(Effects: TX3DNodeList; |
| 1460 |
const Code: TShaderSource; |
| 1461 |
const ForwardDeclareInFinalShader: boolean); |
| 1462 |
|
| 1463 |
procedure EnableEffect(Effect: TEffectNode); |
| 1464 |
|
| 1465 |
procedure EnableEffectPart(Part: TEffectPartNode); |
| 1466 |
var |
| 1467 |
Contents: String; |
| 1468 |
begin |
| 1469 |
Contents := Part.Contents; |
| 1470 |
if Contents <> '' then |
| 1471 |
begin |
| 1472 |
Plug(Part.ShaderType, Contents, Code, ForwardDeclareInFinalShader); |
| 1473 |
{ Right now, for speed, we do not call EnableEffects, or even Plug, |
| 1474 |
before LinkProgram. At which point ShapeRequiresShaders |
| 1475 |
is already known true. } |
| 1476 |
Assert(ShapeRequiresShaders); |
| 1477 |
end; |
| 1478 |
end; |
| 1479 |
|
| 1480 |
var |
| 1481 |
I: Integer; |
| 1482 |
begin |
| 1483 |
if not Effect.FdEnabled.Value then Exit; |
| 1484 |
|
| 1485 |
if not (Effect.Language in [slDefault, slGLSL]) then |
| 1486 |
begin |
| 1487 |
WritelnWarning('VRML/X3D', Format('Unknown shading language "%s" for Effect node', |
| 1488 |
[Effect.FdLanguage.Value])); |
| 1489 |
Exit; |
| 1490 |
end; |
| 1491 |
|
| 1492 |
for I := 0 to Effect.FdParts.Count - 1 do |
| 1493 |
if Effect.FdParts[I] is TEffectPartNode then |
| 1494 |
EnableEffectPart(TEffectPartNode(Effect.FdParts[I])); |
| 1495 |
|
| 1496 |
UniformsNodes.Add(Effect); |
| 1497 |
end; |
| 1498 |
|
| 1499 |
var |
| 1500 |
I: Integer; |
| 1501 |
begin |
| 1502 |
for I := 0 to Effects.Count - 1 do |
| 1503 |
if Effects[I] is TEffectNode then |
| 1504 |
EnableEffect(TEffectNode(Effects[I])); |
| 1505 |
end; |
| 1506 |
|
| 1507 |
procedure TShader.LinkProgram(AProgram: TX3DShaderProgram; |
| 1508 |
const ShapeNiceName: String); |
| 1509 |
var |
| 1510 |
TextureApply, TextureColorDeclare, TextureCoordInitialize, TextureCoordMatrix, |
| 1511 |
TextureAttributeDeclare, TextureVaryingDeclareVertex, TextureVaryingDeclareFragment, TextureUniformsDeclare, |
| 1512 |
GeometryVertexDeclare, GeometryVertexSet, GeometryVertexZero, GeometryVertexAdd: String; |
| 1513 |
TextureUniformsSet: Boolean; |
| 1514 |
|
| 1515 |
const |
| 1516 |
Structures: array [TLightingModel] of String = ( |
| 1517 |
{$I lighting_model_phong_structures.glsl.inc}, |
| 1518 |
{$I lighting_model_physical_structures.glsl.inc}, |
| 1519 |
{$I lighting_model_unlit_structures.glsl.inc} |
| 1520 |
); |
| 1521 |
|
| 1522 |
procedure EnableLightingModel; |
| 1523 |
const |
| 1524 |
LightingModelCode: array [TLightingModel, { PhongShading } Boolean] of String = ( |
| 1525 |
( |
| 1526 |
{$I lighting_model_phong_shading_gouraud.vs.inc}, |
| 1527 |
{$I lighting_model_phong_shading_phong.fs.inc} |
| 1528 |
), |
| 1529 |
( |
| 1530 |
{$I lighting_model_physical_shading_gouraud.vs.inc}, |
| 1531 |
{$I lighting_model_physical_shading_phong.fs.inc} |
| 1532 |
), |
| 1533 |
( |
| 1534 |
{$I lighting_model_unlit_shading_gouraud.vs.inc}, |
| 1535 |
{$I lighting_model_unlit_shading_phong.fs.inc} |
| 1536 |
) |
| 1537 |
); |
| 1538 |
var |
| 1539 |
LightingStage: TShaderType; |
| 1540 |
LightShader: TLightShader; |
| 1541 |
begin |
| 1542 |
{ Just like in EnableLights, don't add lights code in some cases } |
| 1543 |
if (Source[stFragment].Count = 0) or |
| 1544 |
(Source[stVertex].Count = 0) or |
| 1545 |
(SelectedNode <> nil) then |
| 1546 |
Exit; |
| 1547 |
|
| 1548 |
if PhongShading then |
| 1549 |
LightingStage := stFragment |
| 1550 |
else |
| 1551 |
LightingStage := stVertex; |
| 1552 |
|
| 1553 |
Source[LightingStage][0] := StringReplace(Source[LightingStage][0], |
| 1554 |
'/* CASTLE-LIGHTING-MODEL */', |
| 1555 |
LightingModelCode[LightingModel, PhongShading], []); |
| 1556 |
|
| 1557 |
Source[LightingStage][0] := StringReplace(Source[LightingStage][0], |
| 1558 |
'/* PLUG-DECLARATIONS */', |
| 1559 |
Structures[LightingModel] + '/* PLUG-DECLARATIONS */', []); |
| 1560 |
|
| 1561 |
for LightShader in LightShaders do |
| 1562 |
LightShader.LightingModel := LightingModel; |
| 1563 |
end; |
| 1564 |
|
| 1565 |
procedure RequireTextureCoordinateForSurfaceTextures; |
| 1566 |
|
| 1567 |
{ Make sure TextureShaders has an item |
| 1568 |
with TextureUnit = given TextureCoordinateId. } |
| 1569 |
procedure RequireTextureCoordinateId(const TextureCoordinateId: Cardinal); |
| 1570 |
var |
| 1571 |
I: Integer; |
| 1572 |
TexCoordShader: TTextureCoordinateShader; |
| 1573 |
begin |
| 1574 |
for I := 0 to TextureShaders.Count - 1 do |
| 1575 |
if TextureShaders[I].TextureUnit = TextureCoordinateId then |
| 1576 |
Exit; |
| 1577 |
|
| 1578 |
{ item with necessary TextureUnit not found, so create it } |
| 1579 |
TexCoordShader := TTextureCoordinateShader.Create; |
| 1580 |
TexCoordShader.HasMatrixTransform := TextureMatrix.IndexOf(TextureCoordinateId) <> -1; |
| 1581 |
TexCoordShader.TextureUnit := TextureCoordinateId; |
| 1582 |
TextureShaders.Add(TexCoordShader); |
| 1583 |
|
| 1584 |
{ Note that we don't call |
| 1585 |
|
| 1586 |
TexCoordShader.Prepare(FCodeHash); |
| 1587 |
|
| 1588 |
to change the hash at this point. It is not needed (the fact that |
| 1589 |
we use bump mapping or some "surface texture" was already |
| 1590 |
recorded in the hash), and changing hash at this point |
| 1591 |
could have bad consequences. } |
| 1592 |
end; |
| 1593 |
|
| 1594 |
var |
| 1595 |
SurfaceTexture: TSurfaceTexture; |
| 1596 |
begin |
| 1597 |
if FBumpMappingShader.BumpMapping <> bmNone then |
| 1598 |
RequireTextureCoordinateId(FBumpMappingShader.NormalMapTextureCoordinatesId); |
| 1599 |
|
| 1600 |
if MainTextureMapping <> -1 then |
| 1601 |
RequireTextureCoordinateId(MainTextureMapping); |
| 1602 |
|
| 1603 |
for SurfaceTexture := Low(TSurfaceTexture) to High(TSurfaceTexture) do |
| 1604 |
if FSurfaceTextureShaders.Items[SurfaceTexture].Enable then |
| 1605 |
RequireTextureCoordinateId( |
| 1606 |
FSurfaceTextureShaders.Items[SurfaceTexture].TextureCoordinatesId); |
| 1607 |
end; |
| 1608 |
|
| 1609 |
procedure EnableTextures; |
| 1610 |
var |
| 1611 |
I: Integer; |
| 1612 |
begin |
| 1613 |
TextureApply := ''; |
| 1614 |
TextureColorDeclare := ''; |
| 1615 |
TextureCoordInitialize := ''; |
| 1616 |
TextureCoordMatrix := ''; |
| 1617 |
TextureAttributeDeclare := ''; |
| 1618 |
TextureVaryingDeclareVertex := ''; |
| 1619 |
TextureVaryingDeclareFragment := ''; |
| 1620 |
TextureUniformsDeclare := ''; |
| 1621 |
GeometryVertexDeclare := ''; |
| 1622 |
GeometryVertexSet := ''; |
| 1623 |
GeometryVertexZero := ''; |
| 1624 |
GeometryVertexAdd := ''; |
| 1625 |
TextureUniformsSet := true; |
| 1626 |
|
| 1627 |
for I := 0 to TextureShaders.Count - 1 do |
| 1628 |
TextureShaders[I].Enable(MainTextureMapping, MultiTextureColor, |
| 1629 |
TextureApply, TextureColorDeclare, |
| 1630 |
TextureCoordInitialize, TextureCoordMatrix, |
| 1631 |
TextureAttributeDeclare, TextureVaryingDeclareVertex, TextureVaryingDeclareFragment, TextureUniformsDeclare, |
| 1632 |
GeometryVertexDeclare, GeometryVertexSet, GeometryVertexZero, GeometryVertexAdd); |
| 1633 |
end; |
| 1634 |
|
| 1635 |
{ Applies to shader necessary clip plane code, using ClipPlanes value. } |
| 1636 |
procedure EnableClipPlanes; |
| 1637 |
var |
| 1638 |
I: Integer; |
| 1639 |
PlaneName: String; |
| 1640 |
PlugVertexDeclarations, PlugVertexImplementation, PlugFragmentImplementation: String; |
| 1641 |
begin |
| 1642 |
{ This routine closely cooperates with method EnableClipPlane to set |
| 1643 |
up the necessary OpenGL(ES) state. |
| 1644 |
See TClipPlaneAlgorithm for comments what and why we do. } |
| 1645 |
|
| 1646 |
if ClipPlanesCount <> 0 then |
| 1647 |
begin |
| 1648 |
case FClipPlaneAlgorithm of |
| 1649 |
{$ifndef OpenGLES} |
| 1650 |
cpFixedFunction: |
| 1651 |
begin |
| 1652 |
Plug(stVertex, |
| 1653 |
'void PLUG_vertex_eye_space(const in vec4 vertex_eye, const in vec3 normal_eye)' +NL+ |
| 1654 |
'{' +NL+ |
| 1655 |
' gl_ClipVertex = vertex_eye;' +NL+ |
| 1656 |
'}'); |
| 1657 |
end; |
| 1658 |
|
| 1659 |
cpClipDistance: |
| 1660 |
begin |
| 1661 |
PlugVertexDeclarations := ''; |
| 1662 |
PlugVertexImplementation := ''; |
| 1663 |
|
| 1664 |
for I := 0 to ClipPlanesCount - 1 do |
| 1665 |
begin |
| 1666 |
PlaneName := 'castle_ClipPlane' + IntToStr(I); |
| 1667 |
PlugVertexDeclarations := PlugVertexDeclarations + |
| 1668 |
'uniform vec4 ' + PlaneName + ';' + NL; |
| 1669 |
PlugVertexImplementation := PlugVertexImplementation + |
| 1670 |
' gl_ClipDistance[' + IntToStr(I) + '] = dot(' + PlaneName + ', vertex_eye);' + NL; |
| 1671 |
end; |
| 1672 |
|
| 1673 |
Plug(stVertex, |
| 1674 |
PlugVertexDeclarations + |
| 1675 |
'void PLUG_vertex_eye_space(const in vec4 vertex_eye, const in vec3 normal_eye)' +NL+ |
| 1676 |
'{' +NL+ |
| 1677 |
PlugVertexImplementation + |
| 1678 |
'}'); |
| 1679 |
end; |
| 1680 |
{$endif} |
| 1681 |
|
| 1682 |
cpDiscard: |
| 1683 |
begin |
| 1684 |
PlugVertexDeclarations := ''; |
| 1685 |
PlugVertexImplementation := ''; |
| 1686 |
PlugFragmentImplementation := ''; |
| 1687 |
|
| 1688 |
for I := 0 to ClipPlanesCount - 1 do |
| 1689 |
begin |
| 1690 |
PlaneName := 'castle_ClipPlane' + IntToStr(I); |
| 1691 |
PlugVertexDeclarations := PlugVertexDeclarations + |
| 1692 |
'uniform vec4 ' + PlaneName + ';' + NL; |
| 1693 |
PlugVertexImplementation := PlugVertexImplementation + |
| 1694 |
' castle_ClipDistance[' + IntToStr(I) + '] = dot(' + PlaneName + ', vertex_eye);' + NL; |
| 1695 |
PlugFragmentImplementation := PlugFragmentImplementation + |
| 1696 |
' if (castle_ClipDistance[' + IntToStr(I) + '] < 0.0) discard;' + NL; |
| 1697 |
end; |
| 1698 |
|
| 1699 |
Plug(stVertex, |
| 1700 |
'varying float castle_ClipDistance[' + IntToStr(ClipPlanesCount) + '];' +NL+ |
| 1701 |
PlugVertexDeclarations + |
| 1702 |
'void PLUG_vertex_eye_space(const in vec4 vertex_eye, const in vec3 normal_eye)' +NL+ |
| 1703 |
'{' +NL+ |
| 1704 |
PlugVertexImplementation + |
| 1705 |
'}'); |
| 1706 |
|
| 1707 |
Plug(stFragment, |
| 1708 |
'varying float castle_ClipDistance[' + IntToStr(ClipPlanesCount) + '];' +NL+ |
| 1709 |
'void PLUG_main_texture_apply(inout vec4 fragment_color, const in vec3 normal)' +NL+ |
| 1710 |
'{' +NL+ |
| 1711 |
PlugFragmentImplementation + |
| 1712 |
'}'); |
| 1713 |
end; |
| 1714 |
end; |
| 1715 |
end; |
| 1716 |
|
| 1717 |
(* TODO: make this work with geometry shaders: (instead of 0, add each index) |
| 1718 |
ClipPlaneGeometryPlug := |
| 1719 |
'#version 150 compatibility' +NL+ |
| 1720 |
'void PLUG_geometry_vertex_set(const int index)' +NL+ |
| 1721 |
'{' +NL+ |
| 1722 |
' gl_ClipDistance[0] = gl_in[index].gl_ClipDistance[0];' +NL+ |
| 1723 |
'}' +NL+ |
| 1724 |
'void PLUG_geometry_vertex_zero()' +NL+ |
| 1725 |
'{' +NL+ |
| 1726 |
' gl_ClipDistance[0] = 0.0;' +NL+ |
| 1727 |
'}' +NL+ |
| 1728 |
'void PLUG_geometry_vertex_add(const int index, const float scale)' +NL+ |
| 1729 |
'{' +NL+ |
| 1730 |
' gl_ClipDistance[0] += gl_in[index].gl_ClipDistance[0] * scale;' +NL+ |
| 1731 |
'}' +NL; |
| 1732 |
*) |
| 1733 |
end; |
| 1734 |
|
| 1735 |
{ Applies effects from various strings here. |
| 1736 |
This also finalizes applying textures. } |
| 1737 |
procedure EnableInternalEffects; |
| 1738 |
const |
| 1739 |
ShadowMapsFunctions: array [TShadowSampling] of string = |
| 1740 |
( {$I shadow_map_common.fs.inc}, |
| 1741 |
'#define PCF4' + NL + {$I shadow_map_common.fs.inc}, |
| 1742 |
'#define PCF4_BILINEAR' + NL + {$I shadow_map_common.fs.inc}, |
| 1743 |
'#define PCF16' + NL + {$I shadow_map_common.fs.inc}, |
| 1744 |
{$I variance_shadow_map_common.fs.inc}); |
| 1745 |
ToneMappingFunctions = {$I tone_mapping.fs.inc}; |
| 1746 |
var |
| 1747 |
UniformsDeclare, TextureApplyPoint: String; |
| 1748 |
I: Integer; |
| 1749 |
begin |
| 1750 |
PlugDirectly(Source[stVertex], 0, '/* PLUG: vertex_eye_space', |
| 1751 |
TextureCoordInitialize + TextureCoordGen + TextureCoordMatrix, false); |
| 1752 |
|
| 1753 |
TextureApplyPoint := 'main_texture_apply'; |
| 1754 |
PlugDirectly(Source[stFragment], 0, '/* PLUG: ' + TextureApplyPoint, |
| 1755 |
TextureColorDeclare + TextureApply, false); |
| 1756 |
|
| 1757 |
PlugDirectly(Source[stFragment], 0, '/* PLUG: fragment_end', FragmentEnd, false); |
| 1758 |
|
| 1759 |
PlugDirectly(Source[stGeometry], 0, '/* PLUG-DECLARATIONS' , GeometryVertexDeclare, false); |
| 1760 |
PlugDirectly(Source[stGeometry], 0, '/* PLUG: geometry_vertex_set' , GeometryVertexSet , false); |
| 1761 |
PlugDirectly(Source[stGeometry], 0, '/* PLUG: geometry_vertex_zero', GeometryVertexZero , false); |
| 1762 |
PlugDirectly(Source[stGeometry], 0, '/* PLUG: geometry_vertex_add' , GeometryVertexAdd , false); |
| 1763 |
|
| 1764 |
UniformsDeclare := ''; |
| 1765 |
for I := 0 to DynamicUniforms.Count - 1 do |
| 1766 |
UniformsDeclare := UniformsDeclare + DynamicUniforms[I].Declaration; |
| 1767 |
if NeedsCameraInverseMatrix then |
| 1768 |
UniformsDeclare := UniformsDeclare + 'uniform mat4 castle_CameraInverseMatrix;' + NL; |
| 1769 |
|
| 1770 |
if not ( |
| 1771 |
PlugDirectly(Source[stFragment], 0, '/* PLUG-DECLARATIONS */', |
| 1772 |
TextureVaryingDeclareFragment + NL + |
| 1773 |
TextureUniformsDeclare + NL + |
| 1774 |
Iff(UsesShadowMaps, DeclareShadowFunctions, ''), |
| 1775 |
false) and |
| 1776 |
PlugDirectly(Source[stVertex], 0, '/* PLUG-DECLARATIONS */', |
| 1777 |
UniformsDeclare + |
| 1778 |
TextureAttributeDeclare + NL + TextureVaryingDeclareVertex, |
| 1779 |
false) ) then |
| 1780 |
begin |
| 1781 |
{ When we cannot find /* PLUG-DECLARATIONS */, it also means we have |
| 1782 |
base shader from ComposedShader. In this case, forcing |
| 1783 |
TextureXxxDeclare at the beginning of shader code |
| 1784 |
(by InsertAtBeginIfNotFound) would be bad (in case ComposedShader |
| 1785 |
has some #version at the beginning). So we choose the safer route |
| 1786 |
to *not* integrate our texture handling with ComposedShader. |
| 1787 |
|
| 1788 |
We also remove uniform values for textures, to avoid |
| 1789 |
"unused castle_texture_%d" warning. Setting TextureUniformsSet |
| 1790 |
will make it happen. } |
| 1791 |
TextureUniformsSet := false; |
| 1792 |
end; |
| 1793 |
|
| 1794 |
{ Don't add to empty Source[stFragment], in case ComposedShader |
| 1795 |
doesn't want any fragment shader. |
| 1796 |
Only add if we're not using shaders from custom ComposedShader |
| 1797 |
(SelectedNode not set). } |
| 1798 |
if (Source[stFragment].Count <> 0) and |
| 1799 |
(SelectedNode = nil) then |
| 1800 |
begin |
| 1801 |
if UsesShadowMaps then |
| 1802 |
Source[stFragment].Add(ShadowMapsFunctions[ShadowSampling]); |
| 1803 |
Source[stFragment].Add(ToneMappingFunctions); |
| 1804 |
end; |
| 1805 |
end; |
| 1806 |
|
| 1807 |
var |
| 1808 |
PassLightsUniforms: boolean; |
| 1809 |
|
| 1810 |
procedure EnableLights; |
| 1811 |
var |
| 1812 |
LightShader: TLightShader; |
| 1813 |
LightShaderCode: TShaderSource; |
| 1814 |
LightingStage: TShaderType; |
| 1815 |
LightShaderCodeBase: String; |
| 1816 |
begin |
| 1817 |
PassLightsUniforms := false; |
| 1818 |
|
| 1819 |
{ If we have no fragment/vertex shader (means that we used ComposedShader |
| 1820 |
node without one shader) then don't add any code. |
| 1821 |
Otherwise we would create a shader without any main() inside. |
| 1822 |
|
| 1823 |
Source.Append later also has some safeguard against this, |
| 1824 |
but we need to check it earlier (to avoid plugging LightShaderBack), |
| 1825 |
and check them both (as vertex and fragment code cooperates, |
| 1826 |
so we need both or none). |
| 1827 |
|
| 1828 |
Also don't add anything in case we're rendering a custom ComposedShader node. } |
| 1829 |
if (Source[stFragment].Count = 0) or |
| 1830 |
(Source[stVertex].Count = 0) or |
| 1831 |
(SelectedNode <> nil) then |
| 1832 |
Exit; |
| 1833 |
|
| 1834 |
if Lighting then |
| 1835 |
begin |
| 1836 |
Source[stFragment][0] := '#define LIT' + NL + Source[stFragment][0]; |
| 1837 |
Source[stVertex ][0] := '#define LIT' + NL + Source[stVertex ][0]; |
| 1838 |
|
| 1839 |
PassLightsUniforms := true; |
| 1840 |
|
| 1841 |
if PhongShading then |
| 1842 |
LightingStage := stFragment |
| 1843 |
else |
| 1844 |
LightingStage := stVertex; |
| 1845 |
|
| 1846 |
for LightShader in LightShaders do |
| 1847 |
begin |
| 1848 |
LightShaderCode := LightShader.Code; |
| 1849 |
|
| 1850 |
// Plug the "base" GLSL code of the light (with PLUG_add_light) |
| 1851 |
LightShaderCodeBase := LightShaderCode[LightingStage][0]; |
| 1852 |
LightShaderCodeBase := |
| 1853 |
// when "separate compilation units" are used (desktop OpenGL), need to redeclare structures |
| 1854 |
{$ifndef OpenGLES} Structures[LightingModel] + {$endif} |
| 1855 |
LightShaderCodeBase; |
| 1856 |
Plug(LightingStage, LightShaderCodeBase); |
| 1857 |
|
| 1858 |
{ Append the rest of LightShader, it may contain shadow maps utilities |
| 1859 |
and light plugs. } |
| 1860 |
Source.Append(LightShaderCode, LightingStage); |
| 1861 |
end; |
| 1862 |
end else |
| 1863 |
begin |
| 1864 |
// TODO: fix this to pass color in new shaders (not using deprecated gl_FrontColor, gl_BackColor) |
| 1865 |
// Plug(stGeometry, GeometryShaderPassColors); |
| 1866 |
end; |
| 1867 |
end; |
| 1868 |
|
| 1869 |
{ Define COLOR_PER_VERTEX* symbols for GLSL. } |
| 1870 |
procedure EnableShaderColorPerVertex; |
| 1871 |
begin |
| 1872 |
if ColorPerVertexType <> ctNone then |
| 1873 |
begin |
| 1874 |
{ TODO: need to pass castle_ColorPerVertexFragment onward? |
| 1875 |
Plug(stGeometry, GeometryShaderPassColors); |
| 1876 |
} |
| 1877 |
|
| 1878 |
Define('COLOR_PER_VERTEX', stVertex); |
| 1879 |
Define('COLOR_PER_VERTEX', stFragment); |
| 1880 |
case ColorPerVertexMode of |
| 1881 |
cmReplace: |
| 1882 |
begin |
| 1883 |
Define('COLOR_PER_VERTEX_REPLACE', stVertex); |
| 1884 |
Define('COLOR_PER_VERTEX_REPLACE', stFragment); |
| 1885 |
end; |
| 1886 |
cmModulate: |
| 1887 |
begin |
| 1888 |
Define('COLOR_PER_VERTEX_MODULATE', stVertex); |
| 1889 |
Define('COLOR_PER_VERTEX_MODULATE', stFragment); |
| 1890 |
end; |
| 1891 |
end; |
| 1892 |
case ColorPerVertexType of |
| 1893 |
ctNone: ; |
| 1894 |
ctRgb: |
| 1895 |
begin |
| 1896 |
Define('COLOR_PER_VERTEX_RGB', stVertex); |
| 1897 |
Define('COLOR_PER_VERTEX_RGB', stFragment); |
| 1898 |
end; |
| 1899 |
ctRgbAlpha: |
| 1900 |
begin |
| 1901 |
Define('COLOR_PER_VERTEX_RGB_ALPHA', stVertex); |
| 1902 |
Define('COLOR_PER_VERTEX_RGB_ALPHA', stFragment); |
| 1903 |
end; |
| 1904 |
end; |
| 1905 |
end; |
| 1906 |
end; |
| 1907 |
|
| 1908 |
procedure EnableShaderFog; |
| 1909 |
var |
| 1910 |
FogFactor, FogUniforms, CoordinateSource: String; |
| 1911 |
begin |
| 1912 |
if FFogEnabled then |
| 1913 |
begin |
| 1914 |
case FFogCoordinateSource of |
| 1915 |
fcDepth : CoordinateSource := '-vertex_eye.z'; |
| 1916 |
fcPassedCoordinate: CoordinateSource := 'castle_FogCoord'; |
| 1917 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 1918 |
else raise EInternalError.Create('TShader.EnableShaderFog:FogCoordinateSource?'); |
| 1919 |
{$endif} |
| 1920 |
end; |
| 1921 |
|
| 1922 |
Plug(stVertex, |
| 1923 |
'attribute float castle_FogCoord;' +NL+ |
| 1924 |
'varying float castle_FogFragCoord;' + NL+ |
| 1925 |
'void PLUG_vertex_eye_space(const in vec4 vertex_eye, const in vec3 normal_eye)' +NL+ |
| 1926 |
'{' +NL+ |
| 1927 |
' castle_FogFragCoord = ' + CoordinateSource + ';' +NL+ |
| 1928 |
'}'); |
| 1929 |
|
| 1930 |
FogUniforms := 'uniform float castle_FogVisibilityRange;'; |
| 1931 |
|
| 1932 |
// See equations in https://www.web3d.org/specifications/X3Dv4Draft/ISO-IEC19775-1v4-CD1/Part01/components/lighting.html#t-foginterpolant |
| 1933 |
case FFogType of |
| 1934 |
ftLinear: |
| 1935 |
begin |
| 1936 |
FogFactor := '1.0 - castle_FogFragCoord / castle_FogVisibilityRange'; |
| 1937 |
end; |
| 1938 |
ftExponential: |
| 1939 |
begin |
| 1940 |
FogFactor := '(castle_FogFragCoord < castle_FogVisibilityRange ? exp(-castle_FogFragCoord / (castle_FogVisibilityRange - castle_FogFragCoord)) : 0.0)'; |
| 1941 |
end; |
| 1942 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 1943 |
else raise EInternalError.Create('TShader.EnableShaderFog:FogType?'); |
| 1944 |
{$endif} |
| 1945 |
end; |
| 1946 |
|
| 1947 |
Plug(stFragment, |
| 1948 |
'varying float castle_FogFragCoord;' + NL+ |
| 1949 |
'uniform vec3 castle_FogColor;' +NL+ |
| 1950 |
FogUniforms + NL + |
| 1951 |
'void PLUG_fog_apply(inout vec4 fragment_color, const vec3 normal_eye_fragment)' +NL+ |
| 1952 |
'{' +NL+ |
| 1953 |
' fragment_color.rgb = mix(castle_FogColor, fragment_color.rgb, ' +NL+ |
| 1954 |
' clamp(' + FogFactor + ', 0.0, 1.0));' +NL+ |
| 1955 |
'}'); |
| 1956 |
end; |
| 1957 |
end; |
| 1958 |
|
| 1959 |
procedure SetupUniformsOnce; |
| 1960 |
var |
| 1961 |
I: Integer; |
| 1962 |
begin |
| 1963 |
AProgram.Enable; |
| 1964 |
|
| 1965 |
if TextureUniformsSet then |
| 1966 |
begin |
| 1967 |
for I := 0 to TextureShaders.Count - 1 do |
| 1968 |
if (TextureShaders[I] is TTextureShader) and |
| 1969 |
(TTextureShader(TextureShaders[I]).UniformName <> '') then |
| 1970 |
AProgram.SetUniform(TTextureShader(TextureShaders[I]).UniformName, |
| 1971 |
TTextureShader(TextureShaders[I]).UniformValue); |
| 1972 |
end; |
| 1973 |
|
| 1974 |
FBumpMappingShader.SetUniformsOnce(AProgram); |
| 1975 |
FSurfaceTextureShaders.SetUniformsOnce(AProgram); |
| 1976 |
|
| 1977 |
AProgram.BindUniforms(UniformsNodes, false); |
| 1978 |
|
| 1979 |
if PassLightsUniforms then |
| 1980 |
for I := 0 to LightShaders.Count - 1 do |
| 1981 |
LightShaders[I].SetUniformsOnce(AProgram); |
| 1982 |
|
| 1983 |
ShadowMapShaders.SetUniformsOnce(AProgram); |
| 1984 |
|
| 1985 |
AProgram.Disable; |
| 1986 |
end; |
| 1987 |
|
| 1988 |
procedure EnableMirrorPlaneTexCoords; |
| 1989 |
begin |
| 1990 |
if NeedsMirrorPlaneTexCoords then |
| 1991 |
Define('CASTLE_NEEDS_MIRROR_PLANE_TEX_COORDS', stVertex); |
| 1992 |
end; |
| 1993 |
|
| 1994 |
procedure PrepareCommonCode; |
| 1995 |
begin |
| 1996 |
if Source[stVertex].Count > 0 then |
| 1997 |
Source[stVertex][0] := StringReplace(Source[stVertex][0], |
| 1998 |
'/* CASTLE-COMMON-CODE */', {$I common.vs.inc}, [rfReplaceAll]); |
| 1999 |
if Source[stFragment].Count > 0 then |
| 2000 |
Source[stFragment][0] := StringReplace(Source[stFragment][0], |
| 2001 |
'/* CASTLE-COMMON-CODE */', {$I common.fs.inc}, [rfReplaceAll]); |
| 2002 |
end; |
| 2003 |
|
| 2004 |
var |
| 2005 |
ShaderType: TShaderType; |
| 2006 |
GeometryInputSize: String; |
| 2007 |
I: Integer; |
| 2008 |
begin |
| 2009 |
EnableLightingModel; // do this early, as later EnableLights may assume it's done |
| 2010 |
ShadowMapShaders.GenerateCode(Self); |
| 2011 |
RequireTextureCoordinateForSurfaceTextures; |
| 2012 |
EnableTextures; |
| 2013 |
EnableClipPlanes; |
| 2014 |
EnableInternalEffects; |
| 2015 |
EnableLights; |
| 2016 |
EnableShaderColorPerVertex; |
| 2017 |
PrepareCommonCode; // must be before FBumpMappingShader.GenerateCode to define PLUG texture_coord_shift |
| 2018 |
FBumpMappingShader.GenerateCode(Self); |
| 2019 |
FSurfaceTextureShaders.GenerateCode(Self); |
| 2020 |
EnableShaderFog; |
| 2021 |
if AppearanceEffects <> nil then |
| 2022 |
EnableEffects(AppearanceEffects); |
| 2023 |
if GroupEffects <> nil then |
| 2024 |
EnableEffects(GroupEffects); |
| 2025 |
EnableMirrorPlaneTexCoords; |
| 2026 |
|
| 2027 |
if HasGeometryMain then |
| 2028 |
begin |
| 2029 |
Define('HAS_GEOMETRY_SHADER', stFragment); |
| 2030 |
if GLVersion.VendorType = gvATI then |
| 2031 |
GeometryInputSize := 'gl_in.length()' else |
| 2032 |
GeometryInputSize := ''; |
| 2033 |
{ Replace CASTLE_GEOMETRY_INPUT_SIZE } |
| 2034 |
for I := 0 to Source[stGeometry].Count - 1 do |
| 2035 |
Source[stGeometry][I] := StringReplace(Source[stGeometry][I], |
| 2036 |
'CASTLE_GEOMETRY_INPUT_SIZE', GeometryInputSize, [rfReplaceAll]); |
| 2037 |
end else |
| 2038 |
Source[stGeometry].Clear; |
| 2039 |
|
| 2040 |
if GLVersion.BuggyGLSLFrontFacing then |
| 2041 |
Define('CASTLE_BUGGY_FRONT_FACING', stFragment); |
| 2042 |
if GLVersion.BuggyGLSLReadVarying then |
| 2043 |
Define('CASTLE_BUGGY_GLSL_READ_VARYING', stVertex); |
| 2044 |
if GLVersion.BuggyGLSLBumpMappingNumSteps then |
| 2045 |
Define('CASTLE_BUGGY_BUMP_MAPPING_NUM_STEPS', stFragment); |
| 2046 |
if ColorSpaceLinear then |
| 2047 |
Define('CASTLE_GAMMA_CORRECTION', stFragment); |
| 2048 |
if NeedsNormals then |
| 2049 |
Define('CASTLE_HAS_NORMALS', stVertex, true); |
| 2050 |
case ToneMapping of |
| 2051 |
tmNone: ; |
| 2052 |
tmUncharted: |
| 2053 |
begin |
| 2054 |
Define('CASTLE_TONE_MAPPING', stFragment); |
| 2055 |
Define('CASTLE_TONE_MAPPING_UNCHARTED', stFragment); |
| 2056 |
end; |
| 2057 |
tmHejlRichard: |
| 2058 |
begin |
| 2059 |
Define('CASTLE_TONE_MAPPING', stFragment); |
| 2060 |
Define('CASTLE_TONE_MAPPING_HEJLRICHARD', stFragment); |
| 2061 |
end; |
| 2062 |
tmACES: |
| 2063 |
begin |
| 2064 |
Define('CASTLE_TONE_MAPPING', stFragment); |
| 2065 |
Define('CASTLE_TONE_MAPPING_ACES', stFragment); |
| 2066 |
end; |
| 2067 |
end; |
| 2068 |
|
| 2069 |
try |
| 2070 |
if (Source[stVertex].Count = 0) and |
| 2071 |
(Source[stFragment].Count = 0) then |
| 2072 |
raise EGLSLError.Create('No vertex and no fragment shader for GLSL program'); |
| 2073 |
|
| 2074 |
for ShaderType := Low(ShaderType) to High(ShaderType) do |
| 2075 |
AProgram.AttachShader(ShaderType, Source[ShaderType]); |
| 2076 |
AProgram.Name := 'TShader:Shape:' + ShapeNiceName; |
| 2077 |
AProgram.Link; |
| 2078 |
|
| 2079 |
if SelectedNode <> nil then |
| 2080 |
SelectedNode.EventIsValid.Send(true); |
| 2081 |
except |
| 2082 |
if SelectedNode <> nil then |
| 2083 |
SelectedNode.EventIsValid.Send(false); |
| 2084 |
raise; |
| 2085 |
end; |
| 2086 |
|
| 2087 |
{ Note that user X3D uniform values go through SetUniformFromField, |
| 2088 |
which passes UniformMissing based on node configuration |
| 2089 |
(TEffectNode.UniformMissing, TComposedShaderNode.UniformMissing). |
| 2090 |
|
| 2091 |
So setting AProgram.UniformMissing below only controls what happens on our |
| 2092 |
built-in uniform values. |
| 2093 |
|
| 2094 |
Missing uniform name should be ignored, as it's normal in some cases: |
| 2095 |
When all the lights are off (including headlight) then normal vectors |
| 2096 |
are unused, and so the normalmap texture is unused. } |
| 2097 |
AProgram.UniformMissing := umIgnore; |
| 2098 |
|
| 2099 |
{ set uniforms that will not need to be updated at each SetupUniforms call } |
| 2100 |
SetupUniformsOnce; |
| 2101 |
end; |
| 2102 |
|
| 2103 |
procedure TShader.LinkFallbackProgram(AProgram: TX3DShaderProgram); |
| 2104 |
const |
| 2105 |
VS = {$I fallback.vs.inc}; |
| 2106 |
FS = {$I fallback.fs.inc}; |
| 2107 |
begin |
| 2108 |
AProgram.Name := 'TShader:Fallback'; |
| 2109 |
AProgram.AttachShader(stVertex, VS); |
| 2110 |
AProgram.AttachShader(stFragment, FS); |
| 2111 |
AProgram.Link; |
| 2112 |
|
| 2113 |
AProgram.UniformMissing := umIgnore; |
| 2114 |
end; |
| 2115 |
|
| 2116 |
function TShader.CodeHash: TShaderCodeHash; |
| 2117 |
|
| 2118 |
{ Add to FCodeHash some stuff that must be added at the end, |
| 2119 |
since it can be changed back (replacing previous values) during TShader |
| 2120 |
lifetime. } |
| 2121 |
procedure CodeHashFinalize; |
| 2122 |
begin |
| 2123 |
FCodeHash.AddInteger(Ord(ShadowSampling) * 1009); |
| 2124 |
FCodeHash.AddInteger(Ord(LightingModel) * 503); |
| 2125 |
FCodeHash.AddInteger(Ord(ColorSpaceLinear) * 347); |
| 2126 |
FCodeHash.AddInteger(Ord(ToneMapping) * 331); |
| 2127 |
FCodeHash.AddInteger(Ord(MainTextureMapping) * 839); |
| 2128 |
FCodeHash.AddFloat(MultiTextureColor.X, 5821); |
| 2129 |
FCodeHash.AddFloat(MultiTextureColor.Y, 5827); |
| 2130 |
FCodeHash.AddFloat(MultiTextureColor.Z, 5839); |
| 2131 |
FCodeHash.AddFloat(MultiTextureColor.W, 5843); |
| 2132 |
end; |
| 2133 |
|
| 2134 |
begin |
| 2135 |
if not CodeHashFinalized then |
| 2136 |
begin |
| 2137 |
CodeHashFinalize; |
| 2138 |
CodeHashFinalized := true; |
| 2139 |
end; |
| 2140 |
Result := FCodeHash; |
| 2141 |
end; |
| 2142 |
|
| 2143 |
procedure TShader.EnableTexture(const TextureUnit: Cardinal; |
| 2144 |
const TextureType: TTextureType; |
| 2145 |
const Node: TAbstractSingleTextureNode; |
| 2146 |
const Env: TTextureEnv); |
| 2147 |
var |
| 2148 |
TextureShader: TTextureShader; |
| 2149 |
begin |
| 2150 |
{ Enable for fixed-function pipeline } |
| 2151 |
if GLFeatures.EnableFixedFunction then |
| 2152 |
begin |
| 2153 |
if GLFeatures.UseMultiTexturing then |
| 2154 |
glActiveTexture(GL_TEXTURE0 + TextureUnit); |
| 2155 |
case TextureType of |
| 2156 |
tt2D : GLEnableTexture(et2D); |
| 2157 |
ttCubeMap: GLEnableTexture(etCubeMap); |
| 2158 |
tt3D : GLEnableTexture(et3D); |
| 2159 |
ttShader : GLEnableTexture(etNone); |
| 2160 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2161 |
else raise EInternalError.Create('TextureEnableDisable?'); |
| 2162 |
{$endif} |
| 2163 |
end; |
| 2164 |
end; |
| 2165 |
|
| 2166 |
{ Enable for shader pipeline } |
| 2167 |
|
| 2168 |
TextureShader := TTextureShader.Create; |
| 2169 |
TextureShader.HasMatrixTransform := (TextureMatrix.IndexOf(TextureUnit) <> -1); |
| 2170 |
TextureShader.TextureUnit := TextureUnit; |
| 2171 |
TextureShader.TextureType := TextureType; |
| 2172 |
TextureShader.Node := Node; |
| 2173 |
TextureShader.Env := Env; |
| 2174 |
TextureShader.Shader := Self; |
| 2175 |
|
| 2176 |
{ Change csMaterial to csPreviousTexture on the 1st texture slot. |
| 2177 |
This fixes the problem of TTextureShader.TextureEnvMix: |
| 2178 |
|
| 2179 |
- it has reliable definition of csPreviousTexture, |
| 2180 |
that also works for the 1st texture slot |
| 2181 |
(and means there "material base/alpha color", as we want). |
| 2182 |
|
| 2183 |
- it has hacky definition of csMaterial, |
| 2184 |
that just returns hardcoded (0.8,0.8,0.8,1). |
| 2185 |
This is good enough for rare cases when MultiTexture really uses |
| 2186 |
source=DIFFUSE/SPECULAR. |
| 2187 |
It is bad for the common case when this is the 1st texture slot |
| 2188 |
(maybe even the only texture slot! when not using MultiTexture) |
| 2189 |
that should be multiplied by material/per-vertex color. |
| 2190 |
} |
| 2191 |
if TextureShaders.Count = 0 then |
| 2192 |
begin |
| 2193 |
if TextureShader.Env.Source[cRGB] = csMaterial then |
| 2194 |
TextureShader.Env.Source[cRGB] := csPreviousTexture; |
| 2195 |
if TextureShader.Env.Source[cAlpha] = csMaterial then |
| 2196 |
TextureShader.Env.Source[cAlpha] := csPreviousTexture; |
| 2197 |
end; |
| 2198 |
|
| 2199 |
TextureShaders.Add(TextureShader); |
| 2200 |
|
| 2201 |
if (TextureType = ttShader) or |
| 2202 |
(Node.FdEffects.Count <> 0) or |
| 2203 |
{ MultiTexture.function requires shaders } |
| 2204 |
(Env.TextureFunction <> tfNone) then |
| 2205 |
ShapeRequiresShaders := true; |
| 2206 |
|
| 2207 |
TextureShader.Prepare(FCodeHash); |
| 2208 |
end; |
| 2209 |
|
| 2210 |
procedure TShader.EnableTexGen(const TextureUnit: Cardinal; |
| 2211 |
const Generation: TTexGenerationComplete; |
| 2212 |
const TransformToWorldSpace: boolean); |
| 2213 |
var |
| 2214 |
TexCoordName: String; |
| 2215 |
begin |
| 2216 |
{ Enable for fixed-function pipeline } |
| 2217 |
if GLFeatures.UseMultiTexturing then |
| 2218 |
glActiveTexture(GL_TEXTURE0 + TextureUnit); |
| 2219 |
{ Rest of code for fixed-function pipeline |
| 2220 |
(glTexGeni and glEnable(GL_TEXTURE_GEN_*)) is below } |
| 2221 |
|
| 2222 |
TexCoordName := TTextureShader.CoordName(TextureUnit); |
| 2223 |
|
| 2224 |
FCodeHash.AddInteger( |
| 2225 |
1303 * (Ord(Generation) + 1) + |
| 2226 |
1307 * (TextureUnit + 1)); |
| 2227 |
|
| 2228 |
{ Enable for fixed-function and shader pipeline } |
| 2229 |
case Generation of |
| 2230 |
tgSphere: |
| 2231 |
begin |
| 2232 |
if GLFeatures.EnableFixedFunction then |
| 2233 |
begin |
| 2234 |
{$ifndef OpenGLES} |
| 2235 |
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); |
| 2236 |
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); |
| 2237 |
glEnable(GL_TEXTURE_GEN_S); |
| 2238 |
glEnable(GL_TEXTURE_GEN_T); |
| 2239 |
{$endif} |
| 2240 |
end; |
| 2241 |
TextureCoordGen := TextureCoordGen + Format('%s.st = castle_generate_tex_coords_sphere(castle_vertex_eye, castle_normal_eye);', |
| 2242 |
[TexCoordName]); |
| 2243 |
NeedsNormalsForTexGen := true; |
| 2244 |
end; |
| 2245 |
tgNormal: |
| 2246 |
begin |
| 2247 |
if GLFeatures.EnableFixedFunction then |
| 2248 |
begin |
| 2249 |
{$ifndef OpenGLES} |
| 2250 |
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB); |
| 2251 |
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB); |
| 2252 |
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP_ARB); |
| 2253 |
glEnable(GL_TEXTURE_GEN_S); |
| 2254 |
glEnable(GL_TEXTURE_GEN_T); |
| 2255 |
glEnable(GL_TEXTURE_GEN_R); |
| 2256 |
{$endif} |
| 2257 |
end; |
| 2258 |
TextureCoordGen := TextureCoordGen + Format('%s.xyz = castle_normal_eye;' + NL, |
| 2259 |
[TexCoordName]); |
| 2260 |
NeedsNormalsForTexGen := true; |
| 2261 |
end; |
| 2262 |
tgReflection: |
| 2263 |
begin |
| 2264 |
if GLFeatures.EnableFixedFunction then |
| 2265 |
begin |
| 2266 |
{$ifndef OpenGLES} |
| 2267 |
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); |
| 2268 |
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); |
| 2269 |
glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_ARB); |
| 2270 |
glEnable(GL_TEXTURE_GEN_S); |
| 2271 |
glEnable(GL_TEXTURE_GEN_T); |
| 2272 |
glEnable(GL_TEXTURE_GEN_R); |
| 2273 |
{$endif} |
| 2274 |
end; |
| 2275 |
{ Negate reflect result --- just like for demo_models/water/water_reflections_normalmap.fs } |
| 2276 |
TextureCoordGen := TextureCoordGen + Format('%s.xyz = -reflect(-vec3(castle_vertex_eye), castle_normal_eye);' + NL, |
| 2277 |
[TexCoordName]); |
| 2278 |
NeedsNormalsForTexGen := true; |
| 2279 |
end; |
| 2280 |
tgcMirrorPlane: |
| 2281 |
begin |
| 2282 |
NeedsMirrorPlaneTexCoords := true; |
| 2283 |
NeedsCameraInverseMatrix := true; |
| 2284 |
TextureCoordGen := TextureCoordGen + Format('%s.xyz = castle_generate_tex_coords_mirror_plane(castle_CameraInverseMatrix * castle_vertex_eye);' + NL, |
| 2285 |
[TexCoordName]); |
| 2286 |
end; |
| 2287 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2288 |
else raise EInternalError.Create('TShader.EnableTexGen:Generation?'); |
| 2289 |
{$endif} |
| 2290 |
end; |
| 2291 |
|
| 2292 |
if TransformToWorldSpace then |
| 2293 |
begin |
| 2294 |
TextureCoordGen := TextureCoordGen + Format('%s.w = 0.0; %0:s = castle_CameraInverseMatrix * %0:s;' + NL, |
| 2295 |
[TexCoordName]); |
| 2296 |
NeedsCameraInverseMatrix := true; |
| 2297 |
FCodeHash.AddInteger(263); |
| 2298 |
end; |
| 2299 |
end; |
| 2300 |
|
| 2301 |
procedure TShader.EnableTexGen(const TextureUnit: Cardinal; |
| 2302 |
const Generation: TTexGenerationComponent; const Component: TTexComponent; |
| 2303 |
const Plane: TVector4); |
| 2304 |
const |
| 2305 |
PlaneComponentNames: array [TTexComponent] of char = ('S', 'T', 'R', 'Q'); |
| 2306 |
{ Note: R changes to p ! } |
| 2307 |
VectorComponentNames: array [TTexComponent] of char = ('s', 't', 'p', 'q'); |
| 2308 |
var |
| 2309 |
PlaneName, CoordSource, TexCoordName: String; |
| 2310 |
Uniform: TDynamicUniformVec4; |
| 2311 |
begin |
| 2312 |
{ Enable for fixed-function pipeline } |
| 2313 |
if GLFeatures.UseMultiTexturing then |
| 2314 |
glActiveTexture(GL_TEXTURE0 + TextureUnit); |
| 2315 |
|
| 2316 |
if GLFeatures.EnableFixedFunction then |
| 2317 |
begin |
| 2318 |
{$ifndef OpenGLES} |
| 2319 |
case Component of |
| 2320 |
0: glEnable(GL_TEXTURE_GEN_S); |
| 2321 |
1: glEnable(GL_TEXTURE_GEN_T); |
| 2322 |
2: glEnable(GL_TEXTURE_GEN_R); |
| 2323 |
3: glEnable(GL_TEXTURE_GEN_Q); |
| 2324 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2325 |
else raise EInternalError.Create('TShader.EnableTexGen:Component?'); |
| 2326 |
{$endif} |
| 2327 |
end; |
| 2328 |
{$endif} |
| 2329 |
end; |
| 2330 |
|
| 2331 |
{ Enable for shader pipeline. |
| 2332 |
See helpful info about simulating glTexGen in GLSL in: |
| 2333 |
http://www.mail-archive.com/[email protected]/msg14238.html } |
| 2334 |
|
| 2335 |
case Generation of |
| 2336 |
tgEye : begin PlaneName := 'EyePlane' ; CoordSource := 'castle_vertex_eye'; end; |
| 2337 |
tgObject: begin PlaneName := 'ObjectPlane'; CoordSource := 'vertex_object' ; end; |
| 2338 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 2339 |
else raise EInternalError.Create('TShader.EnableTexGen:Generation?'); |
| 2340 |
{$endif} |
| 2341 |
end; |
| 2342 |
|
| 2343 |
PlaneName := 'castle_' + PlaneName + PlaneComponentNames[Component] + |
| 2344 |
Format('%d', [TextureUnit]); |
| 2345 |
|
| 2346 |
Uniform := TDynamicUniformVec4.Create; |
| 2347 |
Uniform.Name := PlaneName; |
| 2348 |
Uniform.Declaration := 'uniform vec4 ' + PlaneName + ';' + NL; |
| 2349 |
Uniform.Value := Plane; |
| 2350 |
DynamicUniforms.Add(Uniform); |
| 2351 |
|
| 2352 |
TexCoordName := TTextureShader.CoordName(TextureUnit); |
| 2353 |
TextureCoordGen := TextureCoordGen + Format('%s.%s = dot(%s, %s);' + NL, |
| 2354 |
[TexCoordName, VectorComponentNames[Component], CoordSource, PlaneName]); |
| 2355 |
FCodeHash.AddInteger(1319 * (TextureUnit + 1) * (Ord(Generation) + 1) * (Component + 1)); |
| 2356 |
end; |
| 2357 |
|
| 2358 |
procedure TShader.DisableTexGen(const TextureUnit: Cardinal); |
| 2359 |
begin |
| 2360 |
{$ifndef OpenGLES} |
| 2361 |
if GLFeatures.EnableFixedFunction then |
| 2362 |
begin |
| 2363 |
{ Disable for fixed-function pipeline } |
| 2364 |
if GLFeatures.UseMultiTexturing then |
| 2365 |
glActiveTexture(GL_TEXTURE0 + TextureUnit); |
| 2366 |
glDisable(GL_TEXTURE_GEN_S); |
| 2367 |
glDisable(GL_TEXTURE_GEN_T); |
| 2368 |
glDisable(GL_TEXTURE_GEN_R); |
| 2369 |
glDisable(GL_TEXTURE_GEN_Q); |
| 2370 |
end; |
| 2371 |
{$endif} |
| 2372 |
end; |
| 2373 |
|
| 2374 |
procedure TShader.EnableTextureTransform(const TextureUnit: Cardinal; |
| 2375 |
const Matrix: TMatrix4); |
| 2376 |
var |
| 2377 |
Uniform: TDynamicUniformMat4; |
| 2378 |
begin |
| 2379 |
{ pass the uniform value with transformation to shader } |
| 2380 |
Uniform := TDynamicUniformMat4.Create; |
| 2381 |
Uniform.Name := TTextureShader.MatrixName(TextureUnit); |
| 2382 |
Uniform.Declaration := 'uniform mat4 ' + Uniform.Name + ';' + NL; |
| 2383 |
Uniform.Value := Matrix; |
| 2384 |
DynamicUniforms.Add(Uniform); |
| 2385 |
|
| 2386 |
{ multiply by the uniform value in shader } |
| 2387 |
TextureMatrix.Add(TextureUnit); |
| 2388 |
|
| 2389 |
FCodeHash.AddInteger(1973 * (TextureUnit + 1)); |
| 2390 |
end; |
| 2391 |
|
| 2392 |
procedure TShader.EnableClipPlane(const ClipPlaneIndex: Cardinal; |
| 2393 |
const Plane: TVector4); |
| 2394 |
var |
| 2395 |
Uniform: TDynamicUniformVec4; |
| 2396 |
begin |
| 2397 |
{ Note: This method closely cooperates with EnableClipPlanes, |
| 2398 |
that adds necessary GLSL code to make it all work. } |
| 2399 |
|
| 2400 |
Assert(ClipPlanesCount = ClipPlaneIndex); |
| 2401 |
Inc(ClipPlanesCount); |
| 2402 |
|
| 2403 |
{ This effectively adds 2003 * ClipPlanesCount to hash. } |
| 2404 |
FCodeHash.AddInteger(2003); |
| 2405 |
|
| 2406 |
{$ifndef OpenGLES} |
| 2407 |
if GLFeatures.EnableFixedFunction or (not GLFeatures.Version_3_1) then |
| 2408 |
begin |
| 2409 |
FClipPlaneAlgorithm := cpFixedFunction; |
| 2410 |
|
| 2411 |
CastleGlClipPlane(GL_CLIP_PLANE0 + ClipPlaneIndex, Vector4Double(Plane)); |
| 2412 |
glEnable(GL_CLIP_PLANE0 + ClipPlaneIndex); |
| 2413 |
end else |
| 2414 |
|
| 2415 |
if not ForceOpenGLESClipPlanes then |
| 2416 |
begin |
| 2417 |
FClipPlaneAlgorithm := cpClipDistance; |
| 2418 |
|
| 2419 |
glEnable(GL_CLIP_DISTANCE0 + ClipPlaneIndex); |
| 2420 |
|
| 2421 |
Uniform := TDynamicUniformVec4.Create; |
| 2422 |
Uniform.Name := 'castle_ClipPlane' + IntToStr(ClipPlaneIndex); |
| 2423 |
{ We leave Uniform.Declaration empty, |
| 2424 |
because we only declare them inside the necessary plug in EnableClipPlanes. } |
| 2425 |
{ Convert Plane from world space -> eye space. } |
| 2426 |
Uniform.Value := PlaneTransform(Plane, SceneModelView); |
| 2427 |
DynamicUniforms.Add(Uniform); |
| 2428 |
end else |
| 2429 |
|
| 2430 |
{$endif} |
| 2431 |
begin |
| 2432 |
FClipPlaneAlgorithm := cpDiscard; |
| 2433 |
|
| 2434 |
Uniform := TDynamicUniformVec4.Create; |
| 2435 |
Uniform.Name := 'castle_ClipPlane' + IntToStr(ClipPlaneIndex); |
| 2436 |
{ We leave Uniform.Declaration empty, |
| 2437 |
because we only declare them inside the necessary plug in EnableClipPlanes. } |
| 2438 |
{ Convert Plane from world space -> eye space. } |
| 2439 |
Uniform.Value := PlaneTransform(Plane, SceneModelView); |
| 2440 |
DynamicUniforms.Add(Uniform); |
| 2441 |
end; |
| 2442 |
end; |
| 2443 |
|
| 2444 |
procedure TShader.DisableClipPlane(const ClipPlaneIndex: Cardinal); |
| 2445 |
begin |
| 2446 |
{$ifndef OpenGLES} |
| 2447 |
case FClipPlaneAlgorithm of |
| 2448 |
cpFixedFunction: |
| 2449 |
glDisable(GL_CLIP_PLANE0 + ClipPlaneIndex); |
| 2450 |
cpClipDistance: |
| 2451 |
glDisable(GL_CLIP_DISTANCE0 + ClipPlaneIndex); |
| 2452 |
end; |
| 2453 |
{$endif} |
| 2454 |
end; |
| 2455 |
|
| 2456 |
procedure TShader.EnableAlphaTest(const AlphaCutoff: Single); |
| 2457 |
var |
| 2458 |
AlphaCutoffStr: String; |
| 2459 |
begin |
| 2460 |
FAlphaTest := true; |
| 2461 |
|
| 2462 |
{ Convert float to be a valid GLSL constant. |
| 2463 |
Make sure to use dot, and a fixed notation. } |
| 2464 |
AlphaCutoffStr := FloatToStrFDot(AlphaCutoff, ffFixed, { ignored } 0, 4); |
| 2465 |
|
| 2466 |
FragmentEnd := FragmentEnd + |
| 2467 |
'if (gl_FragColor.a < ' + AlphaCutoffStr + ')' + NL + |
| 2468 |
' discard;' + NL; |
| 2469 |
|
| 2470 |
FCodeHash.AddInteger(2011); |
| 2471 |
FCodeHash.AddFloat(AlphaCutoff, 2017); |
| 2472 |
end; |
| 2473 |
|
| 2474 |
procedure TShader.EnableBumpMapping(const BumpMapping: TBumpMapping; |
| 2475 |
const NormalMapTextureUnit, NormalMapTextureCoordinatesId: Cardinal; |
| 2476 |
const NormalMapScale: Single; |
| 2477 |
const HeightMapInAlpha: boolean; const HeightMapScale: Single); |
| 2478 |
begin |
| 2479 |
FBumpMappingShader.BumpMapping := BumpMapping; |
| 2480 |
FBumpMappingShader.NormalMapTextureUnit := NormalMapTextureUnit; |
| 2481 |
FBumpMappingShader.NormalMapTextureCoordinatesId := NormalMapTextureCoordinatesId; |
| 2482 |
FBumpMappingShader.NormalMapScale := NormalMapScale; |
| 2483 |
FBumpMappingShader.HeightMapInAlpha := HeightMapInAlpha; |
| 2484 |
FBumpMappingShader.HeightMapScale := HeightMapScale; |
| 2485 |
FBumpMappingShader.PrepareHash(FCodeHash); |
| 2486 |
|
| 2487 |
if BumpMapping <> bmNone then |
| 2488 |
ShapeRequiresShaders := true; |
| 2489 |
end; |
| 2490 |
|
| 2491 |
procedure TShader.EnableSurfaceTexture(const SurfaceTexture: TSurfaceTexture; |
| 2492 |
const TextureUnit, TextureCoordinatesId: Cardinal; |
| 2493 |
const UniformTextureName, PlugCode: String); |
| 2494 |
begin |
| 2495 |
FSurfaceTextureShaders.Items[SurfaceTexture].Enable := true; |
| 2496 |
FSurfaceTextureShaders.Items[SurfaceTexture].TextureUnit := TextureUnit; |
| 2497 |
FSurfaceTextureShaders.Items[SurfaceTexture].TextureCoordinatesId := TextureCoordinatesId; |
| 2498 |
FSurfaceTextureShaders.Items[SurfaceTexture].UniformTextureName := UniformTextureName; |
| 2499 |
FSurfaceTextureShaders.Items[SurfaceTexture].PlugCode := PlugCode; |
| 2500 |
|
| 2501 |
ShapeRequiresShaders := true; |
| 2502 |
|
| 2503 |
FSurfaceTextureShaders.Items[SurfaceTexture].PrepareHash(FCodeHash, SurfaceTexture); |
| 2504 |
end; |
| 2505 |
|
| 2506 |
procedure TShader.EnableLight(const Number: Cardinal; Light: PLightInstance); |
| 2507 |
var |
| 2508 |
LightShader: TLightShader; |
| 2509 |
begin |
| 2510 |
LightShader := TLightShader.Create; |
| 2511 |
LightShader.Number := Number; |
| 2512 |
LightShader.Light := Light; |
| 2513 |
LightShader.Node := Light^.Node; |
| 2514 |
LightShader.Shader := Self; |
| 2515 |
LightShader.RenderingCamera := RenderingCamera; |
| 2516 |
|
| 2517 |
LightShaders.Add(LightShader); |
| 2518 |
|
| 2519 |
if Light^.Node.FdEffects.Count <> 0 then |
| 2520 |
ShapeRequiresShaders := true; |
| 2521 |
|
| 2522 |
LightShader.Prepare(FCodeHash, LightShaders.Count - 1); |
| 2523 |
end; |
| 2524 |
|
| 2525 |
procedure TShader.EnableFog(const FogType: TFogType; |
| 2526 |
const FogCoordinateSource: TFogCoordinateSource; |
| 2527 |
const FogColor: TVector3; const FogVisibilityRange: Single); |
| 2528 |
var |
| 2529 |
UColor: TDynamicUniformVec3; |
| 2530 |
USingle: TDynamicUniformSingle; |
| 2531 |
begin |
| 2532 |
FFogEnabled := true; |
| 2533 |
FFogType := FogType; |
| 2534 |
FFogCoordinateSource := FogCoordinateSource; |
| 2535 |
FFogColor := FogColor; |
| 2536 |
FFogVisibilityRange := FogVisibilityRange; |
| 2537 |
FCodeHash.AddInteger( |
| 2538 |
67 * (Ord(FFogType) + 1) + |
| 2539 |
709 * (Ord(FFogCoordinateSource) + 1)); |
| 2540 |
|
| 2541 |
if FFogEnabled then |
| 2542 |
begin |
| 2543 |
USingle := TDynamicUniformSingle.Create; |
| 2544 |
USingle.Name := 'castle_FogVisibilityRange'; |
| 2545 |
USingle.Value := FFogVisibilityRange; |
| 2546 |
DynamicUniforms.Add(USingle); |
| 2547 |
|
| 2548 |
UColor := TDynamicUniformVec3.Create; |
| 2549 |
UColor.Name := 'castle_FogColor'; |
| 2550 |
UColor.Value := FFogColor; |
| 2551 |
{ We leave UColor.Declaration empty, just like USingle.Declaration above, |
| 2552 |
because we only declare them inside this plug |
| 2553 |
(which is a separate compilation unit for desktop OpenGL). } |
| 2554 |
DynamicUniforms.Add(UColor); |
| 2555 |
end; |
| 2556 |
end; |
| 2557 |
|
| 2558 |
procedure TShader.ModifyFog(const FogType: TFogType; |
| 2559 |
const FogCoordinateSource: TFogCoordinateSource; |
| 2560 |
const FogVisibilityRange: Single); |
| 2561 |
begin |
| 2562 |
{ Do not enable fog, or change it's color. Only work if fog already enabled. } |
| 2563 |
FFogType := FogType; |
| 2564 |
FFogCoordinateSource := FogCoordinateSource; |
| 2565 |
FFogVisibilityRange := FogVisibilityRange; |
| 2566 |
|
| 2567 |
FCodeHash.AddInteger( |
| 2568 |
431 * (Ord(FFogType) + 1) + |
| 2569 |
433 * (Ord(FFogCoordinateSource) + 1)); |
| 2570 |
end; |
| 2571 |
|
| 2572 |
function TShader.EnableCustomShaderCode(const Shaders: TMFNode; |
| 2573 |
out Node: TComposedShaderNode): boolean; |
| 2574 |
var |
| 2575 |
I, J: Integer; |
| 2576 |
Part: TShaderPartNode; |
| 2577 |
PartSource: String; |
| 2578 |
PartType, SourceType: TShaderType; |
| 2579 |
begin |
| 2580 |
Result := false; |
| 2581 |
for I := 0 to Shaders.Count - 1 do |
| 2582 |
begin |
| 2583 |
if (Shaders[I] is TComposedShaderNode) and |
| 2584 |
(TComposedShaderNode(Shaders[I]).Language in [slDefault, slGLSL]) then |
| 2585 |
Node := TComposedShaderNode(Shaders[I]) |
| 2586 |
else |
| 2587 |
Node := nil; |
| 2588 |
|
| 2589 |
if Node <> nil then |
| 2590 |
begin |
| 2591 |
Result := true; |
| 2592 |
|
| 2593 |
{ Clear whole Source } |
| 2594 |
for SourceType := Low(SourceType) to High(SourceType) do |
| 2595 |
if SourceType <> stGeometry then |
| 2596 |
Source[SourceType].Count := 0; |
| 2597 |
|
| 2598 |
{ Iterate over Node.FdParts, looking for vertex shaders |
| 2599 |
and fragment shaders. } |
| 2600 |
for J := 0 to Node.FdParts.Count - 1 do |
| 2601 |
if Node.FdParts[J] is TShaderPartNode then |
| 2602 |
begin |
| 2603 |
Part := TShaderPartNode(Node.FdParts[J]); |
| 2604 |
PartSource := Part.Contents; |
| 2605 |
if PartSource <> '' then |
| 2606 |
begin |
| 2607 |
PartType := Part.ShaderType; |
| 2608 |
Source[PartType].Add(PartSource); |
| 2609 |
if PartType = stGeometry then |
| 2610 |
HasGeometryMain := true; |
| 2611 |
end; |
| 2612 |
end; |
| 2613 |
|
| 2614 |
Node.EventIsSelected.Send(true); |
| 2615 |
|
| 2616 |
UniformsNodes.Add(Node); |
| 2617 |
|
| 2618 |
{ For sending isValid to this node later } |
| 2619 |
SelectedNode := Node; |
| 2620 |
|
| 2621 |
{ Ignore missing plugs, as our plugs are (probably) not found there } |
| 2622 |
WarnMissingPlugs := false; |
| 2623 |
|
| 2624 |
ShapeRequiresShaders := true; |
| 2625 |
|
| 2626 |
{ We add to FCodeHash custom shader node. |
| 2627 |
|
| 2628 |
We don't add the source code (all PartSource), we just add node |
| 2629 |
reference, for reasoning see TShaderCodeHash.AddEffects (equal |
| 2630 |
source code may still mean different uniforms). |
| 2631 |
Also, adding a node reference is faster that calculating string hash. |
| 2632 |
|
| 2633 |
Note that our original shader code (from glsl/template*) |
| 2634 |
is never added to hash --- there's no need, after all it's |
| 2635 |
always constant. } |
| 2636 |
FCodeHash.AddPointer(Node); |
| 2637 |
|
| 2638 |
Break; |
| 2639 |
end else |
| 2640 |
if Shaders[I] is TAbstractShaderNode then |
| 2641 |
TAbstractShaderNode(Shaders[I]).EventIsSelected.Send(false); |
| 2642 |
end; |
| 2643 |
end; |
| 2644 |
|
| 2645 |
procedure TShader.EnableAppearanceEffects(Effects: TMFNode); |
| 2646 |
begin |
| 2647 |
AppearanceEffects := Effects; |
| 2648 |
if AppearanceEffects.Count <> 0 then |
| 2649 |
begin |
| 2650 |
ShapeRequiresShaders := true; |
| 2651 |
FCodeHash.AddEffects(AppearanceEffects); |
| 2652 |
end; |
| 2653 |
end; |
| 2654 |
|
| 2655 |
procedure TShader.EnableGroupEffects(Effects: TX3DNodeList); |
| 2656 |
begin |
| 2657 |
GroupEffects := Effects; |
| 2658 |
if GroupEffects.Count <> 0 then |
| 2659 |
begin |
| 2660 |
ShapeRequiresShaders := true; |
| 2661 |
FCodeHash.AddEffects(GroupEffects); |
| 2662 |
end; |
| 2663 |
end; |
| 2664 |
|
| 2665 |
procedure TShader.EnableLighting; |
| 2666 |
begin |
| 2667 |
Lighting := true; |
| 2668 |
FCodeHash.AddInteger(7); |
| 2669 |
end; |
| 2670 |
|
| 2671 |
procedure TShader.EnableColorPerVertex(const AMode: TColorMode; const AColorType: TColorPerVertexType); |
| 2672 |
begin |
| 2673 |
Assert(AColorType <> ctNone); |
| 2674 |
{ This will cause appropriate shader later } |
| 2675 |
ColorPerVertexType := AColorType; |
| 2676 |
ColorPerVertexMode := AMode; |
| 2677 |
FCodeHash.AddInteger( |
| 2678 |
(Ord(AMode) + 1) * 29 + |
| 2679 |
(Ord(AColorType) + 1) * 601 |
| 2680 |
); |
| 2681 |
end; |
| 2682 |
|
| 2683 |
function TShader.DeclareShadowFunctions: String; |
| 2684 |
const |
| 2685 |
ShadowDeclare: array [boolean { vsm? }] of string = |
| 2686 |
('float shadow(sampler2DShadow shadowMap, const vec4 shadowMapCoord, const in float size);', |
| 2687 |
'float shadow(sampler2D shadowMap, const vec4 shadowMapCoord, const in float size);'); |
| 2688 |
begin |
| 2689 |
Result := ShadowDeclare[ShadowSampling = ssVarianceShadowMaps]; |
| 2690 |
end; |
| 2691 |
|
| 2692 |
procedure TShader.SetDynamicUniforms(AProgram: TX3DShaderProgram); |
| 2693 |
var |
| 2694 |
I: Integer; |
| 2695 |
begin |
| 2696 |
for I := 0 to LightShaders.Count - 1 do |
| 2697 |
LightShaders[I].SetDynamicUniforms(AProgram); |
| 2698 |
for I := 0 to DynamicUniforms.Count - 1 do |
| 2699 |
DynamicUniforms[I].SetUniform(AProgram); |
| 2700 |
|
| 2701 |
if NeedsCameraInverseMatrix then |
| 2702 |
begin |
| 2703 |
RenderingCamera.InverseMatrixNeeded; |
| 2704 |
AProgram.SetUniform('castle_CameraInverseMatrix', RenderingCamera.InverseMatrix); |
| 2705 |
end; |
| 2706 |
|
| 2707 |
if NeedsMirrorPlaneTexCoords and (MirrorPlaneUniforms <> nil) then |
| 2708 |
MirrorPlaneUniforms.SetDynamicUniforms(AProgram); |
| 2709 |
|
| 2710 |
ShadowMapShaders.SetDynamicUniforms(AProgram, RenderingCamera); |
| 2711 |
end; |
| 2712 |
|
| 2713 |
procedure TShader.AddScreenEffectCode(const Depth: boolean); |
| 2714 |
var |
| 2715 |
VS, FS: String; |
| 2716 |
begin |
| 2717 |
VS := ScreenEffectVertex; |
| 2718 |
FS := ScreenEffectFragment(Depth); |
| 2719 |
|
| 2720 |
{ Fragment shader code is required, as FS doesn't define main(). |
| 2721 |
Raising exception here prevents getting later a less clear exception |
| 2722 |
message from OpenGL(ES), |
| 2723 |
see https://github.com/castle-engine/castle-engine/issues/509 . |
| 2724 |
|
| 2725 |
Note that EGLSLError will be captured and turned into warning |
| 2726 |
by TScreenEffectResource.PrepareCore . |
| 2727 |
This is desirable for castle-model-viewer, as it should display only a warning |
| 2728 |
for invalid X3D models. } |
| 2729 |
|
| 2730 |
if Source[stFragment].Count = 0 then |
| 2731 |
raise EGLSLError.Create('No fragment shader code provided for a screen effect'); |
| 2732 |
|
| 2733 |
Source[stVertex].Insert(0, VS); |
| 2734 |
|
| 2735 |
{ For OpenGLES, ScreenEffectLibrary must be 1st shader, |
| 2736 |
and it will be glued with the user shader code. |
| 2737 |
So we glue it also on desktop OpenGL, for consistency |
| 2738 |
(so e.g. you should never repeat "uniform screen_width..."). } |
| 2739 |
|
| 2740 |
Assert(Source[stFragment].Count <> 0); // make check it above |
| 2741 |
Source[stFragment][0] := FS + Source[stFragment][0]; |
| 2742 |
end; |
| 2743 |
|
| 2744 |
function TShader.NeedsNormals: Boolean; |
| 2745 |
begin |
| 2746 |
// optimize lmUnlit: no need for normals data |
| 2747 |
Result := (LightingModel <> lmUnlit) or NeedsNormalsForTexGen; |
| 2748 |
end; |
| 2749 |
|
| 2750 |
function TShader.ShapeBoundingBoxInWorld: TBox3D; |
| 2751 |
begin |
| 2752 |
if not FShapeBoundingBoxInWorldKnown then |
| 2753 |
begin |
| 2754 |
FShapeBoundingBoxInWorldKnown := true; |
| 2755 |
FShapeBoundingBoxInWorld := ShapeBoundingBoxInSceneEvent().Transform(SceneTransform); |
| 2756 |
end; |
| 2757 |
Result := FShapeBoundingBoxInWorld; |
| 2758 |
end; |
| 2759 |
|
| 2760 |
procedure TShader.EnableShadowMap(const TextureUnit: Cardinal; |
| 2761 |
const ShadowMap: TGeneratedShadowMapNode); |
| 2762 |
var |
| 2763 |
ShadowMapShader: TShadowMapShader; |
| 2764 |
begin |
| 2765 |
ShapeRequiresShaders := true; |
| 2766 |
UsesShadowMaps := true; |
| 2767 |
|
| 2768 |
{ This method doesn't actually generate shader code to set uniforms, |
| 2769 |
it only adds information to ShadowMapShaders to do it later. } |
| 2770 |
ShadowMapShader.ShadowMap := ShadowMap; |
| 2771 |
ShadowMapShader.TextureUnit := TextureUnit; |
| 2772 |
ShadowMapShaders.Add(ShadowMapShader); |
| 2773 |
|
| 2774 |
ShadowMapShader.PrepareHash(FCodeHash); |
| 2775 |
end; |
| 2776 |
|
| 2777 |
end. |