Debian Codegraph @

src/scene/castleinternalrenderer_renderer.inc

raw
1 {%MainUnit castleinternalrenderer.pas}
2 {
3 Copyright 2002-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Renderer class (TRenderer). }
18
19 {$ifdef read_interface}
20 //type
21 TRenderer = class(TComponent)
22 private
23 { For speed, we keep a single instance of TShader,
24 instead of creating / destroying an instance at each RenderShape.
25 This is necessary, otherwise the constructor / destructor of TShader
26 would be bottle-necks. }
27 PreparedShader: TShader;
28
29 { Custom shaders for shadow maps.
30 Created on-demand, @nil initially. }
31 VarianceShadowMapsShaders, ShadowMapsShaders: TCustomShaders;
32
33 { ------------------------------------------------------------
34 Things usable only during Render. }
35
36 { How many texture units are used.
37
38 It's always clamped by the number of available texture units
39 (GLFeatures.MaxTextureUnits). Always <= 1 if OpenGL doesn't support
40 multitexturing (not GLFeatures.UseMultiTexturing). }
41 BoundTextureUnits: Cardinal;
42
43 { For how many texture units do we have to generate tex coords.
44
45 At the end, the idea is that this is <= BoundTextureUnits
46 (no point in generating tex coords for not existing textures).
47 However during render it may be temporarily > BoundTextureUnits
48 (in case we calculate it before actually binding the textures,
49 this may happen for textures in ComposedShader custom fields). }
50 TexCoordsNeeded: Cardinal;
51
52 { For which texture units we pushed and modified the texture matrix.
53 Only inside RenderShape.
54 Always <= 1 if not GLFeatures.UseMultiTexturing. }
55 TextureTransformUnitsUsed: Cardinal;
56
57 { Additional texture units used,
58 in addition to 0..TextureTransformUnitsUsed - 1.
59 Cleared by RenderShapeBegin, added by PushTextureUnit,
60 used by RenderShapeEnd. }
61 TextureTransformUnitsUsedMore: TInt32List;
62
63 {$ifndef OpenGLES}
64 { Call glPushMatrix, assuming that current matrix mode is GL_TEXTURE
65 and current tex unit is TexUnit (always make sure this is true when
66 calling it!).
67
68 It also records this fact, so that RenderShapeEnd will be able to
69 make pop texture matrix later.
70
71 In fact this optimizes push/pops on texture matrix stack, such that
72 X3D TextureTransform nodes and such together with PushTextureUnit
73 will only use only matrix stack place, even if texture will be
74 "pushed" multiple times (both by PushTextureUnit and normal
75 X3D TextureTransform realized in RenderShapeBegin.) }
76 procedure PushTextureUnit(const TexUnit: Cardinal);
77 {$endif}
78
79 { Check RenderOptions (like RenderOptions.BumpMapping) and OpenGL
80 context capabilities to see if bump mapping can be used. }
81 function BumpMapping(const RenderOptions: TCastleRenderOptions): TBumpMapping;
82
83 {$I castleinternalrenderer_surfacetextures.inc}
84 private
85 { ----------------------------------------------------------------- }
86
87 { Available between RenderBegin / RenderEnd. }
88 LightsRenderer: TLightsRenderer;
89
90 { Currently set fog parameters, during render. }
91 FogFunctionality: TFogFunctionality;
92 FogEnabled: boolean;
93 FogType: TFogType;
94 FogColor: TVector3;
95 FogVisibilityRangeScaled: Single;
96 FogVolumetric: boolean;
97 FogVolumetricDirection: TVector3;
98 FogVolumetricVisibilityStart: Single;
99
100 { Lights shining on all shapes, may be @nil. Set in each RenderBegin. }
101 GlobalLights: TLightInstancesList;
102
103 { Rendering parameters. Set in each RenderBegin, cleared to nil in RenderEnd. }
104 RenderingCamera: TRenderingCamera;
105 Statistics: PRenderStatistics;
106
107 { Rendering pass. Set in each RenderBegin and when changing WireframePass. }
108 FPass: TTotalRenderingPass;
109
110 FInternalPass: TInternalRenderingPass;
111 FWireframePass: TWireframeRenderingPass;
112 FUserPass: TUserRenderingPass;
113
114 procedure SetWireframePass(const Value: TWireframeRenderingPass);
115
116 { Calculate FPass based on FInternalPass, FWireframePass, FUserPass. }
117 procedure UpdatePass;
118
119 { Get X3D fog parameters, based on fog node and RenderOptions. }
120 class procedure GetFog(const AFogFunctionality: TFogFunctionality;
121 const RenderOptions: TCastleRenderOptions;
122 out Enabled, Volumetric: boolean;
123 out VolumetricDirection: TVector3;
124 out VolumetricVisibilityStart: Single);
125
126 { If multitexturing available, this sets currently active texture unit.
127 TextureUnit is newly active unit, this is added to GL_TEXTURE0.
128
129 So the only thing that you have to care about is to specify TextureUnit <
130 FreeGLTexturesCount.
131 Everything else (multitexturing availability, GL_TEXTURE0)
132 is taken care of inside here. }
133 class procedure ActiveTexture(const TextureUnit: Cardinal);
134
135 { Disable any (fixed-function) texturing (2D, 3D, cube map, and so on)
136 on given texture unit. }
137 class procedure DisableTexture(const TextureUnit: Cardinal);
138 class procedure DisableCurrentTexture;
139
140 procedure RenderShapeLineProperties(const Shape: TX3DRendererShape;
141 const RenderOptions: TCastleRenderOptions;
142 const Shader: TShader);
143 procedure RenderShapeMaterials(const Shape: TX3DRendererShape;
144 const RenderOptions: TCastleRenderOptions;
145 const Shader: TShader);
146 procedure RenderShapeLights(const Shape: TX3DRendererShape;
147 const RenderOptions: TCastleRenderOptions;
148 const Shader: TShader;
149 const Lighting: boolean);
150 procedure RenderShapeFog(const Shape: TX3DRendererShape;
151 const RenderOptions: TCastleRenderOptions;
152 const Shader: TShader;
153 const Lighting: boolean);
154 procedure RenderShapeTextureTransform(const Shape: TX3DRendererShape;
155 const RenderOptions: TCastleRenderOptions;
156 const Shader: TShader;
157 const Lighting: boolean);
158 procedure RenderShapeClipPlanes(const Shape: TX3DRendererShape;
159 const RenderOptions: TCastleRenderOptions;
160 const Shader: TShader;
161 const Lighting: boolean);
162 procedure RenderShapeCreateMeshRenderer(const Shape: TX3DRendererShape;
163 const RenderOptions: TCastleRenderOptions;
164 const Shader: TShader;
165 const Lighting: boolean);
166 procedure RenderShapeShaders(const Shape: TX3DRendererShape;
167 const RenderOptions: TCastleRenderOptions;
168 const Shader: TShader;
169 const Lighting: boolean;
170 const GeneratorClass: TArraysGeneratorClass;
171 const ExposedMeshRenderer: TObject);
172 procedure RenderShapeTextures(const Shape: TX3DRendererShape;
173 const RenderOptions: TCastleRenderOptions;
174 const Shader: TShader;
175 const Lighting: boolean;
176 const GeneratorClass: TArraysGeneratorClass;
177 const ExposedMeshRenderer: TObject;
178 const UsedGLSLTexCoordsNeeded: Cardinal);
179 procedure RenderShapeInside(const Shape: TX3DRendererShape;
180 const RenderOptions: TCastleRenderOptions;
181 const Shader: TShader;
182 const Lighting: boolean;
183 const GeneratorClass: TArraysGeneratorClass;
184 const ExposedMeshRenderer: TObject);
185
186 { Pieces of RenderBegin/End that are not dependent on any RenderBegin
187 parameters, and actually could be used to include inside many sequences
188 of RenderBegin/End. Like
189
190 ClassRenderBegin
191 RenderBegin
192 RenderEnd
193 RenderBegin
194 RenderEnd
195 RenderBegin
196 RenderEnd
197 ClassRenderEnd
198
199 They are *not* used like this, though, now.
200 They are just called from RenderBegin/End now.
201
202 In the past we had ViewportRenderBegin/End, called by viewport,
203 but then TRenderer state changes (e.g. depth range)
204 could easily accidentally affect TCastleTransform custom rendering
205 (e.g. using TCastleRenderUnlitMesh). }
206 class procedure ClassRenderBegin;
207 class procedure ClassRenderEnd;
208 public
209 type
210 TRenderMode = (
211 { Normal rendering. }
212 rmRender,
213 { Prepare for future rendering of the same shapes. }
214 rmPrepareRenderSelf,
215 { Prepare for future rendering of the cloned shapes
216 (made by TCastleSceneCore.Clone, or TX3DNode.DeepCopy). }
217 rmPrepareRenderClones
218 );
219 var
220 RenderMode: TRenderMode;
221
222 { Constructor. }
223 constructor Create(AOwner: TComponent); override;
224 destructor Destroy; override;
225
226 procedure RenderBegin(const AGlobalLights: TLightInstancesList;
227 const ARenderingCamera: TRenderingCamera;
228 const LightRenderEvent: TLightRenderEvent;
229 const AInternalPass: TInternalRenderingPass;
230 const AWireframePass: TWireframeRenderingPass;
231 const AUserPass: TUserRenderingPass;
232 const AStatistics: PRenderStatistics);
233 procedure RenderEnd;
234
235 { Render given shape.
236
237 @param(SceneTransform The transformation from scene to world,
238 i.e. the transformation that should be multiplied by the Shape
239 transformation (in @code(Shape.State.Transformation.Transform))
240 to get the final transformation to world.)
241 }
242 procedure RenderShape(const Shape: TX3DRendererShape;
243 const RenderOptions: TCastleRenderOptions;
244 const SceneTransform: TMatrix4;
245 const DepthRange: TDepthRange);
246
247 { Wireframe pass, to avoid recreating shaders when often switching
248 between wireframe and non-wireframe rendering.
249 This can change only between RenderBegin and RenderEnd.
250 Each RenderBegin sets it (to given parameter). }
251 property WireframePass: TWireframeRenderingPass
252 read FWireframePass write SetWireframePass;
253 end;
254 {$endif read_interface}
255
256 {$ifdef read_implementation}
257
258 { TRenderer ---------------------------------------------------------- }
259
260 constructor TRenderer.Create(AOwner: TComponent);
261 begin
262 inherited;
263 TextureTransformUnitsUsedMore := TInt32List.Create;
264 PreparedShader := TShader.Create;
265 end;
266
267 destructor TRenderer.Destroy;
268 begin
269 FreeAndNil(TextureTransformUnitsUsedMore);
270 FreeAndNil(PreparedShader);
271 FreeAndNil(ShadowMapsShaders);
272 FreeAndNil(VarianceShadowMapsShaders);
273 inherited;
274 end;
275
276 function TRenderer.BumpMapping(const RenderOptions: TCastleRenderOptions): TBumpMapping;
277 begin
278 if (RenderOptions.BumpMapping <> bmNone) and
279 RenderOptions.Textures and
280 (RenderOptions.Mode = rmFull) and
281 GLFeatures.UseMultiTexturing and
282 GLFeatures.Shaders then
283 Result := RenderOptions.BumpMapping else
284 Result := bmNone;
285 end;
286
287 class procedure TRenderer.ActiveTexture(const TextureUnit: Cardinal);
288 begin
289 if GLFeatures.UseMultiTexturing then
290 glActiveTexture(GL_TEXTURE0 + TextureUnit);
291 end;
292
293 class procedure TRenderer.DisableTexture(const TextureUnit: Cardinal);
294 begin
295 if GLFeatures.EnableFixedFunction then
296 begin
297 { This must be synchronized, and disable all that can be enabled
298 by TShape.EnableTexture }
299 ActiveTexture(TextureUnit);
300 DisableCurrentTexture;
301 end;
302 end;
303
304 class procedure TRenderer.DisableCurrentTexture;
305 begin
306 GLEnableTexture(etNone);
307 end;
308
309 class procedure TRenderer.GetFog(const AFogFunctionality: TFogFunctionality;
310 const RenderOptions: TCastleRenderOptions;
311 out Enabled, Volumetric: boolean;
312 out VolumetricDirection: TVector3;
313 out VolumetricVisibilityStart: Single);
314 begin
315 Enabled := (RenderOptions.Mode = rmFull) and
316 (AFogFunctionality <> nil) and
317 (AFogFunctionality.VisibilityRange <> 0.0);
318 Volumetric := Enabled and
319 AFogFunctionality.Volumetric and
320 // Volumetric fog is now only supported by shaders
321 (not GLFeatures.EnableFixedFunction);
322
323 if Volumetric then
324 begin
325 VolumetricVisibilityStart :=
326 AFogFunctionality.VolumetricVisibilityStart *
327 AFogFunctionality.TransformScale;
328 VolumetricDirection := AFogFunctionality.VolumetricDirection;
329 end else
330 begin
331 { whatever, just set them to any determined values }
332 VolumetricVisibilityStart := 0;
333 VolumetricDirection := TVector3.Zero;
334 end;
335 end;
336
337 class procedure TRenderer.ClassRenderBegin;
338 {$ifndef OpenGLES}
339 var
340 I: Integer;
341 {$endif}
342 begin
343 {$ifndef OpenGLES}
344 if GLFeatures.EnableFixedFunction then
345 begin
346 { ------------------------------------------------------------------------
347
348 Set fixed-function state that can be assumed by TRenderer,
349 and may change during rendering but will always be restored later.
350 So this secures from other rendering code (outside of TRenderer)
351 setting this OpenGL state to something unexpected.
352
353 E.g. shape may assume that GL_COLOR_MATERIAL is disabled.
354 If a shape does glEnable(GL_COLOR_MATERIAL), then it will for sure also do glDisable(GL_COLOR_MATERIAL)
355 at the end, so that state after shape rendering stays as it was.
356
357 This generally sets "typical" OpenGL state, and can be saved/restored during TCastleScene rendering.
358 }
359
360 // set texture unit to 0, this determines what is affected by glDisable(GL_TEXTURE_GEN_xxx)
361 if GLFeatures.UseMultiTexturing then
362 begin
363 ActiveTexture(0);
364 glClientActiveTexture(GL_TEXTURE0);
365 end;
366 glDisable(GL_TEXTURE_GEN_S);
367 glDisable(GL_TEXTURE_GEN_T);
368 glDisable(GL_TEXTURE_GEN_R);
369 glDisable(GL_TEXTURE_GEN_Q);
370
371 glDisable(GL_COLOR_MATERIAL);
372
373 for I := 0 to GLFeatures.MaxTextureUnits - 1 do
374 DisableTexture(I);
375
376 { ------------------------------------------------------------------------
377
378 Set fixed-function state that can be assumed by TRenderer,
379 and is constant for all shapes and for all scenes
380 (so it doesn't even depend on RenderOptions),
381 and we don't care that we just changed it also
382 for stuff outside of TRenderer (so we make no attempt to restore
383 it at ClassRenderEnd or even track previous state).
384
385 This generally sets "typical" OpenGL state, and remains constant during
386 RenderBegin/End rendering. }
387
388 { About using color material (what does glColor mean for materials):
389 - We always set diffuse material component from the color.
390 This satisfies all cases.
391 - TColorPerVertexCoordinateRenderer.RenderCoordinateBegin
392 takes care of actually enabling COLOR_MATERIAL, it assumes that
393 the state is as set below.
394 - We never change glColorMaterial during rendering,
395 so no need to call this in RenderEnd. }
396 glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
397
398 glShadeModel(GL_SMOOTH);
399
400 { While we don't *really need* to enable GL_NORMALIZE,
401 as we always try to provide normalized normals,
402 but avoiding GL_NORMALIZE doesn't give us *any* performance benefits.
403
404 And enabling GL_NORMALIZE:
405 - make us correct even when glTF/X3D files provided unnormalized normals.
406 - in case the object is scaled.
407 - it is also consistent with what shader pipeline is doing, it is always
408 normalizing normals. }
409 glEnable(GL_NORMALIZE);
410
411 glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, Ord(GL_TRUE));
412 end;
413 {$endif}
414 end;
415
416 class procedure TRenderer.ClassRenderEnd;
417 {$ifndef OpenGLES}
418 var
419 I: Integer;
420 {$endif}
421 begin
422 { Restore defaults, for other rendering code outside of TRenderer.
423
424 These RenderContext properties are always set before rendering every shape,
425 so ClassRenderBegin doesn't care to set them to any value,
426 and we just reset them in ClassRenderEnd. }
427 RenderContext.CullFace := false;
428 RenderContext.FrontFaceCcw := true;
429 RenderContext.CurrentProgram := nil;
430 RenderContext.FixedFunctionAlphaTestDisable;
431 RenderContext.FixedFunctionLighting := false;
432 RenderContext.DepthRange := DefaultDepthRange;
433
434 { Restore defaults, for other rendering code outside of TRenderer.
435
436 These RenderContext properties are always set in InitializeFromRenderOptions,
437 so they are constant for each shape.
438 So ClassRenderBegin doesn't care to set them to any value,
439 and we just reset them in ClassRenderEnd. }
440 RenderContext.PointSize := 1;
441 RenderContext.LineWidth := 1;
442 RenderContext.DepthTest := false;
443 RenderContext.ColorChannels := AllColorChannels;
444
445 { Restore default fixed-function state, for other rendering code outside of TRenderer.
446
447 These state things are adjusted by each shape,
448 and shape rendering assumes that at the beginning it is undefined
449 (so we don't care to set it in ClassRenderBegin),
450 and shape doesn't restore it (because next shape will adjust it anyway).
451 So we reset them at the end to not affect other objects rendered outside of TRenderer.
452
453 This generally sets "typical" OpenGL state,
454 for things that may have non-standard values during TCastleScene rendering,
455 and each shape is prepared that it has non-standard value (but rendering outside
456 of TRenderer may not be prepared for it). }
457
458 {$ifndef OpenGLES}
459 if GLFeatures.EnableFixedFunction then
460 begin
461 for I := 0 to GLFeatures.MaxLights - 1 do
462 glDisable(GL_LIGHT0 + I);
463 glDisable(GL_FOG);
464
465 { Restore active texture unit to 0.
466 This also sets texture unit for subsequent glTexEnvi call. }
467 if GLFeatures.UseMultiTexturing then
468 begin
469 ActiveTexture(0);
470 {$ifndef OpenGLES}
471 glClientActiveTexture(GL_TEXTURE0);
472 {$endif}
473 end;
474
475 { Reset GL_TEXTURE_ENV, otherwise it may be left GL_COMBINE
476 after rendering X3D model using MultiTexture. }
477 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
478 end;
479 {$endif}
480 end;
481
482 procedure TRenderer.RenderBegin(
483 const AGlobalLights: TLightInstancesList;
484 const ARenderingCamera: TRenderingCamera;
485 const LightRenderEvent: TLightRenderEvent;
486 const AInternalPass: TInternalRenderingPass;
487 const AWireframePass: TWireframeRenderingPass;
488 const AUserPass: TUserRenderingPass;
489 const AStatistics: PRenderStatistics);
490 begin
491 FrameProfiler.Start(fmRenderCoreRenderer);
492
493 ClassRenderBegin;
494
495 GlobalLights := AGlobalLights;
496 RenderingCamera := ARenderingCamera;
497 Statistics := AStatistics;
498 Assert(RenderingCamera <> nil);
499
500 Assert(FogFunctionality = nil);
501 Assert(not FogEnabled);
502
503 LightsRenderer := TLightsRenderer.Create;
504 LightsRenderer.LightRenderEvent := LightRenderEvent;
505 LightsRenderer.RenderingCamera := RenderingCamera;
506
507 FInternalPass := AInternalPass;
508 FWireframePass := AWireframePass;
509 FUserPass := AUserPass;
510 UpdatePass;
511 end;
512
513 procedure TRenderer.RenderEnd;
514 begin
515 { Tests:
516 Writeln('LightsRenderer stats: light setups done ',
517 LightsRenderer.Statistics[true], ' vs avoided ',
518 LightsRenderer.Statistics[false]); }
519
520 FreeAndNil(LightsRenderer);
521
522 FogFunctionality := nil;
523 FogEnabled := false;
524
525 { We need this in RenderEnd, not only in ClassRenderEnd.
526 Otherwise some operations could make the current texture unit not bound
527 to any valid texture, causing the glUniform1i setting shader uniform for texture
528 to raise OpenGL errors.
529 Testcase: 3d_model_viewer template. }
530 RenderContext.CurrentProgram := nil;
531
532 RenderingCamera := nil;
533 Statistics := nil;
534
535 ClassRenderEnd;
536
537 FrameProfiler.Stop(fmRenderCoreRenderer);
538 end;
539
540 procedure TRenderer.RenderShape(const Shape: TX3DRendererShape;
541 const RenderOptions: TCastleRenderOptions;
542 const SceneTransform: TMatrix4;
543 const DepthRange: TDepthRange);
544
545 procedure InitializeFromRenderOptions;
546 begin
547 { Set RenderContext properties, determined by RenderOptions.
548
549 These do not change within one TCastleScene,
550 but since the shape rendering order is now independent of TCastleScene
551 division (TShapesRenderer may render shapes from different TCastleScenes
552 in any order), so we have to assume that each RenderShape changes
553 RenderOptions.
554
555 Note that all TCastleTransform rendering code that is not inside TCastleScene
556 (e.g. custom TCastleTransform descendant using TCastleRenderUnlitMesh)
557 must be prepared that this state may be whatever, and so it must save,
558 set and restore this state.
559
560 ClassRenderEnd resets these things, so that this state does not "leak"
561 for stuff rendered outside of TCastleViewport. }
562 RenderContext.PointSize := RenderOptions.PointSize;
563 RenderContext.LineWidth := RenderOptions.LineWidth;
564 RenderContext.DepthTest := RenderOptions.DepthTest;
565 RenderContext.ColorChannels := RenderOptions.InternalColorChannels;
566
567 LightsRenderer.MaxLightsPerShape := RenderOptions.MaxLightsPerShape;
568 end;
569
570 { Initialize new Shader instance.
571 (May reuse previous Shader instance, but then it clears its contents.) }
572 function InitializeShader: TShader;
573
574 function ShapeUsesEnvironmentLight(const Shape: TX3DRendererShape): boolean;
575 var
576 I: Integer;
577 Lights: TLightInstancesList;
578 begin
579 Lights := Shape.State.Lights;
580 if Lights <> nil then
581 for I := 0 to Lights.Count - 1 do
582 if Lights.L[I].Node is TEnvironmentLightNode then
583 Exit(true);
584 Result := false;
585 end;
586
587 function ShapeMaybeUsesShadowMaps(const Shape: TX3DRendererShape): boolean;
588 var
589 Tex, SubTexture: TX3DNode;
590 I: Integer;
591 begin
592 Result := false;
593 if (Shape.Node <> nil) and
594 (Shape.Node.Appearance <> nil) then
595 begin
596 Tex := Shape.Node.Appearance.Texture;
597
598 if Tex is TGeneratedShadowMapNode then
599 Exit(true);
600
601 if Tex is TMultiTextureNode then
602 begin
603 for I := 0 to TMultiTextureNode(Tex).FdTexture.Count - 1 do
604 begin
605 SubTexture := TMultiTextureNode(Tex).FdTexture[I];
606 if SubTexture is TGeneratedShadowMapNode then
607 Exit(true);
608 end;
609 end;
610 end;
611 end;
612
613 function ShapeMaterialRequiresPhongShading(const Shape: TX3DRendererShape): boolean;
614 begin
615 Result :=
616 (Shape.Node <> nil) and
617 (Shape.Node.Appearance <> nil) and
618 (Shape.Node.Appearance.Material is TPhysicalMaterialNode);
619 end;
620
621 var
622 PhongShading: boolean;
623 begin
624 { instead of TShader.Create, reuse existing PreparedShader for speed }
625 Result := PreparedShader;
626 Result.Clear;
627 Result.RenderingCamera := RenderingCamera;
628
629 { calculate PhongShading }
630 PhongShading := RenderOptions.PhongShading;
631 { if Shape specifies Shading = Gouraud or Phong, use it }
632 if Shape.Node <> nil then
633 if Shape.Node.Shading = shPhong then
634 PhongShading := true
635 else
636 if Shape.Node.Shading = shGouraud then
637 PhongShading := false;
638 { if some feature requires PhongShading, make it true }
639 if ShapeTextureForcesPhongShading(Shape) or
640 ShapeMaybeUsesShadowMaps(Shape) or
641 ShapeMaterialRequiresPhongShading(Shape) or
642 ShapeUsesEnvironmentLight(Shape) or
643 (not Shape.Geometry.Solid) { two-sided lighting required by solid=FALSE } then
644 PhongShading := true;
645
646 Result.Initialize(PhongShading);
647
648 if PhongShading then
649 Result.ShapeRequiresShaders := true;
650
651 Result.ShapeBoundingBoxInSceneEvent := {$ifdef FPC}@{$endif} Shape.BoundingBox;
652 Result.SceneTransform := SceneTransform;
653 Result.SceneModelView := RenderingCamera.CurrentMatrix * SceneTransform;
654 Result.ShadowSampling := RenderOptions.ShadowSampling;
655 end;
656
657 procedure FixedFunctionBegin(const SceneModelView: TMatrix4);
658 begin
659 {$ifndef OpenGLES}
660 if GLFeatures.EnableFixedFunction then
661 begin
662 glPushMatrix;
663 glLoadMatrix(SceneModelView);
664
665 if RenderOptions.Mode = rmSolidColor then
666 glColorv(RenderOptions.SolidColor);
667 end;
668 {$endif}
669 end;
670
671 procedure FixedFunctionEnd;
672 begin
673 {$ifndef OpenGLES}
674 if GLFeatures.EnableFixedFunction then
675 glPopMatrix;
676 {$endif}
677 end;
678
679 var
680 Shader: TShader;
681 begin
682 InitializeFromRenderOptions;
683
684 RenderContext.DepthRange := DepthRange;
685
686 Shader := InitializeShader;
687 FixedFunctionBegin(Shader.SceneModelView);
688
689 RenderShapeLineProperties(Shape, RenderOptions, Shader);
690
691 FixedFunctionEnd;
692 end;
693
694 procedure TRenderer.RenderShapeLineProperties(const Shape: TX3DRendererShape;
695 const RenderOptions: TCastleRenderOptions;
696 const Shader: TShader);
697 var
698 LP: TLinePropertiesNode;
699 begin
700 if (Shape.Node <> nil) and { Shape.Node is nil for VRML <= 1.0 }
701 (Shape.Node.Appearance <> nil) then
702 LP := Shape.Node.Appearance.LineProperties
703 else
704 LP := nil;
705
706 if (LP <> nil) and LP.FdApplied.Value then
707 begin
708 RenderContext.LineWidth := Max(1.0, RenderOptions.LineWidth * LP.FdLineWidthScaleFactor.Value);
709 RenderContext.LineType := LP.LineType;
710 end else
711 begin
712 RenderContext.LineWidth := RenderOptions.LineWidth;
713 RenderContext.LineType := ltSolid;
714 end;
715
716 RenderShapeMaterials(Shape, RenderOptions, Shader);
717 end;
718
719 procedure TRenderer.RenderShapeMaterials(const Shape: TX3DRendererShape;
720 const RenderOptions: TCastleRenderOptions;
721 const Shader: TShader);
722
723 {$I castleinternalrenderer_materials.inc}
724
725 begin
726 RenderMaterialsBegin;
727 RenderShapeLights(Shape, RenderOptions, Shader, Lighting);
728 end;
729
730 procedure TRenderer.RenderShapeLights(const Shape: TX3DRendererShape;
731 const RenderOptions: TCastleRenderOptions;
732 const Shader: TShader;
733 const Lighting: boolean);
734 var
735 FinalGlobalLights, SceneLights: TLightInstancesList;
736 begin
737 { This is done after setting Shader.MaterialSpecularColor
738 by RenderMaterialsBegin,
739 as MaterialSpecularColor must be already set during Shader.EnableLight. }
740
741 { When lighting is off (for either shaders or fixed-function),
742 there is no point in setting up lights. }
743 if Lighting then
744 begin
745 if RenderOptions.ReceiveGlobalLights then
746 FinalGlobalLights := GlobalLights
747 else
748 FinalGlobalLights := nil;
749
750 if RenderOptions.ReceiveSceneLights then
751 SceneLights := Shape.State.Lights
752 else
753 SceneLights := nil;
754
755 LightsRenderer.Render(Shape, FinalGlobalLights, SceneLights, Shader);
756 end;
757
758 RenderShapeFog(Shape, RenderOptions, Shader, Lighting);
759 end;
760
761 procedure TRenderer.RenderShapeFog(const Shape: TX3DRendererShape;
762 const RenderOptions: TCastleRenderOptions;
763 const Shader: TShader;
764 const Lighting: boolean);
765
766 const
767 FogCoordinateSource: array [boolean { volumetric }] of TFogCoordinateSource =
768 ( fcDepth, fcPassedCoordinate );
769
770 { Set OpenGL fog based on given fog node. Returns also fog parameters,
771 like GetFog. }
772 procedure RenderFog(const AFogFunctionality: TFogFunctionality;
773 out Volumetric: boolean;
774 out VolumetricDirection: TVector3;
775 out VolumetricVisibilityStart: Single);
776 var
777 VisibilityRangeScaled: Single;
778 begin
779 GetFog(AFogFunctionality, RenderOptions,
780 FogEnabled, Volumetric, VolumetricDirection, VolumetricVisibilityStart);
781
782 if FogEnabled then
783 begin
784 Assert(AFogFunctionality <> nil);
785
786 VisibilityRangeScaled :=
787 AFogFunctionality.VisibilityRange *
788 AFogFunctionality.TransformScale;
789
790 { calculate FogType and other Fog parameters }
791 FogType := AFogFunctionality.FogType;
792 FogColor := AFogFunctionality.Color;
793 FogVisibilityRangeScaled := VisibilityRangeScaled;
794 end;
795 end;
796
797 const
798 FogConstantDensityFactor = 3.0; //< Necessary for exponential fog in fixed-function
799 begin
800 { Enable / disable fog and set fog parameters if needed }
801 if FogFunctionality <> Shape.Fog then
802 begin
803 FogFunctionality := Shape.Fog;
804 RenderFog(FogFunctionality, FogVolumetric,
805 FogVolumetricDirection, FogVolumetricVisibilityStart);
806
807 {$ifndef OpenGLES}
808 if GLFeatures.EnableFixedFunction then
809 begin
810 { Set fixed-function fog parameters. }
811 if FogEnabled then
812 begin
813 glFogv(GL_FOG_COLOR, Vector4(FogColor, 1.0));
814 case FogType of
815 ftLinear:
816 begin
817 glFogi(GL_FOG_MODE, GL_LINEAR);
818 glFogf(GL_FOG_START, 0);
819 glFogf(GL_FOG_END, FogVisibilityRangeScaled);
820 end;
821 ftExponential:
822 begin
823 glFogi(GL_FOG_MODE, GL_EXP);
824 glFogf(GL_FOG_DENSITY, FogConstantDensityFactor / FogVisibilityRangeScaled);
825 end;
826 {$ifndef COMPILER_CASE_ANALYSIS}
827 else raise EInternalError.Create('TRenderer.RenderShapeFog:FogType? 2');
828 {$endif}
829 end;
830 { We want to be able to render any scene --- so we have to be prepared
831 that fog interpolation has to be corrected for perspective. }
832 glHint(GL_FOG_HINT, GL_NICEST);
833 glEnable(GL_FOG);
834 end else
835 glDisable(GL_FOG);
836 end;
837 {$endif}
838 end;
839
840 if FogEnabled then
841 Shader.EnableFog(FogType, FogCoordinateSource[FogVolumetric],
842 FogColor, FogVisibilityRangeScaled);
843 RenderShapeTextureTransform(Shape, RenderOptions, Shader, Lighting);
844 end;
845
846 procedure TRenderer.RenderShapeTextureTransform(const Shape: TX3DRendererShape;
847 const RenderOptions: TCastleRenderOptions;
848 const Shader: TShader; const Lighting: boolean);
849 var
850 TextureTransform: TAbstractTextureTransformNode;
851 Child: TX3DNode;
852 Transforms: TMFNode;
853 I, FirstTexUnit: Integer;
854 State: TX3DGraphTraverseState;
855 Matrix: TMatrix4;
856 begin
857 TextureTransformUnitsUsed := 0;
858 TextureTransformUnitsUsedMore.Count := 0;
859
860 { in case of FontTextureNode <> nil, 1 less texture unit is available.
861 Everything we do, must be shifted by 1 texture unit. }
862 if Shape.OriginalGeometry.FontTextureNode <> nil then
863 FirstTexUnit := 1 else
864 FirstTexUnit := 0;
865
866 State := Shape.State;
867
868 if (State.ShapeNode = nil { VRML 1.0, always some texture transform }) or
869 ( (State.ShapeNode <> nil) and
870 (State.ShapeNode.Appearance <> nil) and
871 (State.ShapeNode.Appearance.TextureTransform <> nil { VRML 2.0 with tex transform })
872 ) then
873 begin
874 {$ifndef OpenGLES}
875 if GLFeatures.EnableFixedFunction then
876 begin
877 glMatrixMode(GL_TEXTURE);
878 end;
879 {$endif}
880
881 { We work assuming that texture matrix before RenderShape was identity.
882 Texture transform encoded in VRML/X3D will be multiplied by this.
883
884 This allows the programmer to eventually transform all textures
885 by placing non-identity texture matrix (just like a programmer
886 can transform whole rendered model by changing modelview matrix).
887 So this is a good thing.
888
889 Additional advantage is that we do not have to explicitly "clear"
890 the texture matrix if it's an identity transformation in VRML/X3D.
891 We just let it stay like it was.
892
893 This also nicely cooperates with X3D MultiTextureTransform desired
894 behavior: "If there are too few entries in the textureTransform field,
895 identity matrices shall be used for all remaining undefined channels.".
896 Which means that looking at MultiTextureTransform node, we know exactly
897 on which texture units we have to apply transform: we can leave
898 the remaining texture units as they were, regardless of whether
899 MultiTexture is used at all and regardless of how many texture units
900 are actually used by MultiTexture. }
901
902 { TODO: for bump mapping, TextureTransform should be done on more than one texture unit. }
903
904 if State.ShapeNode = nil then
905 begin
906 { No multitexturing in VRML 1.0, just always transform first tex unit. }
907 if FirstTexUnit < GLFeatures.MaxTextureUnits then
908 begin
909 TextureTransformUnitsUsed := 1;
910 if GLFeatures.EnableFixedFunction then
911 begin
912 {$ifndef OpenGLES}
913 ActiveTexture(FirstTexUnit);
914 glPushMatrix;
915 glMultMatrix(State.TextureTransform);
916 {$endif}
917 end;
918 Shader.EnableTextureTransform(FirstTexUnit, State.TextureTransform);
919 end;
920 end else
921 begin
922 // conditions above should have already checked this, we have some texture transform
923 Assert(State.ShapeNode <> nil);
924 Assert(State.ShapeNode.Appearance <> nil);
925 Assert(State.ShapeNode.Appearance.TextureTransform <> nil);
926 TextureTransform := State.ShapeNode.Appearance.TextureTransform;
927 if TextureTransform <> nil then
928 begin
929 if TextureTransform is TMultiTextureTransformNode then
930 begin
931 Transforms := TMultiTextureTransformNode(TextureTransform).FdTextureTransform;
932
933 { Multitexturing, so use as many texture units as there are children in
934 MultiTextureTransform.textureTransform.
935 Cap by available texture units. }
936 TextureTransformUnitsUsed := Min(Transforms.Count,
937 GLFeatures.MaxTextureUnits - FirstTexUnit);
938
939 for I := 0 to TextureTransformUnitsUsed - 1 do
940 begin
941 if GLFeatures.EnableFixedFunction then
942 begin
943 {$ifndef OpenGLES}
944 ActiveTexture(FirstTexUnit + I);
945 glPushMatrix;
946 {$endif}
947 end;
948 Child := Transforms[I];
949 if (Child <> nil) and
950 (Child is TAbstractTextureTransformNode) then
951 begin
952 if Child is TMultiTextureTransformNode then
953 WritelnWarning('VRML/X3D', 'MultiTextureTransform.textureTransform list cannot contain another MultiTextureTransform instance') else
954 begin
955 Matrix := TAbstractTextureTransformNode(Child).TransformMatrix;
956 if GLFeatures.EnableFixedFunction then
957 begin
958 {$ifndef OpenGLES}
959 glMultMatrix(Matrix);
960 {$endif}
961 end;
962 Shader.EnableTextureTransform(FirstTexUnit + I, Matrix);
963 end;
964 end;
965 end;
966 end else
967 { Check below is done because X3D specification explicitly
968 says that MultiTexture is affected *only* by MultiTextureTransform,
969 that is normal TextureTransform and such is ignored (treated
970 like identity transform, *not* applied to 1st texture unit).
971
972 By the way, we don't do any texture transform if Texture = nil,
973 since then no texture is used anyway.
974
975 TODO: what to do with CommonSurfaceShader ?
976
977 TODO: fix for new texture channels, where one TextureTransform
978 should work like MultiTextureTransform with one item. }
979 if (State.MainTexture <> nil) and
980 (not (State.MainTexture is TMultiTextureNode)) then
981 begin
982 if FirstTexUnit < GLFeatures.MaxTextureUnits then
983 begin
984 TextureTransformUnitsUsed := 1;
985 Matrix := TextureTransform.TransformMatrix;
986 if GLFeatures.EnableFixedFunction then
987 begin
988 {$ifndef OpenGLES}
989 ActiveTexture(FirstTexUnit);
990 glPushMatrix;
991 glMultMatrix(Matrix);
992 {$endif}
993 end;
994 Shader.EnableTextureTransform(FirstTexUnit, Matrix);
995 end;
996 end;
997 end;
998 end;
999
1000 {$ifndef OpenGLES}
1001 if GLFeatures.EnableFixedFunction then
1002 begin
1003 { restore GL_MODELVIEW }
1004 glMatrixMode(GL_MODELVIEW);
1005 end;
1006 {$endif}
1007 end;
1008
1009 RenderShapeClipPlanes(Shape, RenderOptions, Shader, Lighting);
1010
1011 if GLFeatures.EnableFixedFunction then
1012 begin
1013 {$ifndef OpenGLES}
1014 if (TextureTransformUnitsUsed <> 0) or
1015 (TextureTransformUnitsUsedMore.Count <> 0) then
1016 begin
1017 glMatrixMode(GL_TEXTURE);
1018
1019 for I := 0 to TextureTransformUnitsUsed - 1 do
1020 begin
1021 { This code is Ok also when not GLFeatures.UseMultiTexturing: then
1022 TextureTransformUnitsUsed for sure is <= 1 and ActiveTexture
1023 will be simply ignored. }
1024 ActiveTexture(FirstTexUnit + I);
1025 glPopMatrix;
1026 end;
1027
1028 for I := 0 to TextureTransformUnitsUsedMore.Count - 1 do
1029 begin
1030 ActiveTexture(TextureTransformUnitsUsedMore.L[I]);
1031 glPopMatrix;
1032 end;
1033
1034 { restore GL_MODELVIEW }
1035 glMatrixMode(GL_MODELVIEW);
1036 end;
1037 {$endif}
1038 end;
1039 end;
1040
1041 procedure TRenderer.RenderShapeClipPlanes(const Shape: TX3DRendererShape;
1042 const RenderOptions: TCastleRenderOptions;
1043 const Shader: TShader;
1044 const Lighting: boolean);
1045 var
1046 { How many clip planes were enabled (and so, how many must be disabled
1047 at the end). }
1048 ClipPlanesEnabled: Cardinal;
1049
1050 { Initialize OpenGL clip planes, looking at ClipPlanes list.
1051 We know we're inside GL_MODELVIEW mode,
1052 and we know all clip planes are currently disabled. }
1053 procedure ClipPlanesBegin(ClipPlanes: TClipPlaneList);
1054 var
1055 I: Integer;
1056 ClipPlane: PClipPlane;
1057 begin
1058 ClipPlanesEnabled := 0;
1059 { GLMaxClipPlanes should be >= 6 with every conforming OpenGL,
1060 but still better check. }
1061 if (GLFeatures.MaxClipPlanes > 0) and (ClipPlanes <> nil) then
1062 for I := 0 to ClipPlanes.Count - 1 do
1063 begin
1064 ClipPlane := PClipPlane(ClipPlanes.Ptr(I));
1065 if ClipPlane^.Node.FdEnabled.Value then
1066 begin
1067 Assert(ClipPlanesEnabled < GLFeatures.MaxClipPlanes);
1068 Shader.EnableClipPlane(ClipPlanesEnabled,
1069 PlaneTransform(ClipPlane^.Node.FdPlane.Value, ClipPlane^.Transform));
1070 Inc(ClipPlanesEnabled);
1071
1072 { No more clip planes possible, regardless if there are any more
1073 enabled clip planes on the list. }
1074 if ClipPlanesEnabled = GLFeatures.MaxClipPlanes then Break;
1075 end;
1076 end;
1077 end;
1078
1079 { Disable OpenGL clip planes previously initialized by ClipPlanesBegin. }
1080 procedure ClipPlanesEnd;
1081 var
1082 I: Integer;
1083 begin
1084 for I := 0 to Integer(ClipPlanesEnabled) - 1 do
1085 Shader.DisableClipPlane(I);
1086 ClipPlanesEnabled := 0; { not really needed, but for safety... }
1087 end;
1088
1089 begin
1090 { This must be done before "glMultMatrix(Shape.State.Transform)" below,
1091 as in case of fixed-function pipeline the ClipPlanesBegin
1092 causes glClipPlane that sets clip plane assuming the current matrix
1093 contains only camera. }
1094 ClipPlanesBegin(Shape.State.ClipPlanes);
1095
1096 {$ifndef OpenGLES}
1097 if GLFeatures.EnableFixedFunction then
1098 begin
1099 glPushMatrix;
1100 glMultMatrix(Shape.State.Transformation.Transform);
1101 end;
1102 {$endif}
1103
1104 RenderShapeCreateMeshRenderer(Shape, RenderOptions, Shader, Lighting);
1105
1106 {$ifndef OpenGLES}
1107 if GLFeatures.EnableFixedFunction then
1108 glPopMatrix;
1109 {$endif}
1110
1111 ClipPlanesEnd;
1112 end;
1113
1114 procedure TRenderer.RenderShapeCreateMeshRenderer(const Shape: TX3DRendererShape;
1115 const RenderOptions: TCastleRenderOptions;
1116 const Shader: TShader; const Lighting: boolean);
1117 var
1118 GeneratorClass: TArraysGeneratorClass;
1119 MeshRenderer: TMeshRenderer;
1120
1121 { If Shape.Geometry should be rendered using one of TMeshRenderer
1122 classes, then create appropriate MeshRenderer and return @true.
1123 Otherwise return @false and doesn't set MeshRenderer.
1124
1125 Takes care of initializing MeshRenderer, so you have to call only
1126 MeshRenderer.Render. }
1127 function InitMeshRenderer: boolean;
1128 begin
1129 GeneratorClass := GetArraysGenerator(Shape.Geometry);
1130 Result := GeneratorClass <> nil;
1131 if Result then
1132 begin
1133 { If we have GeneratorClass, create TCompleteCoordinateRenderer.
1134 We'll initialize TCompleteCoordinateRenderer.Arrays later. }
1135 MeshRenderer := TCompleteCoordinateRenderer.Create(Self, Shape);
1136 MeshRenderer.ShapeModelView :=
1137 Shader.SceneModelView * Shape.State.Transformation.Transform;
1138 MeshRenderer.RenderOptions := RenderOptions;
1139 Shape.BumpMappingAllowed := GeneratorClass.BumpMappingAllowed;
1140 end;
1141 end;
1142
1143 begin
1144 { default Shape.BumpMapping* state }
1145 Shape.BumpMappingAllowed := false;
1146 Shape.BumpMappingUsed := false;
1147
1148 { Initalize MeshRenderer to something non-nil. }
1149 if not InitMeshRenderer then
1150 begin
1151 WritelnWarning('VRML/X3D', Format('Rendering of node kind "%s" not implemented',
1152 [Shape.NiceName]));
1153 Exit;
1154 end;
1155
1156 Assert(MeshRenderer <> nil);
1157
1158 try
1159 RenderShapeShaders(Shape, RenderOptions, Shader, Lighting,
1160 GeneratorClass, MeshRenderer);
1161 finally
1162 FreeAndNil(MeshRenderer);
1163 end;
1164 end;
1165
1166 procedure TRenderer.RenderShapeShaders(const Shape: TX3DRendererShape;
1167 const RenderOptions: TCastleRenderOptions;
1168 const Shader: TShader;
1169 const Lighting: boolean;
1170 const GeneratorClass: TArraysGeneratorClass;
1171 const ExposedMeshRenderer: TObject);
1172 var
1173 { > 0 means that we had custom shader node *and* it already
1174 needs given number texture units. Always 0 otherwise. }
1175 UsedGLSLTexCoordsNeeded: Cardinal;
1176
1177 function TextureCoordsDefined: Cardinal;
1178 var
1179 TexCoord: TX3DNode;
1180 begin
1181 if Shape.Geometry.InternalTexCoord(Shape.State, TexCoord) and
1182 (TexCoord <> nil) then
1183 begin
1184 if TexCoord is TMultiTextureCoordinateNode then
1185 Result := TMultiTextureCoordinateNode(TexCoord).FdTexCoord.Count else
1186 Result := 1;
1187 end else
1188 Result := 0;
1189 end;
1190
1191 function TextureUnitsDefined(Node: TComposedShaderNode): Cardinal;
1192
1193 function TextureUnits(Node: TX3DNode): Cardinal;
1194 begin
1195 if Node is TMultiTextureNode then
1196 Result := TMultiTextureNode(Node).FdTexture.Count else
1197 if Node is TAbstractTextureNode then
1198 Result := 1 else
1199 Result := 0;
1200 end;
1201
1202 var
1203 I, J: Integer;
1204 UniformField: TX3DField;
1205 IDecls: TX3DInterfaceDeclarationList;
1206 begin
1207 IDecls := Node.InterfaceDeclarations;
1208 Result := 0;
1209 Assert(IDecls <> nil);
1210 for I := 0 to IDecls.Count - 1 do
1211 begin
1212 UniformField := IDecls[I].Field;
1213
1214 if UniformField <> nil then
1215 begin
1216 if UniformField is TSFNode then
1217 Result := Result + TextureUnits(TSFNode(UniformField).Value) else
1218 if UniformField is TMFNode then
1219 for J := 0 to TMFNode(UniformField).Count - 1 do
1220 Result := Result + TextureUnits(TMFNode(UniformField)[J]);
1221 end;
1222 end;
1223
1224 if Shape.OriginalGeometry.FontTextureNode <> nil then
1225 Inc(Result);
1226 end;
1227
1228 var
1229 TCD: Cardinal;
1230 UsedShaderNode: TComposedShaderNode;
1231 begin
1232 { Use custom shader code (ComposedShader) if available. }
1233
1234 UsedGLSLTexCoordsNeeded := 0;
1235
1236 if (Shape.Node <> nil) and
1237 (Shape.Node.Appearance <> nil) and
1238 Shader.EnableCustomShaderCode(Shape.Node.Appearance.FdShaders, UsedShaderNode) then
1239 begin
1240 UsedGLSLTexCoordsNeeded := TextureUnitsDefined(UsedShaderNode);
1241
1242 { Only if we bound texture units defined in shader ComposedShader fields
1243 (it we have shader but UsedGLSLTexCoordsNeeded = 0 then normal
1244 texture apply (including normal TexCoordsNeeded calculation)
1245 will be done):
1246
1247 Although we bound only UsedGLSLTexCoordsNeeded texture units,
1248 we want to pass all texture coords defined in texCoord.
1249 Shaders may use them (even when textures are not bound for them). }
1250
1251 if UsedGLSLTexCoordsNeeded > 0 then
1252 begin
1253 TCD := TextureCoordsDefined;
1254 if TCD > UsedGLSLTexCoordsNeeded then
1255 WritelnLog('TexCoord', Format('Texture coords defined in VRML/X3D for %d texture units, using them all, even though we bound only %d texture units. Reason: GLSL shaders may use them',
1256 [TCD, UsedGLSLTexCoordsNeeded]));
1257 MaxVar(UsedGLSLTexCoordsNeeded, TCD);
1258 end;
1259 end;
1260
1261 RenderShapeTextures(Shape, RenderOptions, Shader, Lighting,
1262 GeneratorClass, TMeshRenderer(ExposedMeshRenderer), UsedGLSLTexCoordsNeeded);
1263 end;
1264
1265 procedure TRenderer.RenderShapeTextures(const Shape: TX3DRendererShape;
1266 const RenderOptions: TCastleRenderOptions;
1267 const Shader: TShader;
1268 const Lighting: boolean;
1269 const GeneratorClass: TArraysGeneratorClass;
1270 const ExposedMeshRenderer: TObject;
1271 const UsedGLSLTexCoordsNeeded: Cardinal);
1272
1273 function NodeTextured(Node: TAbstractGeometryNode): boolean;
1274 begin
1275 Result := not (
1276 (Node is TPointSetNode) or
1277 (Node is TIndexedLineSetNode));
1278 end;
1279
1280 procedure EnableShadowMaps(const ShadowMaps: TX3DNodeList;
1281 var ABoundTextureUnits: Cardinal; const Shader: TShader);
1282 var
1283 ShadowMapNode: TGeneratedShadowMapNode;
1284 Res: TTextureResource;
1285 I: Integer;
1286 begin
1287 for I := 0 to ShadowMaps.Count - 1 do
1288 begin
1289 Assert(ShadowMaps[I] is TGeneratedShadowMapNode);
1290 ShadowMapNode := TGeneratedShadowMapNode(ShadowMaps[I]);
1291
1292 // get TTextureResource instance
1293 Res := TTextureResources.Get(ShadowMapNode);
1294 if Res = nil then
1295 begin
1296 WritelnWarning('Shadow Map', 'Shadow map "%s" has no renderer texture resource, cannot use it', [
1297 ShadowMapNode.NiceName
1298 ]);
1299 Continue;
1300 end;
1301
1302 // bind the texture to the next free texture unit
1303 Res.Bind(ABoundTextureUnits);
1304
1305 Shader.EnableShadowMap(ABoundTextureUnits, ShadowMapNode);
1306 Inc(ABoundTextureUnits); // we used one more texture unit
1307 end;
1308 end;
1309
1310 function GetAlphaCutoff(const Shape: TShape): Single;
1311 begin
1312 if (Shape.Node <> nil) and
1313 (Shape.Node.Appearance <> nil) then
1314 Result := Shape.Node.Appearance.AlphaCutoff
1315 else
1316 Result := DefaultAlphaCutoff;
1317 end;
1318
1319 procedure RenderTexturesBegin;
1320 var
1321 TextureNode: TAbstractTextureNode;
1322 TextureRes: TTextureResource;
1323 AlphaTest: Boolean;
1324 AlphaCutoff: Single;
1325 FontTextureNode: TAbstractTexture2DNode;
1326 FontTextureRes: TTextureResource;
1327 MainTextureMapping: Integer;
1328 begin
1329 TexCoordsNeeded := 0;
1330 BoundTextureUnits := 0;
1331
1332 if RenderOptions.Mode = rmSolidColor then
1333 begin
1334 { Make sure each shape sets fixed-function alpha test,
1335 regardless of RenderOptions.Mode (code for other RenderOptions.Mode values
1336 is lower in this routine), otherwise it is undefined. }
1337 RenderContext.FixedFunctionAlphaTestDisable;
1338 Exit;
1339 end;
1340
1341 AlphaTest := false;
1342
1343 TextureNode := Shape.State.MainTexture(Shape.Geometry, MainTextureMapping);
1344 TextureRes := TTextureResources.Get(TextureNode);
1345 { assert we never have non-nil TextureRes and nil TextureNode }
1346 Assert((TextureRes = nil) or (TextureNode <> nil));
1347
1348 Shader.MainTextureMapping := MainTextureMapping;
1349
1350 FontTextureNode := Shape.OriginalGeometry.FontTextureNode;
1351 FontTextureRes := TTextureResources.Get(FontTextureNode);
1352 { assert we never have non-nil FontTextureRes and nil FontTextureNode }
1353 Assert((FontTextureRes = nil) or (FontTextureNode <> nil));
1354
1355 if UsedGLSLTexCoordsNeeded > 0 then
1356 begin
1357 { Do not bind/enable normal textures. Just set TexCoordsNeeded
1358 to generate tex coords for textures used in the shader.
1359 Leave BoundTextureUnits at 0 (BoundTextureUnits will be increased
1360 later when shader actually binds texture uniform values). }
1361 TexCoordsNeeded := UsedGLSLTexCoordsNeeded;
1362 end else
1363 if RenderOptions.Textures and
1364 NodeTextured(Shape.Geometry) then
1365 begin
1366 AlphaTest := TGLShape(Shape).AlphaChannel = acTest;
1367
1368 if FontTextureRes <> nil then
1369 FontTextureRes.EnableAll(Self, GLFeatures.MaxTextureUnits, TexCoordsNeeded, Shader,
1370 false);
1371 if TextureRes <> nil then
1372 TextureRes.EnableAll(Self, GLFeatures.MaxTextureUnits, TexCoordsNeeded, Shader,
1373 FontTextureRes <> nil);
1374 BoundTextureUnits := TexCoordsNeeded;
1375
1376 if Shape.InternalShadowMaps <> nil then
1377 EnableShadowMaps(Shape.InternalShadowMaps, BoundTextureUnits, Shader);
1378
1379 { If there is special texture like a normalmap, enable it. }
1380 BumpMappingEnable(Shape, RenderOptions, BoundTextureUnits, TexCoordsNeeded, Shader);
1381 SurfaceTexturesEnable(Shape, BoundTextureUnits, TexCoordsNeeded, Shader);
1382 end;
1383
1384 { Set alpha test state (shader and fixed-function) }
1385 if AlphaTest then
1386 begin
1387 { only calculate AlphaCutoff when AlphaTest, otherwise it is useless }
1388 AlphaCutoff := GetAlphaCutoff(Shape);
1389 RenderContext.FixedFunctionAlphaTestEnable(AlphaCutoff);
1390 Shader.EnableAlphaTest(AlphaCutoff);
1391 end else
1392 RenderContext.FixedFunctionAlphaTestDisable;
1393
1394 { Make active texture 0. This is helpful for rendering code of
1395 some primitives that do not support multitexturing now
1396 (inside vrmlmeshrenderer_x3d_text.inc),
1397 this way they will at least define correct texture coordinates
1398 for texture unit 0. }
1399
1400 if (TexCoordsNeeded > 0) and GLFeatures.UseMultiTexturing then
1401 ActiveTexture(0);
1402 end;
1403
1404 procedure RenderTexturesEnd;
1405 var
1406 I: Integer;
1407 begin
1408 for I := 0 to Integer(TexCoordsNeeded) - 1 do
1409 DisableTexture(I);
1410 end;
1411
1412 begin
1413 RenderTexturesBegin;
1414 try
1415 RenderShapeInside(Shape, RenderOptions, Shader, Lighting, GeneratorClass,
1416 TMeshRenderer(ExposedMeshRenderer));
1417 finally RenderTexturesEnd end;
1418 end;
1419
1420 procedure TRenderer.RenderShapeInside(const Shape: TX3DRendererShape;
1421 const RenderOptions: TCastleRenderOptions;
1422 const Shader: TShader;
1423 const Lighting: boolean;
1424 const GeneratorClass: TArraysGeneratorClass;
1425 const ExposedMeshRenderer: TObject);
1426
1427 procedure SetupShadowMapsGenerationShaders(const MeshRenderer: TMeshRenderer);
1428 begin
1429 case RenderingCamera.Target of
1430 rtVarianceShadowMap:
1431 begin
1432 if VarianceShadowMapsShaders = nil then
1433 VarianceShadowMapsShaders := TCustomShaders.Create(
1434 '#define VARIANCE_SHADOW_MAPS' + NL + {$I shadow_map_generate.vs.inc},
1435 '#define VARIANCE_SHADOW_MAPS' + NL + {$I shadow_map_generate.fs.inc});
1436 MeshRenderer.CustomShaders := VarianceShadowMapsShaders;
1437 end;
1438 rtShadowMap:
1439 begin
1440 if ShadowMapsShaders = nil then
1441 ShadowMapsShaders := TCustomShaders.Create(
1442 {$I shadow_map_generate.vs.inc},
1443 {$I shadow_map_generate.fs.inc});
1444 MeshRenderer.CustomShaders := ShadowMapsShaders;
1445 end;
1446 else
1447 begin
1448 MeshRenderer.CustomShaders := nil;
1449 end;
1450 end;
1451 end;
1452
1453 var
1454 Generator: TArraysGenerator;
1455 CoordinateRenderer: TBaseCoordinateRenderer;
1456 begin
1457 { No point preparing VBO for clones, clones will need own VBOs anyway. }
1458 if RenderMode = rmPrepareRenderClones then
1459 Exit;
1460
1461 { initialize TBaseCoordinateRenderer.Arrays now }
1462 if GeneratorClass <> nil then
1463 begin
1464 Assert(TMeshRenderer(ExposedMeshRenderer) is TBaseCoordinateRenderer);
1465 CoordinateRenderer := TBaseCoordinateRenderer(ExposedMeshRenderer);
1466
1467 { calculate Shape.Cache }
1468 if Shape.Cache = nil then
1469 Shape.Cache := RendererCache.Shape_IncReference(Shape, RenderOptions);
1470
1471 { calculate Shape.Cache.Arrays }
1472 if (Shape.Cache.Arrays = nil) or
1473 (Shape.Cache.VboToReload <> []) then
1474 begin
1475 if not FastUpdateArrays(Shape) then
1476 begin
1477 FreeAndNil(Shape.Cache.Arrays); // we just need to create new Arrays
1478 Generator := GeneratorClass.Create(Shape);
1479 try
1480 Generator.TexCoordsNeeded := TexCoordsNeeded;
1481 Generator.FogVolumetric := FogVolumetric;
1482 Generator.FogVolumetricDirection := FogVolumetricDirection;
1483 Generator.FogVolumetricVisibilityStart := FogVolumetricVisibilityStart;
1484 Generator.ShapeBumpMappingUsed := Shape.BumpMappingUsed;
1485 Generator.ShapeBumpMappingTextureCoordinatesId := Shape.BumpMappingTextureCoordinatesId;
1486 Shape.Cache.Arrays := Generator.GenerateArrays;
1487 finally FreeAndNil(Generator) end;
1488
1489 { Always after recreating Shape.Cache.Arrays, reload Shape.Cache.Vbo contents.
1490 This also clears VboToReload. }
1491 Shape.LoadArraysToVbo;
1492 end;
1493 end;
1494
1495 if GLFeatures.VertexBufferObject then
1496 begin
1497 { Shape.Arrays contents are already loaded,
1498 so Vbo contents are already loaded too }
1499 Assert(Shape.Cache.Vbo[vtCoordinate] <> 0);
1500 CoordinateRenderer.Vbo := Shape.Cache.Vbo;
1501 CoordinateRenderer.Vao := Shape.Cache.Vao;
1502 end;
1503
1504 CoordinateRenderer.Arrays := Shape.Cache.Arrays;
1505 CoordinateRenderer.Shader := Shader;
1506 CoordinateRenderer.BoundTextureUnits := BoundTextureUnits;
1507 CoordinateRenderer.Lighting := Lighting;
1508 end;
1509
1510 SetupShadowMapsGenerationShaders(TMeshRenderer(ExposedMeshRenderer));
1511
1512 TMeshRenderer(ExposedMeshRenderer).PrepareRenderShape := RenderMode in [rmPrepareRenderSelf, rmPrepareRenderClones];
1513 TMeshRenderer(ExposedMeshRenderer).Render;
1514
1515 if (GeneratorClass <> nil) and GLFeatures.VertexBufferObject then
1516 begin
1517 { unbind arrays, to have a clean state on exit.
1518 TODO: this should not be needed, instead move to RenderEnd.
1519 Check does occlusion query work Ok when some vbo is bound. }
1520 RenderContext.BindBuffer[btArray] := 0;
1521 RenderContext.BindBuffer[btElementArray] := 0;
1522 end;
1523 end;
1524
1525 {$ifndef OpenGLES}
1526 procedure TRenderer.PushTextureUnit(const TexUnit: Cardinal);
1527 begin
1528 { Only continue if texture unit is not already pushed
1529 (otherwise glPushMatrix would not be paired by exactly one glPopMatrix
1530 later). }
1531
1532 if (TexUnit >= TextureTransformUnitsUsed) and
1533 (TextureTransformUnitsUsedMore.IndexOf(TexUnit) = -1) then
1534 begin
1535 if GLFeatures.EnableFixedFunction then
1536 glPushMatrix;
1537
1538 { Simple implementation would just add always TexUnit
1539 to TextureTransformUnitsUsedMore. But there are optimizations possible,
1540 knowing that TextureTransformUnitsUsed already takes care of many units,
1541 and TextureTransformUnitsUsed can only be increased (by this
1542 very method...) in RenderShape.
1543
1544 If texture unit is = TextureTransformUnitsUsed, this can be taken care
1545 of easily, just increase TextureTransformUnitsUsed. (This is an often
1546 case, as it happens when no texture transform was explicitly defined
1547 in VRML file, and only one texture unit using WORLDSPACEREFLECTIONVECTOR
1548 is defined; this is the most common case when using cube env mapping
1549 with WORLDSPACEREFLECTIONVECTOR.)
1550
1551 Otherwise, we know (from previous checks) that
1552 TexUnit > TextureTransformUnitsUsed and it's not mentioned in
1553 TextureTransformUnitsUsedMore. So add it there. }
1554
1555 if TexUnit = TextureTransformUnitsUsed then
1556 Inc(TextureTransformUnitsUsed) else
1557 TextureTransformUnitsUsedMore.Add(TexUnit);
1558 end;
1559 end;
1560 {$endif}
1561
1562 procedure TRenderer.UpdatePass;
1563
1564 { Combine a set of numbers (each in their own range) into one unique number.
1565 This is like combining a couple of digits into a whole number,
1566 but each digit is in a separate numeric system.
1567
1568 This is used to calculate TTotalRenderingPass from a couple of numbers.
1569 The goal is that changing *any* number must also change the result,
1570 so that result is a unique representation of all the numbers. }
1571 function GetTotalPass(
1572 const Digits: array of Cardinal;
1573 const Ranges: array of Cardinal): Cardinal;
1574 var
1575 I: Integer;
1576 Multiplier: Cardinal;
1577 begin
1578 Result := 0;
1579 Multiplier := 1;
1580 Assert(Length(Digits) = Length(Ranges));
1581 for I := 0 to Length(Digits) - 1 do
1582 begin
1583 Result := Result + Digits[I] * Multiplier;
1584 Multiplier := Multiplier * Ranges[I];
1585 end;
1586 end;
1587
1588 begin
1589 FPass := GetTotalPass(
1590 [ FInternalPass, FWireframePass, FUserPass ],
1591 [High(FInternalPass), High(FWireframePass), High(FUserPass)]);
1592 end;
1593
1594 procedure TRenderer.SetWireframePass(const Value: TWireframeRenderingPass);
1595 begin
1596 if FWireframePass <> Value then
1597 begin
1598 FWireframePass := Value;
1599 UpdatePass;
1600 end;
1601 end;
1602
1603 {$endif}