Debian Codegraph @

src/base_rendering/castlerendercontext.pas

raw
1 {
2 Copyright 2001-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 { Rendering context state. }
17 unit CastleRenderContext;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Generics.Collections, Classes,
24 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
25 CastleUtils, CastleVectors, CastleRectangles, CastleGLShaders, CastleColors,
26 CastleRenderOptions, CastleGLUtils;
27
28 type
29 TClearBuffer = (cbColor, cbDepth, cbStencil);
30
31 TClearBuffers = set of TClearBuffer;
32
33 { Scissor to clip displayed things, in addition to the global scissor
34 affected by TRenderContext.ScissorEnable / TRenderContext.ScissorDisable.
35 Always disable an enabled scissor (destructor does it automatically).
36
37 Make sure to enable and disable the scissor when the same OpenGL context
38 is current. In practice, the only reliable way to do this is to enable
39 and then disable the scissor within the same OnRender event. }
40 TScissor = class
41 strict private
42 FEnabled: boolean;
43 procedure SetEnabled(const Value: boolean);
44 public
45 { Rectangle to which we clip rendering. Empty by default (will clip everything,
46 if you don't assign this!). Do not change this when scissor is enabled. }
47 Rect: TRectangle;
48 constructor Create;
49 destructor Destroy; override;
50 property Enabled: boolean read FEnabled write SetEnabled;
51 end;
52
53 { Possible values of @link(TRenderContext.DepthFunc).
54 Note: For now, the values of this enum correspond to OpenGL(ES) constants,
55 but do not depend on this outside (and it may change in the future).
56 Treat it like opaque enum. }
57 TDepthFunction = (
58 dfNever = $0200,
59 dfLess = $0201,
60 dfEqual = $0202,
61 dfLessEqual = $0203,
62 dfGreater = $0204,
63 dfNotEqual = $0205,
64 dfGreaterEqual = $0206,
65 dfAlways = $0207
66 );
67
68 TPolygonOffset = record
69 Enabled: Boolean;
70 Scale, Bias: Single;
71 end;
72
73 { Target of bound buffer, see https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBindBuffer.xhtml . }
74 TBufferTarget = (
75 { Vertex attributes. }
76 btArray,
77 { Indexes. }
78 btElementArray
79 );
80
81 { The OpenGL / OpenGLES context state.
82 We try hard to make this a @bold(very, very) small class,
83 because usually it's better to introduce a clean higher-level API
84 than to track the OpenGL context state in a simple global @link(RenderContext)
85 instance.
86
87 Use the methods and properties of this class
88 only when this context is @italic(current),
89 which means it's set as @link(RenderContext) value.
90
91 Do not depend on the context state being persistent.
92 The @link(RenderContext) does not change during a single TCastleUserInterface.OnRender
93 method (with all 2D and 3D stuff rendered inside),
94 but that's all we guarantee. On desktops, you control the context
95 creation / destruction explicitly (by opening / closing the TCastleWindow).
96 But on mobile devices -- the context may get destroyed and created at almost
97 any moment. So do not use the instance of @link(RenderContext) to store
98 anything you rely on being stored. Instead, use your own variables for this,
99 and only synchronize @link(RenderContext) with your variables.
100 }
101 TRenderContext = class(TComponent)
102 strict private
103 type
104 TScissorList = class({$ifdef FPC}specialize{$endif} TObjectList<TScissor>)
105 public
106 FFinalScissor: TRectangle; // only defined when Count <> 0
107 procedure Update;
108 end;
109 var
110 FClearColor: TCastleColor;
111 FLineWidth, FPointSize: Single;
112 FGlobalAmbient: TCastleColorRGB;
113 FGlobalScissor: TScissor;
114 FProjectionMatrix: TMatrix4;
115 FDepthRange: TDepthRange;
116 FCullFace, FFrontFaceCcw: boolean;
117 FDepthTest: Boolean;
118 FDepthFunc: TDepthFunction;
119 FColorChannels: TColorChannels;
120 FDepthBufferUpdate: Boolean;
121 FViewport: TRectangle;
122 FViewportDelta: TVector2Integer;
123 WarningViewportTooLargeDone: Boolean;
124 FCurrentProgram: TGLSLProgram;
125 FCurrentVao: TVertexArrayObject;
126 FBlendingSourceFactor: TBlendingSourceFactor;
127 FBlendingDestinationFactor: TBlendingDestinationFactor;
128 FBlendingEnabled: Boolean;
129 FFixedFunctionAlphaTest: Boolean;
130 FFixedFunctionAlphaCutoff: Single;
131 FFixedFunctionLighting: boolean;
132 FLineType: TLineType;
133 FPolygonOffset: TPolygonOffset;
134 FBoundBuffer: array [TBufferTarget] of TGLuint;
135
136 procedure SetLineWidth(const Value: Single);
137 procedure SetPointSize(const Value: Single);
138 procedure SetGlobalAmbient(const Value: TCastleColorRGB);
139 procedure WarnContextNotCurrent;
140 procedure SetProjectionMatrix(const Value: TMatrix4);
141 procedure SetDepthRange(const Value: TDepthRange);
142 procedure SetCullFace(const Value: boolean);
143 procedure SetFrontFaceCcw(const Value: boolean);
144 procedure SetDepthTest(const Value: Boolean);
145 procedure SetDepthFunc(const Value: TDepthFunction);
146 function GetColorMask: boolean;
147 procedure SetColorMask(const Value: boolean);
148 procedure SetColorChannels(const Value: TColorChannels);
149 procedure SetDepthBufferUpdate(const Value: boolean);
150 procedure SetViewport(const Value: TRectangle);
151 procedure SetViewportDelta(const Value: TVector2Integer);
152 procedure UpdateViewport;
153 procedure WarningViewportTooLarge;
154 procedure SetCurrentProgram(const Value: TGLSLProgram);
155 procedure SetCurrentVao(const Value: TVertexArrayObject);
156 procedure SetFixedFunctionLighting(const Value: boolean);
157 procedure SetLineType(const Value: TLineType);
158 procedure SetPolygonOffset(const Value: TPolygonOffset);
159 function GetBoundBuffer(const Target: TBufferTarget): TGLuint;
160 procedure SetBoundBuffer(const Target: TBufferTarget; const Value: TGLuint);
161 private
162 FEnabledScissors: TScissorList;
163 public
164 { If @true, @link(Clear) will clear color buffer by DrawRectangle instead
165 of OpenGL glClear call.
166 This is a bit slower, but makes it honor the stencil test. }
167 InternalClearColorsByDraw: Boolean;
168
169 constructor Create(AOwner: TComponent); override;
170 destructor Destroy; override;
171
172 { Clear the whole buffer contents.
173
174 Never call OpenGL glClear or glClearColor, always use this method. }
175 procedure Clear(Buffers: TClearBuffers; const ClearColor: TCastleColor);
176
177 { The rendered line width.
178 Never call OpenGL glLineWidth directly.
179
180 Do not access this property directly, unless you make direct
181 OpenGL/OpenGLES calls. In normal circumstances, engine API
182 (like DrawPrimitive2D or TCastleScene) set this automatically. }
183 property LineWidth: Single read FLineWidth write SetLineWidth {$ifdef FPC}default 1{$endif};
184
185 { The rendered point size.
186 Never call OpenGL glPointSize directly.
187
188 Do not access this property directly, unless you make direct
189 OpenGL/OpenGLES calls. In normal circumstances, engine API
190 (like DrawPrimitive2D or TCastleScene) set this automatically. }
191 property PointSize: Single read FPointSize write SetPointSize {$ifdef FPC}default 1{$endif};
192
193 { Global ambient lighting. This is added to every 3D object color,
194 multiplied by material ambient.
195
196 The default value is (0.2, 0.2, 0.2). It matches default
197 GL_LIGHT_MODEL_AMBIENT in fixed-function OpenGL.
198 It also matches the required value of VRML 1.0 specification.
199 For VRML 2.0 / X3D, lighting equations suggest that it should be zero. }
200 property GlobalAmbient: TCastleColorRGB read FGlobalAmbient write SetGlobalAmbient;
201
202 { Enable or disable scissor.
203
204 Never call OpenGL glScissor or glEnable(GL_SCISSOR_TEST) / glDisable(GL_SCISSOR_TEST)
205 directly, or push/pop the related attrib (in case of fixed-function pipeline).
206 @groupBegin }
207 procedure ScissorEnable(const Rect: TRectangle);
208 procedure ScissorDisable;
209 { @groupEnd }
210
211 { Current projection matrix.
212
213 When GLFeatures.EnableFixedFunction = true, setting this also
214 sets fixed-function projection matrix. }
215 property ProjectionMatrix: TMatrix4
216 read FProjectionMatrix write SetProjectionMatrix;
217
218 { Use this to operate on OpenGL glDepthRange. For now, our engine has
219 very simple use for this, for TPlayer.RenderOnTop. }
220 property DepthRange: TDepthRange read FDepthRange write SetDepthRange;
221
222 { Should we use backface-culling (ignore some faces during rendering). }
223 property CullFace: boolean read FCullFace write SetCullFace
224 default false;
225
226 { Is the front face ordered counter-clockwise.
227 The "front face" is important to interpreting the @link(CullFace)
228 and to interpret the normal vectors (they point outward from front face). }
229 property FrontFaceCcw: boolean read FFrontFaceCcw write SetFrontFaceCcw
230 default true;
231
232 { Depth testing means we reject things that don't pass @link(DepthFunc). }
233 property DepthTest: Boolean read FDepthTest write SetDepthTest default false;
234
235 { Function to use when comparing depth, only if @link(DepthTest). }
236 property DepthFunc: TDepthFunction read FDepthFunc write SetDepthFunc default dfLess;
237
238 {$ifdef FPC}
239 { Are color buffer channels changed by rendering. }
240 property ColorMask: boolean
241 read GetColorMask write SetColorMask default true;
242 deprecated 'use ColorChannels';
243 {$endif}
244
245 { Which color buffer channels are written by rendering.
246 This affects all rendering, including @link(TDrawableImage.Draw).
247
248 Note that this state may be internally modified by various engine rendering
249 functions too, e.g. by @link(TCastleScene.LocalRender), depending on rendering
250 attributes.
251 So it is only reliable for you to modify this temporarily,
252 and during your own rendering.
253 E.g. change ColorChannels right before and right after calling a couple of
254 @link(TDrawableImage.Draw). Always restore it afterwards to default [0..3].
255
256 Example uses:
257
258 @unorderedList(
259 @item(
260 Set this to ccNone to temporarily turn off writing to the color buffer.
261 This is useful e.g. if you only want to write
262 to the delph and stencil buffer.)
263 @item(
264 Set this to [0..2] to temporarily turn off writing to the alpha channel,
265 or to [3] to temporarily turn off writing to the RGB channels.)
266 @item(
267 Set this [0..3] to go back to default (write all channels).)
268 )
269 }
270 property ColorChannels: TColorChannels
271 read FColorChannels write SetColorChannels default AllColorChannels;
272
273 { Is depth buffer updated by rendering.
274 This affects all rendering that enables depth testing
275 (which in practice means only TCastleScene in CGE). }
276 property DepthBufferUpdate: Boolean
277 read FDepthBufferUpdate write SetDepthBufferUpdate default true;
278
279 { Controls OpenGL viewport. This is always shifted by ViewportDelta. }
280 property Viewport: TRectangle read FViewport write SetViewport;
281
282 { Shifts the rectangle passed to @link(Viewport).
283 Only the @link(TCastleScreenEffects) should control this. }
284 property ViewportDelta: TVector2Integer read FViewportDelta write SetViewportDelta;
285
286 { Scissor rectangle to which we clip the view.
287 This is determined by all @link(TScissor) that are currently enabled.
288 Returns @true and sets Rect if any scissor is active.
289 Returns @false if we don't clip the view now. }
290 function FinalScissor(out Rect: TRectangle): Boolean;
291
292 { Currently enabled GLSL program.
293 @nil if none (rendering is not possible, unless ancient fixed-function pipeline is used).
294 Setting this property encapsulates the OpenGL glUseProgram. }
295 property CurrentProgram: TGLSLProgram read FCurrentProgram write SetCurrentProgram;
296
297 { Currently bound vertex array object.
298 @nil if none.. }
299 property CurrentVao: TVertexArrayObject read FCurrentVao write SetCurrentVao;
300
301 { Does the current color buffer have any alpha channel.
302 Some blending features depend on storing alpha in the color channel. }
303 function ColorBufferHasAlpha: Boolean; deprecated 'use GLFeatures.AlphaBits > 0';
304
305 { Enable blending, sets also blending function.
306 See https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBlendFunc.xhtml
307 for blending equations.
308 You @italic(must) use this to change blending parameters, this class
309 assumes it knows the blending state always. }
310 procedure BlendingEnable(
311 const SourceFactor: TBlendingSourceFactor = bsSrcAlpha;
312 const DestinationFactor: TBlendingDestinationFactor = bdOneMinusSrcAlpha);
313 procedure BlendingDisable;
314
315 { Enable alpha test with old/buggy OpenGL implementations that use deprecated fixed-function pipeline.
316 This is simply ignored on modern GPUs when "not GLFeatures.EnableFixedFunction". }
317 procedure FixedFunctionAlphaTestEnable(const AlphaCutoff: Single = 0.5);
318 procedure FixedFunctionAlphaTestDisable;
319
320 { Fixed-function GL_LIGHTING state.
321 This is simply ignored on modern GPUs when "not GLFeatures.EnableFixedFunction". }
322 property FixedFunctionLighting: boolean read FFixedFunctionLighting write SetFixedFunctionLighting;
323
324 { Line type determines OpenGL glLineStipple, GL_LINE_STIPPLE enable state.
325 Note: This is not supported on OpenGLES. }
326 property LineType: TLineType read FLineType write SetLineType;
327
328 { Current polygon offset state. You can read and write it. }
329 property PolygonOffset: TPolygonOffset read FPolygonOffset write SetPolygonOffset;
330 { Shortcut for setting @link(PolygonOffset) with PolygonOffset.Enabled = @true. }
331 procedure PolygonOffsetEnable(const Scale, Bias: Single);
332 { Shortcut for setting @link(PolygonOffset) with PolygonOffset.Enabled = @false. }
333 procedure PolygonOffsetDisable;
334
335 { Bind buffer to target, just like glBindBuffer.
336
337 Optimized to do nothing if given buffer is already bound.
338 This optimization actually matters for optimization (Android Samsung Galaxy Tab,
339 castle-model-viewer-mobile displaying inspector).
340 Without it, TDrawableImage does a lot of redundant glBindBuffer calls. }
341 property BindBuffer[const Target: TBufferTarget]: TGLuint
342 read GetBoundBuffer write SetBoundBuffer;
343 end;
344
345 var
346 { Current OpenGL / OpenGLES context state.
347 @bold(Only access it during the rendering, i.e. in TCastleUserInterface.Render.)
348
349 TODO: In the future, this global singleton may be removed,
350 and this may be accessible instead through a new TCastleUserInterface.Render parameter. }
351 RenderContext: TRenderContext;
352
353 { Projection matrix -------------------------------------------------------- } { }
354
355 { Calculate projection matrix, and set
356 @link(TRenderContext.ProjectionMatrix RenderContext.ProjectionMatrix)
357 to given value.
358
359 For PerspectiveProjection, ZFar may have special ZFarInfinity value
360 to create a perspective projection with far plane set at infinity.
361 Useful e.g. for z-fail shadow volumes.
362
363 @groupBegin }
364 function PerspectiveProjection(const fovy, aspect, ZNear, ZFar: Single): TMatrix4;
365 function OrthoProjection(const Dimensions: TFloatRectangle;
366 const ZNear: Single = -1; const ZFar: Single = 1): TMatrix4;
367 function FrustumProjection(const Dimensions: TFloatRectangle; const ZNear, ZFar: Single): TMatrix4;
368 { @groupEnd }
369
370 const
371 BufferTargetGL: array [TBufferTarget] of TGLenum = (
372 GL_ARRAY_BUFFER,
373 GL_ELEMENT_ARRAY_BUFFER
374 );
375
376 implementation
377
378 uses CastleLog, CastleProjection, CastleInternalGLUtils, CastleGLImages;
379
380 constructor TRenderContext.Create(AOwner: TComponent);
381 begin
382 inherited;
383 FLineWidth := 1;
384 FPointSize := 1;
385 FGlobalAmbient := Vector3(0.2, 0.2, 0.2);
386 FEnabledScissors := TScissorList.Create(false);
387 FProjectionMatrix := TMatrix4.Identity;
388 FDepthRange := drFull;
389 FCullFace := false;
390 FFrontFaceCcw := true;
391 FColorChannels := AllColorChannels;
392 FDepthBufferUpdate := true;
393 FDepthTest := false;
394 FDepthFunc := dfLess;
395 FViewport := TRectangle.Empty;
396 FBlendingEnabled := false;
397 // initial blending factors, see https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBlendFunc.xhtml
398 FBlendingSourceFactor := bsOne;
399 FBlendingDestinationFactor := bdZero;
400 { the initial glAlphaFunc state is (GL_ALWAYS, 0), see https://docs.gl/gl3/glAlphaFunc,
401 so be sure to call glAlphaFunc in 1st FixedFunctionAlphaTestEnable. }
402 FFixedFunctionAlphaCutoff := -1;
403 end;
404
405 destructor TRenderContext.Destroy;
406 begin
407 FreeAndNil(FEnabledScissors);
408 FreeAndNil(FGlobalScissor);
409 inherited;
410 end;
411
412 procedure TRenderContext.WarnContextNotCurrent;
413 begin
414 WritelnWarning('RenderContext', 'Do not access TRenderContext properties and methods when this context is not the "current" one. Always access the properties and methods through the RenderContext singleton to avoid this warning.');
415 end;
416
417 procedure TRenderContext.Clear(Buffers: TClearBuffers;
418 const ClearColor: TCastleColor);
419 const
420 ClearBufferMask: array [TClearBuffer] of TGLbitfield =
421 ( GL_COLOR_BUFFER_BIT,
422 GL_DEPTH_BUFFER_BIT,
423 GL_STENCIL_BUFFER_BIT );
424 var
425 Mask: TGLbitfield;
426 B: TClearBuffer;
427 begin
428 if Self <> RenderContext then
429 WarnContextNotCurrent;
430
431 if InternalClearColorsByDraw and (cbColor in Buffers) then
432 begin
433 DrawRectangle(Viewport, ClearColor,
434 { Using these blending factors means that ClearColor overrides screen,
435 just like glClear does. So we don't do blending, in case ClearColor.W is <> 1,
436 which is consistent with our behavior when InternalClearColorsByDraw = false. }
437 bsOne, bdZero, false);
438 Exclude(Buffers, cbColor);
439 end;
440
441 if (cbColor in Buffers) and
442 not TVector4.PerfectlyEquals(FClearColor, ClearColor) then
443 begin
444 FClearColor := ClearColor;
445 glClearColor(FClearColor.X, FClearColor.Y, FClearColor.Z, FClearColor.W);
446 end;
447 Mask := 0;
448 for B in Buffers do
449 Mask := Mask or ClearBufferMask[B];
450 if Mask <> 0 then
451 glClear(Mask);
452 end;
453
454 procedure TRenderContext.SetLineWidth(const Value: Single);
455 begin
456 if Self <> RenderContext then
457 WarnContextNotCurrent;
458
459 if FLineWidth <> Value then
460 begin
461 FLineWidth := Value;
462 {$if (not defined(DARWIN)) or defined(OpenGLES)}
463 // on desktop macOS, glLineWidth raise GL_INVALID_VALUE for parameters <> 1.0
464 glLineWidth(Value);
465 {$endif}
466 end;
467 end;
468
469 procedure TRenderContext.SetPointSize(const Value: Single);
470 begin
471 if Self <> RenderContext then
472 WarnContextNotCurrent;
473
474 if FPointSize <> Value then
475 begin
476 FPointSize := Value;
477
478 { Not possible with OpenGL ES.
479 See http://stackoverflow.com/questions/9381562/using-gl-points-in-glkit-ios-5
480 http://www.idevgames.com/forums/thread-3.html :
481 "You must write gl_PointSize in the vertex shader, per point." }
482
483 {$ifndef OpenGLES}
484 glPointSize(Value);
485 {$endif}
486 end;
487 end;
488
489 procedure TRenderContext.SetGlobalAmbient(const Value: TCastleColorRGB);
490 begin
491 if Self <> RenderContext then
492 WarnContextNotCurrent;
493
494 if not TVector3.PerfectlyEquals(FGlobalAmbient, Value) then
495 begin
496 FGlobalAmbient := Value;
497
498 if GLFeatures.EnableFixedFunction then
499 begin
500 {$ifndef OpenGLES}
501 { We always set "1" as global ambient alpha.
502 This alpha does not have any useful interpretation, it seems,
503 so don't let it change. }
504 glLightModelv(GL_LIGHT_MODEL_AMBIENT, Vector4(FGlobalAmbient, 1));
505 {$endif}
506 end;
507 end;
508 end;
509
510 procedure TRenderContext.ScissorEnable(const Rect: TRectangle);
511 begin
512 if Self <> RenderContext then
513 WarnContextNotCurrent;
514
515 if FGlobalScissor = nil then
516 FGlobalScissor := TScissor.Create else
517 FGlobalScissor.Enabled := false; // disable previously enabled scissor, if any
518 FGlobalScissor.Rect := Rect;
519 FGlobalScissor.Enabled := true;
520 end;
521
522 procedure TRenderContext.ScissorDisable;
523 begin
524 if Self <> RenderContext then
525 WarnContextNotCurrent;
526
527 if FGlobalScissor <> nil then // secure in case FGlobalScissor was already fred
528 FGlobalScissor.Enabled := false;
529 end;
530
531 procedure TRenderContext.SetProjectionMatrix(const Value: TMatrix4);
532 begin
533 if Self <> RenderContext then
534 WarnContextNotCurrent;
535
536 FProjectionMatrix := Value;
537
538 if GLFeatures.EnableFixedFunction then
539 begin
540 {$ifndef OpenGLES}
541 glMatrixMode(GL_PROJECTION);
542 {$warnings off}
543 glLoadMatrix(Value); // consciously using deprecated stuff; this should be internal in this unit
544 {$warnings on}
545 glMatrixMode(GL_MODELVIEW);
546 {$endif}
547 end;
548 end;
549
550
551 procedure TRenderContext.SetDepthRange(const Value: TDepthRange);
552 begin
553 if Self <> RenderContext then
554 WarnContextNotCurrent;
555
556 if FDepthRange <> Value then
557 begin
558 {$ifdef OpenGLES} {$define glDepthRange := glDepthRangef} {$endif}
559 FDepthRange := Value;
560 case Value of
561 drFull: glDepthRange(0 , 1);
562 drNear: glDepthRange(0 , 0.1);
563 drFar : glDepthRange(0.1, 1);
564 end;
565 end;
566 end;
567
568 procedure TRenderContext.SetCullFace(const Value: boolean);
569 begin
570 if Self <> RenderContext then
571 WarnContextNotCurrent;
572
573 if FCullFace <> Value then
574 begin
575 FCullFace := Value;
576 GLSetEnabled(GL_CULL_FACE, FCullFace);
577 end;
578 end;
579
580 procedure TRenderContext.SetFrontFaceCcw(const Value: boolean);
581 begin
582 if Self <> RenderContext then
583 WarnContextNotCurrent;
584
585 if FFrontFaceCcw <> Value then
586 begin
587 FFrontFaceCcw := Value;
588 if Value then
589 glFrontFace(GL_CCW)
590 else
591 glFrontFace(GL_CW);
592 end;
593 end;
594
595 procedure TRenderContext.SetDepthTest(const Value: Boolean);
596 begin
597 if Self <> RenderContext then
598 WarnContextNotCurrent;
599
600 if FDepthTest <> Value then
601 begin
602 FDepthTest := Value;
603 GLSetEnabled(GL_DEPTH_TEST, FDepthTest);
604 end;
605 end;
606
607 procedure TRenderContext.SetDepthFunc(const Value: TDepthFunction);
608 begin
609 if Self <> RenderContext then
610 WarnContextNotCurrent;
611
612 if FDepthFunc <> Value then
613 begin
614 FDepthFunc := Value;
615 glDepthFunc(Ord(FDepthFunc));
616 end;
617 end;
618
619 function TRenderContext.GetColorMask: boolean;
620 begin
621 Result := ColorChannels <> [];
622 end;
623
624 procedure TRenderContext.SetColorMask(const Value: boolean);
625 begin
626 if Value then
627 ColorChannels := AllColorChannels
628 else
629 ColorChannels := [];
630 end;
631
632 procedure TRenderContext.SetColorChannels(const Value: TColorChannels);
633 begin
634 if Self <> RenderContext then
635 WarnContextNotCurrent;
636
637 if FColorChannels <> Value then
638 begin
639 FColorChannels := Value;
640 glColorMask(
641 BoolToGL(0 in FColorChannels),
642 BoolToGL(1 in FColorChannels),
643 BoolToGL(2 in FColorChannels),
644 BoolToGL(3 in FColorChannels)
645 );
646 end;
647 end;
648
649 procedure TRenderContext.SetDepthBufferUpdate(const Value: boolean);
650 begin
651 if Self <> RenderContext then
652 WarnContextNotCurrent;
653
654 if FDepthBufferUpdate <> Value then
655 begin
656 FDepthBufferUpdate := Value;
657 glDepthMask(BoolToGL(Value));
658 end;
659 end;
660
661 procedure TRenderContext.UpdateViewport;
662 begin
663 glViewport(
664 FViewport.Left + FViewportDelta.X,
665 FViewport.Bottom + FViewportDelta.Y,
666 FViewport.Width,
667 FViewport.Height);
668 end;
669
670 procedure TRenderContext.WarningViewportTooLarge;
671 begin
672 if not WarningViewportTooLargeDone then
673 begin
674 WritelnWarning('Setting viewport %s, with has dimensions larger than maximum allowed %s. (Further warnings of the same type will not be shown.)', [
675 FViewport.ToString,
676 GLFeatures.MaxViewportDimensions.ToString
677 ]);
678 WarningViewportTooLargeDone := true;
679 end;
680 end;
681
682 procedure TRenderContext.SetViewport(const Value: TRectangle);
683 begin
684 if Self <> RenderContext then
685 WarnContextNotCurrent;
686
687 if not FViewport.Equals(Value) then
688 begin
689 if (GLFeatures <> nil) and
690 ((FViewport.Width > GLFeatures.MaxViewportDimensions.X) or
691 (FViewport.Height > GLFeatures.MaxViewportDimensions.Y)) then
692 WarningViewportTooLarge;
693
694 FViewport := Value;
695 UpdateViewport;
696 end;
697 end;
698
699 procedure TRenderContext.SetViewportDelta(const Value: TVector2Integer);
700 begin
701 if Self <> RenderContext then
702 WarnContextNotCurrent;
703
704 if not TVector2Integer.Equals(FViewportDelta, Value) then
705 begin
706 FViewportDelta := Value;
707 UpdateViewport;
708 end;
709 end;
710
711 function TRenderContext.FinalScissor(out Rect: TRectangle): Boolean;
712 begin
713 Result :=
714 (FEnabledScissors <> nil) and
715 (FEnabledScissors.Count <> 0);
716 if Result then
717 Rect := FEnabledScissors.FFinalScissor;
718 end;
719
720 procedure TRenderContext.SetCurrentProgram(const Value: TGLSLProgram);
721 begin
722 if FCurrentProgram <> Value then
723 begin
724 FCurrentProgram := Value;
725 InternalSetCurrentProgram(Value);
726 end;
727 end;
728
729 procedure TRenderContext.SetCurrentVao(const Value: TVertexArrayObject);
730 begin
731 if FCurrentVao <> Value then
732 begin
733 FCurrentVao := Value;
734 if GLFeatures.VertexArrayObject then
735 begin
736 if Value <> nil then
737 glBindVertexArray(Value.InternalHandle(Self))
738 else
739 glBindVertexArray(0);
740 end;
741 end;
742 end;
743
744 function TRenderContext.ColorBufferHasAlpha: Boolean;
745 begin
746 Result := GLFeatures.AlphaBits > 0;
747 end;
748
749 procedure TRenderContext.BlendingEnable(
750 const SourceFactor: TBlendingSourceFactor = bsSrcAlpha;
751 const DestinationFactor: TBlendingDestinationFactor = bdOneMinusSrcAlpha);
752 begin
753 if not FBlendingEnabled then
754 begin
755 FBlendingEnabled := true;
756 glEnable(GL_BLEND);
757 end;
758
759 if (FBlendingSourceFactor <> SourceFactor) or
760 (FBlendingDestinationFactor <> DestinationFactor) then
761 begin
762 FBlendingSourceFactor := SourceFactor;
763 FBlendingDestinationFactor := DestinationFactor;
764 {$warnings off} // using deprecated routine that should be internal here
765 GLBlendFunction(SourceFactor, DestinationFactor);
766 {$warnings on}
767 end;
768 end;
769
770 procedure TRenderContext.BlendingDisable;
771 begin
772 if FBlendingEnabled then
773 begin
774 FBlendingEnabled := false;
775 glDisable(GL_BLEND);
776 end;
777 end;
778
779 procedure TRenderContext.FixedFunctionAlphaTestEnable(const AlphaCutoff: Single = 0.5);
780 begin
781 if GLFeatures.EnableFixedFunction then
782 begin
783 if not FFixedFunctionAlphaTest then
784 begin
785 FFixedFunctionAlphaTest := true;
786 {$ifndef OpenGLES}
787 glEnable(GL_ALPHA_TEST);
788 {$endif}
789 end;
790
791 if FFixedFunctionAlphaCutoff <> AlphaCutoff then
792 begin
793 FFixedFunctionAlphaCutoff := AlphaCutoff;
794 {$ifndef OpenGLES}
795 glAlphaFunc(GL_GEQUAL, AlphaCutoff);
796 {$endif}
797 end;
798 end;
799 end;
800
801 procedure TRenderContext.FixedFunctionAlphaTestDisable;
802 begin
803 if GLFeatures.EnableFixedFunction then
804 begin
805 if FFixedFunctionAlphaTest then
806 begin
807 FFixedFunctionAlphaTest := false;
808 {$ifndef OpenGLES}
809 glDisable(GL_ALPHA_TEST);
810 {$endif}
811 end;
812 end;
813 end;
814
815 procedure TRenderContext.SetFixedFunctionLighting(const Value: boolean);
816 begin
817 if FFixedFunctionLighting <> Value then
818 begin
819 FFixedFunctionLighting := Value;
820 {$ifndef OpenGLES}
821 if GLFeatures.EnableFixedFunction then
822 GLSetEnabled(GL_LIGHTING, Value);
823 {$endif}
824 end;
825 end;
826
827 procedure TRenderContext.SetLineType(const Value: TLineType);
828 begin
829 if FLineType <> Value then
830 begin
831 FLineType := Value;
832 {$ifndef OpenGLES}
833 case LineType of
834 ltSolid: glDisable(GL_LINE_STIPPLE);
835 ltDashed : begin glLineStipple(1, $00FF); glEnable(GL_LINE_STIPPLE); end;
836 ltDotted : begin glLineStipple(1, $CCCC); glEnable(GL_LINE_STIPPLE); end;
837 ltDashedDotted: begin glLineStipple(1, $FFCC); glEnable(GL_LINE_STIPPLE); end;
838 ltDashDotDot : begin glLineStipple(1, $FCCC); glEnable(GL_LINE_STIPPLE); end;
839 {$ifndef COMPILER_CASE_ANALYSIS}
840 else raise EInternalError.Create('LineType?');
841 {$endif}
842 end;
843 {$endif}
844 end;
845 end;
846
847 procedure TRenderContext.SetPolygonOffset(const Value: TPolygonOffset);
848 begin
849 if (FPolygonOffset.Enabled <> Value.Enabled) or
850 (FPolygonOffset.Scale <> Value.Scale) or
851 (FPolygonOffset.Bias <> Value.Bias) then
852 begin
853 FPolygonOffset := Value;
854 if Value.Enabled then
855 begin
856 glEnable(GL_POLYGON_OFFSET_FILL);
857 {$ifndef OpenGLES} // These do not exist on OpenGLES
858 glEnable(GL_POLYGON_OFFSET_LINE);
859 glEnable(GL_POLYGON_OFFSET_POINT);
860 {$endif}
861 glPolygonOffset(Value.Scale, Value.Bias);
862 end else
863 begin
864 glDisable(GL_POLYGON_OFFSET_FILL);
865 {$ifndef OpenGLES} // These do not exist on OpenGLES
866 glDisable(GL_POLYGON_OFFSET_LINE);
867 glDisable(GL_POLYGON_OFFSET_POINT);
868 {$endif}
869 end;
870 end;
871 end;
872
873 procedure TRenderContext.PolygonOffsetEnable(const Scale, Bias: Single);
874 var
875 NewState: TPolygonOffset;
876 begin
877 NewState.Enabled := true;
878 NewState.Scale := Scale;
879 NewState.Bias := Bias;
880 PolygonOffset := NewState;
881 end;
882
883 procedure TRenderContext.PolygonOffsetDisable;
884 var
885 NewState: TPolygonOffset;
886 begin
887 NewState.Enabled := false;
888 { Whatever, will not be set anyway. }
889 NewState.Scale := 0;
890 NewState.Bias := 0;
891 PolygonOffset := NewState;
892 end;
893
894 function TRenderContext.GetBoundBuffer(const Target: TBufferTarget): TGLuint;
895 begin
896 Result := FBoundBuffer[Target];
897 end;
898
899 procedure TRenderContext.SetBoundBuffer(const Target: TBufferTarget; const Value: TGLuint);
900 begin
901 { TODO: Optimization (avoiding glBindBuffer) disabled.
902 Reason: castle-model-viewer (rock.gltf, triangulatio.x3dv) shows
903 that we cannot optimize out glBindBuffer calls like this,
904 it's causing crashes (Linux "guardia" system, Nvidia GPU).
905
906 if FBoundBuffer[Target] <> Value then
907 begin
908 FBoundBuffer[Target] := Value;
909 glBindBuffer(BufferTargetGL[Target], Value);
910 end;
911 }
912
913 glBindBuffer(BufferTargetGL[Target], Value);
914 end;
915
916 { TRenderContext.TScissorList ------------------------------------------------------------------- }
917
918 procedure TRenderContext.TScissorList.Update;
919 var
920 R: TRectangle;
921 I: Integer;
922 begin
923 // we need to flush batched things, before scissor change
924 TDrawableImage.BatchingFlush;
925
926 if Count <> 0 then
927 begin
928 R := Items[0].Rect;
929 for I := 1 to Count - 1 do
930 R := R * Items[I].Rect;
931 FFinalScissor := R;
932 glScissor(R.Left, R.Bottom, R.Width, R.Height);
933 glEnable(GL_SCISSOR_TEST);
934 end else
935 glDisable(GL_SCISSOR_TEST);
936 end;
937
938 { TScissor ------------------------------------------------------------------- }
939
940 constructor TScissor.Create;
941 begin
942 inherited;
943 Rect := TRectangle.Empty;
944 end;
945
946 destructor TScissor.Destroy;
947 begin
948 Enabled := false;
949 inherited;
950 end;
951
952 procedure TScissor.SetEnabled(const Value: boolean);
953 begin
954 if FEnabled <> Value then
955 begin
956 FEnabled := Value;
957 if RenderContext.FEnabledScissors <> nil then
958 begin
959 if Value then
960 RenderContext.FEnabledScissors.Add(Self) else
961 RenderContext.FEnabledScissors.Remove(Self);
962 RenderContext.FEnabledScissors.Update;
963 end;
964 end;
965 end;
966
967 { projection matrix ---------------------------------------------------------- }
968
969 function PerspectiveProjection(const fovy, aspect, ZNear, ZFar: Single): TMatrix4;
970 begin
971 Result := PerspectiveProjectionMatrixDeg(fovy, aspect, ZNear, ZFar);
972 RenderContext.ProjectionMatrix := Result;
973 end;
974
975 function OrthoProjection(const Dimensions: TFloatRectangle; const ZNear, ZFar: Single): TMatrix4;
976 begin
977 Result := OrthoProjectionMatrix(Dimensions, ZNear, ZFar);
978 RenderContext.ProjectionMatrix := Result;
979 end;
980
981 function FrustumProjection(const Dimensions: TFloatRectangle; const ZNear, ZFar: Single): TMatrix4;
982 begin
983 Result := FrustumProjectionMatrix(Dimensions, ZNear, ZFar);
984 RenderContext.ProjectionMatrix := Result;
985 end;
986
987 end.