Debian Codegraph @

src/base_rendering/castleglimages_drawableimage.inc

raw
1 {%MainUnit castleglimages.pas}
2 {
3 Copyright 2001-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 { Part of CastleGLImages unit: drawing 2D images on screen (TDrawableImage class). }
18
19 {$ifdef read_interface}
20
21 {$ifdef read_interface_type}
22 // type - don't add type Delphi can't parse that correctly
23 TGLRenderToTexture = class;
24
25 { Statistics to measure TDrawableImage rendering impact.
26 Cleared at every TCastleContainer.EventRender start. }
27 TDrawableImageRenderStatistics = record
28 { How many times TDrawableImage.Draw was called (regardless of the Count argument). }
29 ImageDraws: Cardinal;
30
31 { Draw calls done, in case of OpenGL this literally counts the number of calls
32 to glDrawElements and glDrawArrays. }
33 DrawCalls: Cardinal;
34
35 { Present the statistics information as a string (without any newlines).
36 Display it e.g. by assigning to TCastleLabel.Caption. }
37 function ToString: String;
38 end;
39
40 { Image that can be drawn.
41 This image can be drawn in various rendering methods and events,
42 e.g. inside overridden @link(TCastleUserInterface.Render) or from events
43 @link(TCastleWindow.OnRender) or
44 @link(TCastleControl.OnRender).
45
46 See the manual about drawing using TDrawableImage:
47 https://castle-engine.io/manual_2d_ui_custom_drawn.php .
48 See the description how to render 2D stuff using Castle Game Engine:
49 https://castle-engine.io/how_to_render_2d .
50
51 We have a few (probably too many) ways to show a 2D image.
52 Alternatives to TDrawableImage are:
53
54 @unorderedList(
55 @item(TCastleImagePersistent: Wraps TEncodedImage and TDrawableImage in a class
56 that has comfortable published properties (so it can be edited in CGE editor,
57 can be saved to CGE design files). Also adds caching.)
58
59 @item(TCastleImageControl: UI control to draw an image, using TCastleImagePersistent.
60 This will perform the drawing by itself.)
61
62 @item(TCastleScene: You can also load an image to TCastleScene.Load to create
63 a rectangle displaying this texture, which can be rendered in 2D and 3D.)
64 ) }
65 TDrawableImage = class(TNoParameterlessContructor)
66 strict private
67 type
68 TPoint = packed record
69 Position: TVector2;
70 TexCoord: TVector2;
71 end;
72 TPointArray = packed array [0..MaxInt div SizeOf(TPoint) - 1] of TPoint;
73 PPointArray = ^TPointArray;
74
75 { Used only in shader pipeline }
76 TColorTreatment = (
77 { Use texture color to draw. }
78 ctPureTexture,
79 { Use constant color * texture (on all RGBA channels). }
80 ctColorMultipliesTexture,
81 { Use constant color for RGB,
82 for alpha use constant color.a * texture.
83 Useful when texture has no alpha information. }
84 ctColorMultipliesTextureAlpha);
85
86 TImageProgram = record
87 Prog: TGLSLProgram;
88 UniformViewportSize, UniformColor, UniformClipLine: TGLSLUniform;
89 AttribVertex, AttribTexCoord: TGLSLAttribute;
90 procedure InitializeUniformsAttributes(
91 const ClipLineShader: boolean;
92 const ColorTreatment: TColorTreatment);
93 end;
94
95 TVboStorage = record
96 PointsVbo, IndexesVbo: TGLuint;
97 PointsVboSize, IndexesVboSize: Cardinal;
98 Vao: TVertexArrayObject;
99 end;
100 PVboStorage = ^TVboStorage;
101
102 class var
103 { Static OpenGL resources, used by all TDrawableImage instances.
104 Instead of using the same TVboStorage for all TDrawableImage.Draw calls,
105 we rotate between a number of TVboStorage, each with it's own VBOs.
106
107 This way we minimize the overhead caused by updating VBO that is currently
108 drawn in parallel:
109 https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBufferSubData.xhtml
110 :
111
112 """
113 Consider using multiple buffer objects to avoid stalling
114 the rendering pipeline during data store updates.
115 If any rendering in the pipeline makes reference to data in
116 the buffer object being updated by glBufferSubData,
117 especially from the specific region being updated,
118 that rendering must drain from the pipeline before
119 the data store can be updated.
120 """
121
122 This makes a huge speedup for drawing UI on Raspberry Pi OpenGLES
123 without X.
124 }
125 VboStorage: array [0..9] of TVboStorage;
126 VboStorageNext: Cardinal;
127 { Point VBO contents, reused in every Draw. }
128 Points: array of TPoint;
129 Indexes: array of TGLIndex;
130
131 { Used only in shader pipeline }
132 Programs: array [boolean { alpha test? }, boolean { clip? }, TColorTreatment] of TImageProgram;
133 var
134 TextureHasOnlyAlpha: boolean;
135 FWidth: Cardinal;
136 FHeight: Cardinal;
137 FAlpha: TAutoAlphaChannel;
138 FColor: TCastleColor;
139 FSmoothScaling: boolean;
140 FScaleCorners: Single;
141 FRotation: Single;
142 FRotationCenter: TVector2;
143 ScreenRotationCenter: TVector2;
144 UseScreenRotationCenter: boolean;
145 FClip: boolean;
146 FClipLine: TVector3;
147 { The detected alpha channel of the loaded image.
148 It influences the drawing mode, if @link(Alpha) is acAuto.
149
150 This property is always acNone before the image is loaded.
151 You cannot change it, you can only change the @link(Alpha) property
152 that actually dictates the alpha drawing mode. }
153 FImageAlpha: TAlphaChannel;
154 FBlendingSourceFactor: TBlendingSourceFactor;
155 FBlendingDestinationFactor: TBlendingDestinationFactor;
156 FBlendingConstantColor: TVector4;
157 FCustomShader: TGLSLProgram;
158
159 FTexture: TGLTextureId;
160 FImage: TEncodedImage;
161 FOwnsImage: boolean;
162 FUrl: String;
163 FRepeatS, FRepeatT: Boolean;
164
165 FRenderToImage: TGLRenderToTexture;
166 HasViewportToRestore: boolean;
167 ViewportToRestore: TRectangle;
168
169 function FinalAlpha: TAlphaChannel;
170 procedure SetSmoothScaling(const Value: boolean);
171 function CurrentFilter: TTextureFilter;
172 function CurrentWrap: TTextureWrap2D;
173 procedure SetImage(const AImage: TEncodedImage);
174 procedure GLContextCloseEvent(Sender: TObject);
175 procedure GLContextOpen(const AImage: TEncodedImage);
176 procedure GLContextClose;
177 function GetCenterX: Single;
178 function GetCenterY: Single;
179 procedure SetCenterX(const Value: Single);
180 procedure SetCenterY(const Value: Single);
181 procedure SetRepeatS(const Value: Boolean);
182 procedure SetRepeatT(const Value: Boolean);
183 procedure SetUrl(const Value: String);
184 procedure SetColor(const Value: TCastleColor);
185 procedure SetRotation(const Value: Single);
186 procedure SetRotationCenter(const Value: TVector2);
187 procedure SetAlpha(const Value: TAutoAlphaChannel);
188 procedure SetBlendingSourceFactor(const Value: TBlendingSourceFactor);
189 procedure SetBlendingDestinationFactor(const Value: TBlendingDestinationFactor);
190 procedure SetBlendingConstantColor(const Value: TVector4);
191 procedure SetClip(const Value: Boolean);
192 procedure SetClipLine(const Value: TVector3);
193 { If this image state affects current batching operation, flush batching. }
194 procedure BatchingFlushIfNeeded;
195 procedure DrawNoBatch(
196 const ScreenRects, ImageRects: PFloatRectangleArray; const Count: Integer);
197 private
198 class var
199 StaticResourcesReady: Boolean;
200
201 { 0 means we're not in batching mode, > 1 means we are between BatchingBegin and BatchingEnd. }
202 BatchingLevel: Cardinal;
203
204 { Pending image to draw with BatchingLastScreenRects, BatchingLastImageRects.
205 Conditions:
206 - May be @nil if none.
207 - Always @nil if BatchingLevel = 0. }
208 BatchingLastImage: TDrawableImage;
209
210 { Pending rectangles to draw.
211 Conditions:
212 - Always @nil if BatchingLevel = 0, never @nil otherwise.
213 - Always empty (count = 0) and non-@nil if (BatchingLevel > 0) and (BatchingLastImage = @nil). }
214 BatchingLastScreenRects, BatchingLastImageRects: TFloatRectangleList;
215
216 { Create / destroy static stuff for rendering. }
217 class procedure StaticGLContextOpen;
218 class procedure StaticGLContextClose;
219 public
220 class var
221 Statistics: TDrawableImageRenderStatistics;
222
223 const
224 DefaultBlendingSourceFactor = bsSrcAlpha;
225 DefaultBlendingDestinationFactor = bdOneMinusSrcAlpha;
226 DefaultBlendingConstantColor: TVector4 = (X: 1; Y: 1; Z: 1; W: 1);
227
228 { Start batching that optimizes further @link(TDrawableImage.Draw) calls by grouping them.
229
230 All subsequent calls to @link(TDrawableImage.Draw) are delayed, to be grouped in case
231 you execute @link(TDrawableImage.Draw) multiple times on the same image,
232 in which case it is more efficient to draw multiple rectangles in one "draw call" for OpenGL.
233
234 The images are actually drawn only when you try to draw a different image,
235 or when you execute @link(BatchingEnd).
236
237 Some other operations also flush the last batch to to the screen:
238 rendering using @link(DrawPrimitive2D) and friends like @link(DrawRectangle),
239 changing the parameters or last image that affect rendering (like image contents,
240 @link(TDrawableImage.Color) or @link(TDrawableImage.Rotation)), freeing last image.
241 This fact should be transparent to you, we try to flush as seldom as possible
242 to have as big groups (and thus effective batching) as possible.
243
244 Calling BatchingBegin with matching BatchingEnd when the batching is already in progress
245 is gracefully handled, i.e. we assume you just continue larger-scope batching.
246 So the "inner" BatchingBegin + BatchingEnd calls are ignored, but you always must match
247 one BatchingBegin with one BatchingEnd.
248 }
249 class procedure BatchingBegin;
250 class procedure BatchingEnd;
251
252 { If we are during batching, then flush the pending drawing now.
253
254 You should never need to call this, unless you do direct rendering
255 that is not
256
257 @unorderedList(
258 @itemSpacing compact
259 @item using TDrawableImage
260 @item using DrawPrimitive2D (and friends in CastleGLUtils),
261 @item using TCastleScreenEffect, TCasleViewport rendering.
262 )
263 }
264 class procedure BatchingFlush;
265
266 { Prepare image for drawing.
267
268 @param(Image Initial image contents.
269 The @code(Image) instance passed here must exist throughout
270 the whole lifetime of this TDrawableImage instance (so don't free it earlier).
271 It can be automatically freed by us, if OwnsImage = @true.
272
273 It can be @nil.)
274
275 @raises(EImageClassNotSupportedForOpenGL When Image class is not supported
276 by OpenGL.) }
277 constructor Create(const AImage: TEncodedImage; const ASmoothScaling: boolean;
278 const AOwnsImage: boolean); overload;
279
280 { Load image from disk, and prepare for drawing.
281
282 @param(AUrl URL (or filename) from which to load the image.
283 Often you want to use here castle-data:/ protocol to load application data,
284 like:
285
286 @longCode(# Image := TDrawableImage.Create('castle-data:/textures/my_image.png', ...); #)
287
288 See https://castle-engine.io/data
289 )
290
291 @param(ASmoothScaling The initial value of @link(SmoothScaling),
292 determines whether the image scaling is smooth (bilinear filtering)
293 or not (nearest-pixel filtering).
294 You can always change it later through the @link(SmoothScaling)
295 property. But each change has a small cost, so it's more efficient
296 to just set the initial value correctly.)
297 }
298 constructor Create(const AUrl: String;
299 const ASmoothScaling: boolean = true); overload;
300
301 { Load image from disk, and prepare for drawing.
302
303 @param(AUrl URL (or filename) from which to load the image.
304 Usually you want to use here URL starting with the "castle-data:" protocol,
305 to load an image from application data, like this:
306
307 @longCode(# Image := TDrawableImage.Create('castle-data:/textures/my_image.png', ...); #)
308 )
309
310 @param(LoadAsClass Constrain the possible image classes to load into.
311 This can force removing (or adding) an alpha channel,
312 or converting contents to grayscale or RGB, regardless of the preferred
313 image file format.
314 Must be a subset of PixelsImageClasses, as other classes cannot
315 be loaded into OpenGL 2D images, otherwise you may get
316 EImageClassNotSupportedForOpenGL exception.
317 Pass empty set [] to load into any allowed class
318 (it's equivalent to passing LoadAsClass = PixelsImageClasses).
319
320 You can pass e.g. [TRGBImage] to force loading into an RGB image without
321 an alpha channel (it will be stripped from the image if necessary).)
322
323 @param(ResizeToX After loading, resize to given width.
324 Pass 0 to not resize width.)
325
326 @param(ResizeToY After loading, resize to given height.
327 Pass 0 to not resize height.)
328
329 @param(Interpolation If any resizing will be needed (if
330 ResizeToX / ResizeToY parameters request some specific size,
331 and it is different than loaded image size) then the resize
332 operation will use given interpolation.)
333
334 @raises(EImageClassNotSupportedForOpenGL When image class is not supported
335 by OpenGL.)
336 }
337 constructor Create(const AUrl: String;
338 const LoadAsClass: array of TEncodedImageClass;
339 const ResizeToX: Cardinal = 0;
340 const ResizeToY: Cardinal = 0;
341 const Interpolation: TResizeInterpolation = riBilinear); overload;
342
343 { Load image from disk, and prepare for drawing.
344
345 @param(AUrl URL (or filename) from which to load the image.
346 Often you want to pass here the result ot ApplicationData
347 function, like:
348
349 @longCode(# Image := TDrawableImage.Create('castle-data:/textures/my_image.png', ...); #)
350 )
351
352 @param(LoadAsClass Constrain the possible image classes to load into.
353 This can force removing (or adding) an alpha channel,
354 or converting contents to grayscale or RGB, regardless of the preferred
355 image file format.
356 Must be a subset of PixelsImageClasses, as other classes cannot
357 be loaded into OpenGL 2D images, otherwise you may get
358 EImageClassNotSupportedForOpenGL exception.
359 Pass empty set [] to load into any allowed class
360 (it's equivalent to passing LoadAsClass = PixelsImageClasses).
361
362 You can pass e.g. [TRGBImage] to force loading into an RGB image without
363 an alpha channel (it will be stripped from the image if necessary).)
364
365 @param(ASmoothScaling The initial value of @link(SmoothScaling),
366 determines whether the image scaling is smooth (bilinear filtering)
367 or not (nearest-pixel filtering).
368 You can always change it later through the @link(SmoothScaling)
369 property. But each change has a small cost, so it's more efficient
370 to just set the initial value correctly.)
371 }
372 constructor Create(const AUrl: String;
373 const LoadAsClass: array of TEncodedImageClass;
374 const ASmoothScaling: boolean); overload;
375
376 destructor Destroy; override;
377
378 property Width: Cardinal read FWidth;
379 property Height: Cardinal read FHeight;
380
381 { Rectangle representing the inside of this image.
382 Always (Left,Bottom) are zero, and (Width,Height) correspond to image
383 sizes. }
384 function Rect: TRectangle;
385
386 { How to render the alpha channel of the texture.
387
388 @unorderedList(
389 @item(acAuto means to guess correct alpha channel from the loaded image
390 contents, and the current @link(Color). We use @italic(alpha blending)
391 if the loaded image alpha indicates so, or @code(Color[3] < 1).
392 Otherwise we use @italic(alpha testing) if the loaded image
393 alpha indicates so. Otherwise we don't use any alpha,
394 we render image opaque.)
395 @item acNone means to ignore it.
396 @item acTest means to render with alpha-test.
397 @item acBlending means to render with blending.
398 )
399
400 This is initialized based on loaded image class and data.
401 This means that e.g. if you have smooth alpha channel in the image,
402 it will be automatically rendered with nice blending.
403
404 You can change the value of this property to force a specific
405 rendering method, for example to force using alpha test or alpha blending
406 regardless of alpha values. Or to disable alpha channel usage,
407 because your image must always cover pixels underneath.
408
409 Remember that you can also change the alpha channel existence
410 at loading: use LoadAsClass parameters of LoadImage
411 or TDrawableImage.Create to force your image to have/don't have
412 an alpha channel (e.g. use LoadAsClass=[TRGBImage]
413 to force RGB image without alpha, use LoadAsClass=[TRGBAlphaImage]
414 to force alpha channel). }
415 property Alpha: TAutoAlphaChannel read FAlpha write SetAlpha
416 default acAuto;
417
418 { Blending source factor, if we use blending (see @link(Alpha)). }
419 property BlendingSourceFactor: TBlendingSourceFactor
420 read FBlendingSourceFactor
421 write SetBlendingSourceFactor
422 default DefaultBlendingSourceFactor;
423
424 { Blending destination factor, if we use blending (see @link(Alpha)). }
425 property BlendingDestinationFactor: TBlendingDestinationFactor
426 read FBlendingDestinationFactor
427 write SetBlendingDestinationFactor
428 default DefaultBlendingDestinationFactor;
429
430 { For some blending source or destination factors (see
431 @link(BlendingSourceFactor), @link(BlendingDestinationFactor)),
432 this constant color (or it's alpha value) take part
433 in the blending equation. Used only if blending (see @link(Alpha)).
434 By default, opaque white. }
435 property BlendingConstantColor: TCastleColor
436 read FBlendingConstantColor
437 write SetBlendingConstantColor;
438
439 { Draw the image as 2D on screen.
440
441 The X, Y parameters determine where the left-bottom
442 corner of the image will be placed (from 0 to size - 1).
443
444 You should only use this inside TCastleUserInterface.Render.
445 We require that current projection is 2D and
446 lighting / depth test and such are off, which is the default state
447 there.
448
449 The image is drawn in 2D. In normal circumstances
450 1 pixel of the image is just placed over 1 pixel of the screen,
451 and we draw the whole image. But you can use the overloaded
452 versions where you specify DrawWidth, DrawHeight or ScreenRect,
453 and then the indicated image portion is stretched over the designated
454 screen area. Note: if you plan to use such stretching when drawing
455 the image, then you usually want to create the image with
456 SmoothScaling = @true (otherwise the scaling will look pixelated).
457
458 Note that the image position (ImageX, ImageY) is specified
459 like a texture coordinate. So (0, 0) is actually
460 the left-bottom corner of the left-bottom pixel,
461 and (Width,Height) is the right-top corner of the right-top pixel.
462 That is why image position and sizes are floats, it makes sense
463 to render partial pixels this way (make sure you have
464 SmoothScaling = @true to get nice scaling of image contents).
465
466 You can also flip the image horizontally or vertically,
467 e.g. use ImageX = Width and ImageWidth = -Width to mirror
468 image horizontally. Although it's usually more comfortable
469 to flip using DrawFlipped methods.
470
471 @groupBegin }
472 procedure Draw(const X, Y: Single); overload;
473 procedure Draw(const X, Y, DrawWidth, DrawHeight: Single); overload;
474 procedure Draw(const X, Y, DrawWidth, DrawHeight: Single;
475 const ImageX, ImageY, ImageWidth, ImageHeight: Single); overload;
476
477 procedure Draw(const Pos: TVector2Integer); overload;
478
479 procedure Draw(const ScreenRect: TFloatRectangle); overload;
480 procedure Draw(const ScreenRect, ImageRect: TFloatRectangle); overload;
481
482 procedure Draw(const ScreenRect: TRectangle); overload;
483 procedure Draw(const ScreenRect: TRectangle;
484 const ImageX, ImageY, ImageWidth, ImageHeight: Single); overload;
485 procedure Draw(const ScreenRect, ImageRect: TRectangle); overload;
486
487 procedure Draw(ScreenRects, ImageRects: PFloatRectangleArray;
488 Count: Integer); overload; virtual;
489 { @groupEnd }
490
491 procedure DrawFlipped(const ScreenRect: TRectangle;
492 const FlipHorizontal, FlipVertical: boolean); overload;
493 procedure DrawFlipped(const ScreenRect: TFloatRectangle;
494 const FlipHorizontal, FlipVertical: boolean); overload;
495 procedure DrawFlipped(const ScreenRect: TFloatRectangle;
496 ImageRect: TFloatRectangle;
497 const FlipHorizontal, FlipVertical: boolean); overload;
498
499 { In case of @link(Draw3x3) the corners
500 on screen are scaled by this amount. This is especially useful
501 for UI scaling, see @link(TCastleContainer.UIScaling)
502 and @link(TCastleUserInterface.UIScale). }
503 property ScaleCorners: Single
504 read FScaleCorners write FScaleCorners {$ifdef FPC}default 1{$endif};
505
506 { Draw the image on the screen, divided into 3x3 parts for corners,
507 sides, and inside.
508
509 Just like the regular @link(Draw) method, this fills a rectangle on the
510 2D screen, with bottom-left corner in (X, Y), and size (DrawWidth,
511 DrawHeight). The image is divided into 3 * 3 = 9 parts:
512
513 @unorderedList(
514 @item(4 corners, used to fill the corners of the screen
515 rectangle. They are not stretched.)
516 @item(4 sides, used to fill the sides of the screen rectangle
517 between the corners. They are scaled in one dimension, to fill
518 the space between corners completely.)
519 @item(the inside. Used to fill the rectangular inside.
520 Scaled in both dimensions as necessary.)
521 )
522 }
523 procedure Draw3x3(const X, Y, DrawWidth, DrawHeight: Single;
524 CornerTop, CornerRight, CornerBottom, CornerLeft: Single;
525 ImageLeft: Single = 0; ImageBottom: Single = 0;
526 ImageWidth: Single = -1; ImageHeight: Single = -1); overload;
527
528 procedure Draw3x3(const X, Y, DrawWidth, DrawHeight: Single;
529 const Corner: TVector4Integer; const ImageRect: TFloatRectangle); overload;
530 procedure Draw3x3(const ScreenRect: TRectangle;
531 const Corner: TVector4Integer; const ImageRect: TFloatRectangle); overload;
532 procedure Draw3x3(const ScreenRect: TFloatRectangle;
533 const Corner: TVector4Integer; const ImageRect: TFloatRectangle); overload;
534 procedure Draw3x3(const ScreenRect: TFloatRectangle;
535 const Corner: TVector4; const ImageRect: TFloatRectangle); overload;
536
537 procedure Draw3x3(const X, Y, DrawWidth, DrawHeight: Single;
538 const Corner: TVector4Integer); overload;
539 procedure Draw3x3(const ScreenRect: TRectangle;
540 const Corner: TVector4Integer); overload;
541 procedure Draw3x3(const ScreenRect: TFloatRectangle;
542 const Corner: TVector4Integer); overload;
543 procedure Draw3x3(const ScreenRect: TFloatRectangle;
544 const Corner: TVector4); overload;
545
546 (* Commented out for now: using Draw3x3 with
547 CornerTop = CornerBottom = 0 should have the same effect?
548
549 { Draw the image on the screen, divided into 3x1 parts:
550 unscaled left and right sides, and scaled inside.
551
552 Similar to @link(Draw3x3), but image is divided into 3 parts, not 9. }
553 procedure Draw3x1(const X, Y, DrawWidth, DrawHeight: Single;
554 const SideRight, SideLeft: Integer);
555 procedure Draw3x1(const X, Y, DrawWidth, DrawHeight: Single;
556 const Side: TVector2Integer);
557 procedure Draw3x1(const ScreenRect: TRectangle;
558 const Side: TVector2Integer);
559 *)
560
561 { Color to multiply the texture contents (all RGBA channels).
562 By default this is White, which is (1, 1, 1, 1) as RGBA,
563 and it means that texture contents are not actually modified.
564 This case is also optimized when possible, to no multiplication will
565 actually happen.
566
567 When the color's alpha is < 1, then we automatically use blending,
568 if @link(Alpha) is acAuto (regardless of the image alpha channel, in this case).
569
570 Note that if you use TGrayscaleImage with TGrayscaleImage.TreatAsAlpha
571 (which means that texture does not contain any RGB information),
572 then only this color's RGB values determine the drawn RGB color. }
573 property Color: TCastleColor read FColor write SetColor;
574
575 { Load the given image contents.
576 Use this to efficiently replace the image contents on GPU.
577 Updates the @link(Width), @link(Height), @link(Alpha) to correspond
578 to new image.
579
580 It is valid (and reasonable) to call this with AImage instance equal
581 to the image instance that you used when creating this TDrawableImage.
582 That's because TDrawableImage @italic(does not) automatically update
583 the image contents (once they were loaded to GPU) when you change
584 the underlying @link(TEncodedImage) instance.
585
586 It is valid to pass @nil as parameter.
587
588 @italic(Do not call this method too often.) This methos copies
589 the image contents from @link(TEncodedImage) to GPU, which is not something
590 you want to do every frame. Doing this occasionally,
591 or during the loading/preparation stage, is OK.
592 Doing this often, e.g. during every @link(TCastleWindow.OnRender)
593 or @link(TCastleWindow.OnUpdate), will hurt your performance.
594 During the game, it's most efficient to treat the @link(TDrawableImage) instances
595 as "constant" -- avoid changing their contents, avoid creating new ones. }
596 procedure Load(const AImage: TEncodedImage); virtual;
597
598 { Prepare all the possible resources.
599 Since we may load OpenGL resources on-demand
600 (if the TDrawableImage instance was created when OpenGL context
601 was not available yet),
602 this method can be used to force loading OpenGL resources now (if possible).
603 This is only useful if you want to avoid slowdown when loading it later,
604 and prefer to do the loading now. }
605 procedure PrepareResources;
606
607 { Is the image scaling mode smooth (bilinear filtering)
608 or not (nearest-pixel filtering).
609 This is important if you draw the image
610 such that one image pixel does not perfectly fit one screen pixel.
611
612 If you will not ever do any scaling, then set
613 this to @false. It may cause minimally faster drawing,
614 and avoids any possible artifacts from bilinear filtering.
615
616 If you will do scaling, you usually want to set this to @true,
617 unless you deliberately want a pixelated look (for pixelart).
618
619 Note that switching this property after this object is constructed
620 is possible, but costly. }
621 property SmoothScaling: boolean read FSmoothScaling write SetSmoothScaling;
622
623 {$ifdef FPC}
624 property ScalingPossible: boolean read FSmoothScaling write SetSmoothScaling;
625 deprecated 'use SmoothScaling';
626
627 { X coordinate of the center of rotation. Value from 0 to 1. Default value 0.5. }
628 property CenterX: Single read GetCenterX write SetCenterX default 0.5;
629 deprecated 'use RotationCenter';
630
631 { Y coordinate of the center of rotation. Value from 0 to 1. Default value 0.5. }
632 property CenterY: Single read GetCenterY write SetCenterY default 0.5;
633 deprecated 'use RotationCenter';
634 {$endif}
635
636 { Center of rotation.
637 Expressed as a fraction within the drawn ScreenRectangle,
638 (0,0) means bottom-left corner, (1,1) means top-right corner.
639 Default (0.5,0.5). }
640 property RotationCenter: TVector2 read FRotationCenter write SetRotationCenter;
641
642 { Rotation in radians. Increase to rotate in a counter-clockwise direction.
643 Hint: use function like ArcTan2 from Math unit to convert 2D direction
644 into a rotation angle. }
645 property Rotation: Single
646 read FRotation write SetRotation {$ifdef FPC}default 0{$endif};
647
648 { Clip the image by an arbitrary 2D line defined in @link(ClipLine). }
649 property Clip: Boolean read FClip write SetClip;
650
651 { If @link(Clip), this is the line equation used to determine whether
652 we clip the given pixel. Given a line (A, B, C) and pixel (x, y),
653 the pixel is clipped (rejected) if @code(A * x + B * y + C < 0).
654
655 The line equation works in texture coordinates.
656 If the image is drawn complete on the screen,
657 texture coordinates span from (0,0) at bottom-left to (1,1) top-right.
658
659 For example ClipLine = (1, 0, -0.5) means that we reject pixels
660 where @code(1 * x + 0 * y - 0.5 < 0). In other words,
661 we reject pixels where @code(x < 0.5), so we reject
662 the left half of the image. }
663 property ClipLine: TVector3 read FClipLine write SetClipLine;
664
665 { Get the image contents from GPU to CPU.
666 @raises(ECannotSaveTextureContents If we cannot get texture contents
667 (not supported on OpenGLES).) }
668 function GetContents(const ImageClass: TCastleImageClass): TCastleImage;
669
670 { Internal OpenGL texture identifier.
671
672 You cannot free it (e.g. by glFreeTexture), and you cannot change it's
673 parameters (because TDrawableImage assumes it controls all the texture
674 parameters). For normal drawing, you do not need this (use @link(Draw)
675 or other rendering routines in this class), but it may be useful to
676 integrate with external rendering systems. }
677 property Texture: TGLTextureId read FTexture;
678
679 { Use a custom shader for image rendering.
680
681 The shader must define the same uniform variables and attributes
682 as the standard TDrawableImage shader, like viewport_size, vertex, tex_coord.
683 See for example our default shader code:
684 https://github.com/castle-engine/castle-engine/blob/master/src/images/opengl/glsl/source/image.vs
685 https://github.com/castle-engine/castle-engine/blob/master/src/images/opengl/glsl/source/image.fs .
686
687 See also example: examples/images_videos/image_render_custom_shader/ .
688
689 Note that some uniforms/attributes are only used in some cases.
690 For example, when TDrawableImage.Color is White (1, 1, 1, 1), then we don't pass "color" uniform.
691 When TDrawableImage.Clip is @false, then we don't pass "clip_line" uniform.
692 When assigning your custom shader, you take responsibility of setting
693 the shader that matches the current TDrawableImage properties.
694
695 You can (and should, if possible) reuse a single TGLSLProgram instance
696 for many TDrawableImage and TCastleImageControl instances
697 (as TDrawableImage.CustomShader and TCastleImageControl.CustomShader).
698 You can also use your own uniforms in your shader code, of course. }
699 property CustomShader: TGLSLProgram read FCustomShader write FCustomShader;
700
701 property Image: TEncodedImage read FImage write SetImage;
702 property OwnsImage: boolean read FOwnsImage write FOwnsImage;
703
704 { Start rendering to this image, using an efficient GPU method
705 ("Framebuffer Object", FBO).
706 Remember that the result lives only on GPU (the underlying TEncodedImage,
707 in normal RAM memory, is not updated by this drawing in any way).
708
709 Between @link(RenderToImageBegin) and @link(RenderToImageEnd)
710 you can use various rendering methods, like
711
712 @unorderedList(
713 @item(TDrawableImage.Draw (to draw @italic(other) TDrawableImage instances on this one),)
714 @item(DrawRectangle, DrawCircle, DrawPrimitive2D and friends in CastleGLUtils,)
715 @item(@link(TCastleContainer.RenderControl Window.Container.RenderControl)
716 to render any TCastleUserInterface to this image.)
717 )
718
719 Calling the RenderToImageBegin for the first time automatically
720 creates a TGLRenderToTexture descendant suitable for rendering to this texture.
721 It is automatically released on certain events,
722 you can also explicitly release it by @link(RenderToImageFree). }
723 procedure RenderToImageBegin(const SetAndRestoreViewport: boolean = true);
724 procedure RenderToImageEnd;
725 procedure RenderToImageFree;
726
727 { Draw a SourceImage over this image.
728
729 The drawing is done completely on GPU (using the @link(RenderToImageBegin)).
730 This is a much faster alternative to drawing using
731 @link(TCastleImage.DrawFrom) (that happens on CPU).
732 The result "lives" only on GPU (the underlying TEncodedImage,
733 in normal RAM memory, is not updated by this drawing in any way).
734
735 If you use this only occasionally, it's nice to later free the resources
736 by @link(RenderToImageFree). }
737 procedure DrawFrom(const SourceImage: TDrawableImage;
738 const DestinationRect, SourceRect: TFloatRectangle);
739
740 { URL of currently loaded image.
741 Non-empty only if the image was loaded from URL. }
742 property Url: String read FUrl write SetUrl;
743
744 { Repeat or clamp texture in S (width) or T (height) dimensions.
745 @groupBegin }
746 property RepeatS: Boolean read FRepeatS write SetRepeatS default false;
747 property RepeatT: Boolean read FRepeatT write SetRepeatT default false;
748 { @groupEnd }
749 end;
750
751 {$ifdef FPC}
752 TGLImageManaged = TDrawableImage deprecated 'use TDrawableImage';
753 TGLImageOnDemand = TDrawableImage deprecated 'use TDrawableImage';
754 TGLImageCore = TDrawableImage deprecated 'use TDrawableImage';
755 TGLImage = TDrawableImage deprecated 'use TDrawableImage';
756 {$endif}
757
758 {$endif read_interface_type}
759 {$endif read_interface}
760
761 {$ifdef read_implementation}
762
763 { TDrawableImage.TImageProgram ------------------------------------------------- }
764
765 procedure TDrawableImage.TImageProgram.InitializeUniformsAttributes(
766 const ClipLineShader: boolean;
767 const ColorTreatment: TColorTreatment);
768 begin
769 UniformViewportSize := Prog.Uniform('viewport_size');
770 if ColorTreatment <> ctPureTexture then
771 UniformColor := Prog.Uniform('color')
772 else
773 UniformColor := TGLSLUniform.NotExisting;
774 if ClipLineShader then
775 UniformClipLine := Prog.Uniform('clip_line')
776 else
777 UniformClipLine := TGLSLUniform.NotExisting;
778 AttribVertex := Prog.Attribute('vertex');
779 AttribTexCoord := Prog.Attribute('tex_coord');
780 end;
781
782 { TDrawableImage ------------------------------------------------------------------- }
783
784 constructor TDrawableImage.Create(const AImage: TEncodedImage;
785 const ASmoothScaling, AOwnsImage: boolean);
786 begin
787 inherited Create;
788
789 FColor := White;
790 FScaleCorners := 1;
791 FRotationCenter := Vector2(0.5, 0.5);
792 FRotation := 0;
793 { this sets CurrentFilter, that will be immediately used by Load }
794 FSmoothScaling := ASmoothScaling;
795 FImageAlpha := acNone;
796 FAlpha := acAuto;
797 FBlendingSourceFactor := DefaultBlendingSourceFactor;
798 FBlendingDestinationFactor := DefaultBlendingDestinationFactor;
799 FBlendingConstantColor := DefaultBlendingConstantColor;
800
801 Load(AImage);
802
803 // note that above Create will call virtual Load() which will already set our FImage
804 FOwnsImage := AOwnsImage;
805 ApplicationProperties.OnGLContextCloseObject.Add(
806 {$ifdef FPC}@{$endif} GLContextCloseEvent);
807 end;
808
809 constructor TDrawableImage.Create(const AUrl: String;
810 const ASmoothScaling: boolean);
811 begin
812 Create(AUrl, [], ASmoothScaling);
813 end;
814
815 constructor TDrawableImage.Create(const AUrl: String;
816 const LoadAsClass: array of TEncodedImageClass;
817 const ResizeToX, ResizeToY: Cardinal;
818 const Interpolation: TResizeInterpolation);
819 var
820 NewImage: TCastleImage;
821 begin
822 if High(LoadAsClass) = -1 then
823 NewImage := LoadImage(AUrl, PixelsImageClasses, ResizeToX, ResizeToY, Interpolation)
824 else
825 NewImage := LoadImage(AUrl, LoadAsClass, ResizeToX, ResizeToY, Interpolation);
826 FUrl := AUrl;
827 Create(NewImage, { ASmoothScaling } true, { AOwnsImage } true);
828 end;
829
830 constructor TDrawableImage.Create(const AUrl: String;
831 const LoadAsClass: array of TEncodedImageClass;
832 const ASmoothScaling: boolean);
833 var
834 NewImage: TEncodedImage;
835 begin
836 if High(LoadAsClass) = -1 then
837 NewImage := LoadEncodedImage(AUrl, PixelsImageClasses)
838 else
839 NewImage := LoadEncodedImage(AUrl, LoadAsClass);
840 FUrl := AUrl;
841 Create(NewImage, ASmoothScaling, { AOwnsImage } true);
842 end;
843
844 destructor TDrawableImage.Destroy;
845 begin
846 BatchingFlushIfNeeded;
847
848 if FOwnsImage then
849 FreeAndNil(FImage)
850 else
851 FImage := nil;
852
853 if ApplicationProperties <> nil then
854 ApplicationProperties.OnGLContextCloseObject.Remove(
855 {$ifdef FPC}@{$endif} GLContextCloseEvent);
856
857 RenderToImageFree;
858 GLContextClose;
859 inherited;
860 end;
861
862 procedure TDrawableImage.SetImage(const AImage: TEncodedImage);
863 begin
864 { exactly like Load(), but can ignore the call if AImage reference
865 is already set.
866 Load() should not do it, to allow loading the same AImage reference
867 in case AImage contents change. }
868 if FImage <> AImage then
869 Load(AImage);
870 end;
871
872 procedure TDrawableImage.GLContextOpen(const AImage: TEncodedImage);
873 begin
874 if AImage <> nil then
875 begin
876 if FTexture = 0 then
877 glGenTextures(1, @FTexture);
878 LoadGLGeneratedTexture(FTexture, AImage, CurrentFilter,
879 CurrentWrap, nil, true);
880 end;
881 end;
882
883 procedure TDrawableImage.GLContextClose;
884 begin
885 glFreeTexture(FTexture);
886 end;
887
888 procedure TDrawableImage.Load(const AImage: TEncodedImage);
889 begin
890 BatchingFlushIfNeeded;
891
892 if FOwnsImage and (FImage <> AImage) then
893 FreeAndNil(FImage)
894 else
895 FImage := nil;
896
897 if AImage <> nil then
898 begin
899 FWidth := AImage.Width;
900 FHeight := AImage.Height;
901 FImageAlpha := AImage.AlphaChannel;
902 end else
903 begin
904 FWidth := 0;
905 FHeight := 0;
906 FImageAlpha := acNone;
907 end;
908
909 { calculate TextureHasOnlyAlpha, useful only for GLSL image rendering }
910 TextureHasOnlyAlpha :=
911 (AImage <> nil) and
912 (AImage is TGrayscaleImage) and
913 (TGrayscaleImage(AImage).TreatAsAlpha);
914
915 if ApplicationProperties.IsGLContextOpen then
916 begin
917 GLContextOpen(AImage);
918 StaticGLContextOpen;
919 end;
920
921 FImage := AImage;
922 end;
923
924 class procedure TDrawableImage.StaticGLContextOpen;
925 var
926 AlphaTestShader, ClipLineShader: boolean;
927 ColorTreatment: TColorTreatment;
928 NewProgram: TImageProgram;
929 VS, FS: string;
930 I: Integer;
931 begin
932 if not GLFeatures.EnableFixedFunction then
933 begin
934 for I := Low(VboStorage) to High(VboStorage) do
935 begin
936 if VboStorage[I].PointsVbo = 0 then
937 glGenBuffers(1, @VboStorage[I].PointsVbo);
938 if VboStorage[I].IndexesVbo = 0 then
939 glGenBuffers(1, @VboStorage[I].IndexesVbo);
940 if VboStorage[I].Vao = nil then
941 VboStorage[I].Vao := TVertexArrayObject.Create(nil);
942 end;
943
944 { create programs }
945 for AlphaTestShader := Low(boolean) to High(boolean) do
946 for ClipLineShader := Low(boolean) to High(boolean) do
947 for ColorTreatment := Low(TColorTreatment) to High(TColorTreatment) do
948 if Programs[AlphaTestShader, ClipLineShader, ColorTreatment].Prog = nil then
949 begin
950 VS := Iff(ClipLineShader, '#define CLIP_LINE' + NL, '') +
951 {$I image.vs.inc};
952 FS := Iff(AlphaTestShader, '#define ALPHA_TEST' + NL, '') +
953 Iff(ClipLineShader, '#define CLIP_LINE' + NL, '') +
954 Iff(ColorTreatment in [ctColorMultipliesTexture, ctColorMultipliesTextureAlpha], '#define COLOR_UNIFORM' + NL, '') +
955 Iff(ColorTreatment = ctColorMultipliesTextureAlpha, '#define TEXTURE_HAS_ONLY_ALPHA' + NL, '') +
956 {$I image.fs.inc};
957
958 NewProgram.Prog := TGLSLProgram.Create;
959 NewProgram.Prog.Name := 'TDrawableImage';
960 NewProgram.Prog.AttachVertexShader(VS);
961 NewProgram.Prog.AttachFragmentShader(FS);
962 NewProgram.Prog.Link;
963 NewProgram.InitializeUniformsAttributes(ClipLineShader, ColorTreatment);
964
965 Programs[AlphaTestShader, ClipLineShader, ColorTreatment] := NewProgram;
966 end;
967 end;
968
969 StaticResourcesReady := true;
970 end;
971
972 class procedure TDrawableImage.StaticGLContextClose;
973 var
974 AlphaTestShader, ClipLineShader: boolean;
975 ColorTreatment: TDrawableImage.TColorTreatment;
976 I: Integer;
977 begin
978 for I := Low(VboStorage) to High(VboStorage) do
979 begin
980 glFreeBuffer(VboStorage[I].PointsVbo);
981 glFreeBuffer(VboStorage[I].IndexesVbo);
982 FreeAndNil(VboStorage[I].Vao);
983 VboStorage[I].PointsVboSize := 0;
984 VboStorage[I].IndexesVboSize := 0;
985 end;
986
987 { Free below regardless of GLFeatures.EnableFixedFunction,
988 in case user toggles GLFeatures.EnableFixedFunction at runtime.
989 Note: This robustness is not really unnecessary now,
990 as GLFeatures.EnableFixedFunction and TGLFeatures.RequestCapabilities
991 cannot change once GL context is initialized. }
992 //if not GLFeatures.EnableFixedFunction then
993 for AlphaTestShader := Low(boolean) to High(boolean) do
994 for ClipLineShader := Low(boolean) to High(boolean) do
995 for ColorTreatment := Low(TColorTreatment) to High(TColorTreatment) do
996 FreeAndNil(Programs[AlphaTestShader, ClipLineShader, ColorTreatment].Prog);
997
998 StaticResourcesReady := false;
999 end;
1000
1001 function TDrawableImage.FinalAlpha: TAlphaChannel;
1002 begin
1003 if FAlpha = acAuto then
1004 begin
1005 Result := FImageAlpha;
1006 if FColor[3] < 1 then
1007 Result := acBlending;
1008 end else
1009 Result := FAlpha;
1010 end;
1011
1012 procedure TDrawableImage.Draw(const X, Y: Single);
1013 begin
1014 Draw(
1015 FloatRectangle(X, Y, Width, Height),
1016 FloatRectangle(0, 0, Width, Height));
1017 end;
1018
1019 procedure TDrawableImage.Draw(const X, Y, DrawWidth, DrawHeight: Single);
1020 begin
1021 Draw(
1022 FloatRectangle(X, Y, DrawWidth, DrawHeight),
1023 FloatRectangle(0, 0, Width, Height));
1024 end;
1025
1026 procedure TDrawableImage.Draw(const Pos: TVector2Integer);
1027 begin
1028 Draw(
1029 FloatRectangle(Pos[0], Pos[1], Width, Height),
1030 FloatRectangle(0, 0, Width, Height));
1031 end;
1032
1033 procedure TDrawableImage.Draw(const X, Y, DrawWidth, DrawHeight: Single;
1034 const ImageX, ImageY, ImageWidth, ImageHeight: Single);
1035 begin
1036 Draw(
1037 FloatRectangle(X, Y, DrawWidth, DrawHeight),
1038 FloatRectangle(ImageX, ImageY, ImageWidth, ImageHeight));
1039 end;
1040
1041 procedure TDrawableImage.Draw(const ScreenRect: TRectangle);
1042 begin
1043 Draw(
1044 FloatRectangle(ScreenRect),
1045 FloatRectangle(0, 0, Width, Height));
1046 end;
1047
1048 procedure TDrawableImage.Draw(const ScreenRect: TFloatRectangle);
1049 begin
1050 Draw(
1051 ScreenRect,
1052 FloatRectangle(0, 0, Width, Height));
1053 end;
1054
1055 procedure TDrawableImage.Draw(const ScreenRect: TRectangle;
1056 const ImageX, ImageY, ImageWidth, ImageHeight: Single);
1057 begin
1058 Draw(
1059 FloatRectangle(ScreenRect),
1060 FloatRectangle(ImageX, ImageY, ImageWidth, ImageHeight));
1061 end;
1062
1063 procedure TDrawableImage.Draw(const ScreenRect, ImageRect: TRectangle);
1064 begin
1065 Draw(
1066 FloatRectangle(ScreenRect),
1067 FloatRectangle(ImageRect));
1068 end;
1069
1070 procedure TDrawableImage.Draw(const ScreenRect, ImageRect: TFloatRectangle);
1071 begin
1072 Draw(@ScreenRect, @ImageRect, 1);
1073 end;
1074
1075 procedure TDrawableImage.Draw(
1076 ScreenRects, ImageRects: PFloatRectangleArray; Count: Integer);
1077 var
1078 { Must be PFloatRectangle, not PFloatRectangleArray,
1079 because we will increment them to advance to next. }
1080 SrPtr, IrPtr: PFloatRectangle;
1081 begin
1082 Inc(Statistics.ImageDraws);
1083
1084 if BatchingLevel <> 0 then
1085 begin
1086 if (BatchingLastImage <> nil) and (BatchingLastImage <> Self) then
1087 BatchingFlush; // will change BatchingLastImage to nil
1088 if BatchingLastImage = nil then
1089 begin
1090 Assert(BatchingLastScreenRects.Count = 0);
1091 Assert(BatchingLastImageRects.Count = 0);
1092 BatchingLastImage := Self;
1093 end;
1094 // add to last batch
1095 if BatchingLastImage = Self then
1096 begin
1097 SrPtr := PFloatRectangle(ScreenRects);
1098 IrPtr := PFloatRectangle(ImageRects);
1099 while Count > 0 do
1100 begin
1101 BatchingLastScreenRects.Add(SrPtr^);
1102 BatchingLastImageRects.Add(IrPtr^);
1103 Inc(SrPtr);
1104 Inc(IrPtr);
1105 Dec(Count);
1106 end;
1107 end;
1108 end else
1109 DrawNoBatch(ScreenRects, ImageRects, Count);
1110 end;
1111
1112 procedure TDrawableImage.DrawNoBatch(
1113 const ScreenRects, ImageRects: PFloatRectangleArray; const Count: Integer);
1114
1115 procedure AlphaBegin;
1116 begin
1117 case FinalAlpha of
1118 acTest: RenderContext.FixedFunctionAlphaTestEnable;
1119 acBlending:
1120 begin
1121 if GLFeatures.BlendConstant and
1122 ( (BlendingSourceFactor in
1123 [bsConstantColor, bsOneMinusConstantColor,
1124 bsConstantAlpha, bsOneMinusConstantAlpha]) or
1125 (BlendingDestinationFactor in
1126 [bdConstantColor, bdOneMinusConstantColor,
1127 bdConstantAlpha, bdOneMinusConstantAlpha]) ) then
1128 begin
1129 glBlendColor(
1130 BlendingConstantColor[0],
1131 BlendingConstantColor[1],
1132 BlendingConstantColor[2],
1133 BlendingConstantColor[3]);
1134 end;
1135
1136 RenderContext.BlendingEnable(BlendingSourceFactor, BlendingDestinationFactor);
1137 end;
1138 else ;
1139 end;
1140 end;
1141
1142 procedure AlphaEnd;
1143 begin
1144 case FinalAlpha of
1145 acTest: RenderContext.FixedFunctionAlphaTestDisable;
1146 acBlending: RenderContext.BlendingDisable;
1147 else ;
1148 end;
1149 end;
1150
1151 var
1152 Shift: TVector2;
1153
1154 { Rotate Point by Rotation radians around Shift. }
1155 function RotatePoint2DAroundShift(const Point: TVector2): TVector2;
1156 begin
1157 Result := RotatePoint2D(Point - Shift, Rotation) + Shift;
1158 end;
1159
1160 procedure SetupQuadPoints(const ScreenRect, ImageRect: TFloatRectangle;
1161 QuadPoints: PPointArray);
1162 var
1163 TexX0, TexY0, TexX1, TexY1: Single;
1164 X0, Y0, X1, Y1: Single;
1165 begin
1166 TexX0 := ImageRect.Left / Width;
1167 TexY0 := ImageRect.Bottom / Height;
1168 TexX1 := (ImageRect.Left + ImageRect.Width ) / Width;
1169 TexY1 := (ImageRect.Bottom + ImageRect.Height) / Height;
1170
1171 X0 := ScreenRect.Left;
1172 Y0 := ScreenRect.Bottom;
1173 X1 := ScreenRect.Left + ScreenRect.Width;
1174 Y1 := ScreenRect.Bottom + ScreenRect.Height;
1175
1176 QuadPoints^[0].TexCoord := Vector2(TexX0, TexY0);
1177 QuadPoints^[0].Position := Vector2(X0, Y0);
1178 QuadPoints^[1].TexCoord := Vector2(TexX1, TexY0);
1179 QuadPoints^[1].Position := Vector2(X1, Y0);
1180 QuadPoints^[2].TexCoord := Vector2(TexX1, TexY1);
1181 QuadPoints^[2].Position := Vector2(X1, Y1);
1182 QuadPoints^[3].TexCoord := Vector2(TexX0, TexY1);
1183 QuadPoints^[3].Position := Vector2(X0, Y1);
1184
1185 if FRotation <> 0 then
1186 begin
1187 if UseScreenRotationCenter then
1188 begin
1189 Shift := ScreenRotationCenter;
1190 end else
1191 begin
1192 Shift := Vector2(
1193 ScreenRect.Left + FRotationCenter.X * ScreenRect.Width,
1194 ScreenRect.Bottom + FRotationCenter.Y * ScreenRect.Height);
1195 end;
1196 QuadPoints^[0].Position := RotatePoint2DAroundShift(QuadPoints^[0].Position);
1197 QuadPoints^[1].Position := RotatePoint2DAroundShift(QuadPoints^[1].Position);
1198 QuadPoints^[2].Position := RotatePoint2DAroundShift(QuadPoints^[2].Position);
1199 QuadPoints^[3].Position := RotatePoint2DAroundShift(QuadPoints^[3].Position);
1200 end;
1201 end;
1202
1203 { Bind the given buffer and update contents. }
1204 procedure LoadBuffer(const Target: TBufferTarget;
1205 const Vbo: TGLuint; var VboCurrentSize: Cardinal;
1206 const ContentsPtr: Pointer; const ContentsSize: Cardinal);
1207 var
1208 TargetGL: TGLenum;
1209 begin
1210 RenderContext.BindBuffer[Target] := Vbo;
1211 TargetGL := BufferTargetGL[Target];
1212 { Try using glBufferSubData if possible, manual suggests it's better
1213 than repeatedly calling glBufferData.
1214 The VBO size will only increase this way, but this is probably OK,
1215 it's a single VBO for all our UI stuff. }
1216 if VboCurrentSize < ContentsSize then
1217 begin
1218 glBufferData(TargetGL, ContentsSize, ContentsPtr, GL_DYNAMIC_DRAW);
1219 VboCurrentSize := ContentsSize;
1220 end else
1221 glBufferSubData(TargetGL, 0, ContentsSize, ContentsPtr);
1222 end;
1223
1224 const
1225 IndexesPerQuad = 6;
1226 var
1227 ColorTreatment: TColorTreatment;
1228 Prog: TImageProgram;
1229 I: Integer;
1230 Vbo: PVboStorage;
1231 IndexPtr: Pointer;
1232 UseIndex: Boolean;
1233 begin
1234 if (Count = 0) or
1235 ((Count = 1) and
1236 ((ScreenRects^[0].Width = 0) or
1237 (ScreenRects^[0].Height = 0))) then
1238 Exit;
1239
1240 FrameProfiler.Start(fmDrawImage);
1241
1242 // we load on demand, so do PrepareResources always
1243 PrepareResources;
1244 // PrepareResources, done while GL context is active, must make it true
1245 Assert(FTexture <> 0);
1246 Assert(StaticResourcesReady);
1247
1248 if GLFeatures.UseMultiTexturing then glActiveTexture(GL_TEXTURE0);
1249 glBindTexture(GL_TEXTURE_2D, FTexture);
1250 GLEnableTexture(et2D);
1251
1252 { calculate Indexes contents, only used when Count <> 1 }
1253 UseIndex := Count <> 1;
1254 if UseIndex then
1255 begin
1256 {$ifdef GLIndexesShort}
1257 if Integer(Count - 1) * IndexesPerQuad + IndexesPerQuad - 1 > High(Word) then
1258 raise Exception.CreateFmt('Maximum index value is larger than %d (max 16-bit unsigned integer). Split your rendering into more shapes (draw calls). Or undefine GLIndexesShort in castleconf.inc to be able to render your data (but beware that it may fail on some buggy Android devices).', [High(Word)]);
1259 {$endif}
1260 SetLength(Indexes, Count * IndexesPerQuad);
1261 for I := 0 to Count - 1 do
1262 begin
1263 { 1st triangle of quad }
1264 Indexes[I * IndexesPerQuad ] := I * 4;
1265 Indexes[I * IndexesPerQuad + 1] := I * 4 + 1;
1266 Indexes[I * IndexesPerQuad + 2] := I * 4 + 2;
1267 { 2nd triangle of quad }
1268 Indexes[I * IndexesPerQuad + 3] := I * 4;
1269 Indexes[I * IndexesPerQuad + 4] := I * 4 + 2;
1270 Indexes[I * IndexesPerQuad + 5] := I * 4 + 3;
1271 end;
1272 end;
1273
1274 { calculate Point contents }
1275 SetLength(Points, Count * 4);
1276 for I := 0 to Count - 1 do
1277 SetupQuadPoints(ScreenRects^[I], ImageRects^[I], @Points[I * 4]);
1278
1279 AlphaBegin;
1280
1281 if not GLFeatures.EnableFixedFunction then
1282 begin
1283 // initialize VBO
1284 Vbo := @VboStorage[VboStorageNext];
1285 Inc(VboStorageNext);
1286 if VboStorageNext = High(VboStorage) + 1 then
1287 VboStorageNext := 0;
1288
1289 { VAO must be bound before binding VBOs,
1290 esp. important for GL_ELEMENT_ARRAY_BUFFER whose VBO isn't bound later. }
1291 RenderContext.CurrentVao := Vbo^.Vao;
1292
1293 LoadBuffer(btArray, Vbo^.PointsVbo, Vbo^.PointsVboSize,
1294 @Points[0], Length(Points) * SizeOf(TPoint));
1295
1296 if UseIndex then
1297 LoadBuffer(btElementArray, Vbo^.IndexesVbo, Vbo^.IndexesVboSize,
1298 @Indexes[0], Length(Indexes) * SizeOf(Indexes[0]));
1299
1300 // initialize shaders
1301
1302 if TextureHasOnlyAlpha then
1303 ColorTreatment := ctColorMultipliesTextureAlpha else
1304 if not TCastleColor.PerfectlyEquals(Color, White) then
1305 ColorTreatment := ctColorMultipliesTexture else
1306 ColorTreatment := ctPureTexture;
1307
1308 if CustomShader <> nil then
1309 begin
1310 Prog.Prog := CustomShader;
1311 Prog.InitializeUniformsAttributes(Clip, ColorTreatment);
1312 end else
1313 Prog := Programs[FinalAlpha = acTest, Clip, ColorTreatment];
1314
1315 RenderContext.CurrentProgram := Prog.Prog;
1316 Prog.AttribVertex.EnableArrayVector2(
1317 Vbo^.Vao, SizeOf(TPoint), OffsetUInt(Points[0].Position, Points[0]));
1318 Prog.AttribTexCoord.EnableArrayVector2(
1319 Vbo^.Vao, SizeOf(TPoint), OffsetUInt(Points[0].TexCoord, Points[0]));
1320
1321 if (RenderContext.Viewport.Left <> 0) or
1322 (RenderContext.Viewport.Bottom <> 0) then
1323 WritelnWarning('Drawing TDrawableImage when viewport (left,bottom) is not (0,0) is undefined now');
1324 Prog.UniformViewportSize.SetValue(Vector2(
1325 RenderContext.Viewport.Width,
1326 RenderContext.Viewport.Height));
1327
1328 if ColorTreatment <> ctPureTexture then
1329 Prog.UniformColor.SetValue(Color);
1330 if Clip then
1331 Prog.UniformClipLine.SetValue(ClipLine);
1332 end else
1333 begin
1334 {$ifndef OpenGLES}
1335 Assert(RenderContext.CurrentProgram = nil); // when EnableFixedFunction, this should always stay nil
1336 glLoadIdentity();
1337 glColorv(Color);
1338
1339 glEnableClientState(GL_VERTEX_ARRAY);
1340 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1341 glVertexPointer (2, GL_FLOAT, SizeOf(TPoint), @(Points[0].Position));
1342 glTexCoordPointer(2, GL_FLOAT, SizeOf(TPoint), @(Points[0].TexCoord));
1343
1344 if Clip then
1345 begin
1346 { TODO: Clip not implemented in this case yet.
1347 Need to transform ClipLine into screen coordinates, then do
1348 glEnable(GL_CLIP_PLANE0);
1349 CastleGlClipPlane(GL_CLIP_PLANE0, Vector4Double(
1350 FScreenClipLine[0], FScreenClipLine[1], 0, FScreenClipLine[2]));
1351 }
1352 end;
1353 {$endif not OpenGLES}
1354 end;
1355
1356 Inc(Statistics.DrawCalls);
1357
1358 if UseIndex then
1359 begin
1360 if not GLFeatures.EnableFixedFunction then
1361 IndexPtr := nil
1362 else
1363 IndexPtr := @Indexes[0];
1364 glDrawElements(GL_TRIANGLES, Length(Indexes), GLIndexConst, IndexPtr);
1365 end else
1366 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1367
1368 if not GLFeatures.EnableFixedFunction then
1369 begin
1370 // Prog.Prog.Disable; // not necessary, and may give some speed gain if the next drawing call will also use TDrawableImage
1371 { attribute arrays are enabled independent from GLSL program, so we need
1372 to disable them separately }
1373 Prog.AttribVertex.DisableArray;
1374 Prog.AttribTexCoord.DisableArray;
1375
1376 RenderContext.BindBuffer[btArray] := 0;
1377 if UseIndex then // optimize out glBindBuffer call when not necessary
1378 RenderContext.BindBuffer[btElementArray] := 0;
1379 end else
1380 begin
1381 {$ifndef OpenGLES}
1382 { TODO: Clip not implemented in this case yet.
1383 if Clip then
1384 glDisable(GL_CLIP_PLANE0);
1385 }
1386 glDisableClientState(GL_VERTEX_ARRAY);
1387 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1388
1389 GLEnableTexture(etNone);
1390 {$endif not OpenGLES}
1391 end;
1392
1393 AlphaEnd;
1394
1395 FrameProfiler.Stop(fmDrawImage);
1396 end;
1397
1398 procedure TDrawableImage.DrawFlipped(const ScreenRect: TRectangle;
1399 const FlipHorizontal, FlipVertical: boolean);
1400 begin
1401 DrawFlipped(FloatRectangle(ScreenRect), FlipHorizontal, FlipVertical);
1402 end;
1403
1404 procedure TDrawableImage.DrawFlipped(const ScreenRect: TFloatRectangle;
1405 const FlipHorizontal, FlipVertical: boolean);
1406 begin
1407 DrawFlipped(ScreenRect, FloatRectangle(Rect), FlipHorizontal, FlipVertical);
1408 end;
1409
1410 procedure TDrawableImage.DrawFlipped(
1411 const ScreenRect: TFloatRectangle; ImageRect: TFloatRectangle;
1412 const FlipHorizontal, FlipVertical: boolean);
1413 begin
1414 if FlipHorizontal then
1415 begin
1416 ImageRect.Left := ImageRect.Left + ImageRect.Width;
1417 ImageRect.Width := -ImageRect.Width;
1418 end;
1419
1420 if FlipVertical then
1421 begin
1422 ImageRect.Bottom := ImageRect.Bottom + ImageRect.Height;
1423 ImageRect.Height := -ImageRect.Height;
1424 end;
1425
1426 Draw(ScreenRect, ImageRect);
1427 end;
1428
1429 procedure TDrawableImage.Draw3x3(const X, Y, DrawWidth, DrawHeight: Single;
1430 CornerTop, CornerRight, CornerBottom, CornerLeft: Single;
1431 ImageLeft: Single = 0; ImageBottom: Single = 0;
1432 ImageWidth: Single = -1; ImageHeight: Single = -1);
1433 var
1434 ScreenRects, ImageRects: packed array [0..8] of TFloatRectangle;
1435 DrawAddCount: Cardinal;
1436
1437 { Add the quad to draw to ScreenRects, ImageRects.
1438 This looks and behaves like TDrawableImage.Draw,
1439 but the actual drawing is delayed to later. }
1440 procedure DrawAdd(const X, Y, DrawWidth, DrawHeight: Single;
1441 const ImageX, ImageY, ImageWidth, ImageHeight: Single);
1442 begin
1443 ScreenRects[DrawAddCount] := FloatRectangle(X, Y, DrawWidth, DrawHeight);
1444 ImageRects[DrawAddCount] := FloatRectangle(ImageX, ImageY, ImageWidth, ImageHeight);
1445 Inc(DrawAddCount);
1446 end;
1447
1448 { Make A + B <= Max.
1449 If A + B are too large, decrease them, but preserving A to B ratio.
1450 In effect e.g.
1451 A = 10, B = 100, MaxSize = 1
1452 ->
1453 A := 1/11, B = 10/11
1454 }
1455 procedure FitWithin(var A, B: Single; const Max: Single);
1456 begin
1457 if A + B > Max then
1458 begin
1459 A := Max * A / (A + B);
1460 B := Max * B / (A + B);
1461 end;
1462 end;
1463
1464 var
1465 XScreenLeft, XScreenRight, YScreenBottom, YScreenTop,
1466 HorizontalScreenSize, VerticalScreenSize: Single;
1467 XImageLeft, XImageRight, YImageBottom, YImageTop,
1468 HorizontalImageSize, VerticalImageSize: Single;
1469 EpsilonT, EpsilonR, EpsilonB, EpsilonL: Single;
1470 DrawCornerTop, DrawCornerRight, DrawCornerBottom, DrawCornerLeft: Single;
1471
1472 { We tweak texture coordinates a little, to avoid bilinear filtering
1473 that would cause border colors to "bleed" over the texture inside.
1474 Something minimally > 0.5 is necessary when SmoothScaling. }
1475 Epsilon: Single;
1476 begin
1477 if SmoothScaling then Epsilon := 0.51 else Epsilon := 0.01;
1478
1479 { Just like TFloatRectangle.IsEmpty, if any size is < 0 then this is
1480 empty rectangle, and just like TCastleImagePersistent we treat it
1481 as "draw whole image". }
1482 if (ImageWidth < 0) or (ImageHeight < 0) then
1483 begin
1484 ImageLeft := 0;
1485 ImageBottom := 0;
1486 ImageWidth := Width;
1487 ImageHeight := Height;
1488 end;
1489
1490 FitWithin(CornerLeft, CornerRight, ImageWidth);
1491 FitWithin(CornerBottom, CornerTop, ImageHeight);
1492
1493 DrawCornerTop := CornerTop * ScaleCorners;
1494 DrawCornerRight := CornerRight * ScaleCorners;
1495 DrawCornerBottom := CornerBottom * ScaleCorners;
1496 DrawCornerLeft := CornerLeft * ScaleCorners;
1497
1498 FitWithin(DrawCornerLeft, DrawCornerRight, DrawWidth);
1499 FitWithin(DrawCornerBottom, DrawCornerTop, DrawHeight);
1500
1501 XScreenLeft := X;
1502 XImageLeft := ImageLeft;
1503 XScreenRight := X + DrawWidth - DrawCornerRight;
1504 XImageRight := ImageLeft + ImageWidth - CornerRight;
1505
1506 YScreenBottom := Y;
1507 YImageBottom := ImageBottom;
1508 YScreenTop := Y + DrawHeight - DrawCornerTop;
1509 YImageTop := ImageBottom + ImageHeight - CornerTop;
1510
1511 { setup rotations }
1512 if Rotation <> 0 then
1513 begin
1514 UseScreenRotationCenter := true; // only temporary for this Draw3x3 call
1515 ScreenRotationCenter := Vector2(
1516 X + FRotationCenter.X * DrawWidth,
1517 Y + FRotationCenter.Y * DrawHeight);
1518 end;
1519
1520 DrawAddCount := 0;
1521
1522 { 4 corners }
1523 DrawAdd(XScreenLeft, YScreenBottom, DrawCornerLeft, DrawCornerBottom,
1524 XImageLeft, YImageBottom, CornerLeft, CornerBottom);
1525 DrawAdd(XScreenRight, YScreenBottom, DrawCornerRight, DrawCornerBottom,
1526 XImageRight, YImageBottom, CornerRight, CornerBottom);
1527 DrawAdd(XScreenRight, YScreenTop, DrawCornerRight, DrawCornerTop,
1528 XImageRight, YImageTop, CornerRight, CornerTop);
1529 DrawAdd(XScreenLeft, YScreenTop, DrawCornerLeft, DrawCornerTop,
1530 XImageLeft, YImageTop, CornerLeft, CornerTop);
1531
1532 { 4 sides }
1533 HorizontalScreenSize := DrawWidth - DrawCornerLeft - DrawCornerRight;
1534 HorizontalImageSize := ImageWidth - CornerLeft - CornerRight;
1535 VerticalScreenSize := DrawHeight - DrawCornerTop - DrawCornerBottom;
1536 VerticalImageSize := ImageHeight - CornerTop - CornerBottom;
1537
1538 DrawAdd(XScreenLeft + DrawCornerLeft, YScreenBottom, HorizontalScreenSize, DrawCornerBottom,
1539 XImageLeft + CornerLeft, YImageBottom, HorizontalImageSize, CornerBottom);
1540 DrawAdd(XScreenLeft + DrawCornerLeft, YScreenTop, HorizontalScreenSize, DrawCornerTop,
1541 XImageLeft + CornerLeft, YImageTop, HorizontalImageSize, CornerTop);
1542
1543 DrawAdd(XScreenLeft, YScreenBottom + DrawCornerBottom, DrawCornerLeft, VerticalScreenSize,
1544 XImageLeft, YImageBottom + CornerBottom, CornerLeft, VerticalImageSize);
1545 DrawAdd(XScreenRight, YScreenBottom + DrawCornerBottom, DrawCornerRight, VerticalScreenSize,
1546 XImageRight, YImageBottom + CornerBottom, CornerRight, VerticalImageSize);
1547
1548 { inside }
1549 if CornerLeft > 0 then EpsilonL := Epsilon else EpsilonL := 0;
1550 if CornerTop > 0 then EpsilonT := Epsilon else EpsilonT := 0;
1551 if CornerRight > 0 then EpsilonR := Epsilon else EpsilonR := 0;
1552 if CornerBottom > 0 then EpsilonB := Epsilon else EpsilonB := 0;
1553
1554 DrawAdd( X + DrawCornerLeft , Y + DrawCornerBottom , HorizontalScreenSize, VerticalScreenSize,
1555 ImageLeft + CornerLeft + EpsilonL, ImageBottom + CornerBottom + EpsilonB, HorizontalImageSize - (EpsilonL+EpsilonR), VerticalImageSize - (EpsilonT+EpsilonB));
1556
1557 Assert(DrawAddCount = 9);
1558 Draw(@ScreenRects, @ImageRects, 9);
1559
1560 UseScreenRotationCenter := false;
1561 end;
1562
1563 procedure TDrawableImage.Draw3x3(const X, Y, DrawWidth, DrawHeight: Single;
1564 const Corner: TVector4Integer; const ImageRect: TFloatRectangle);
1565 begin
1566 Draw3x3(X, Y, DrawWidth, DrawHeight,
1567 Corner[0], Corner[1], Corner[2], Corner[3],
1568 ImageRect.Left, ImageRect.Bottom, ImageRect.Width, ImageRect.Height);
1569 end;
1570
1571 procedure TDrawableImage.Draw3x3(const ScreenRect: TRectangle;
1572 const Corner: TVector4Integer; const ImageRect: TFloatRectangle);
1573 begin
1574 Draw3x3(ScreenRect.Left, ScreenRect.Bottom,
1575 ScreenRect.Width, ScreenRect.Height,
1576 Corner[0], Corner[1], Corner[2], Corner[3],
1577 ImageRect.Left, ImageRect.Bottom, ImageRect.Width, ImageRect.Height);
1578 end;
1579
1580 procedure TDrawableImage.Draw3x3(const ScreenRect: TFloatRectangle;
1581 const Corner: TVector4Integer; const ImageRect: TFloatRectangle);
1582 begin
1583 Draw3x3(ScreenRect.Left, ScreenRect.Bottom,
1584 ScreenRect.Width, ScreenRect.Height,
1585 Corner[0], Corner[1], Corner[2], Corner[3],
1586 ImageRect.Left, ImageRect.Bottom, ImageRect.Width, ImageRect.Height);
1587 end;
1588
1589 procedure TDrawableImage.Draw3x3(const ScreenRect: TFloatRectangle;
1590 const Corner: TVector4; const ImageRect: TFloatRectangle);
1591 begin
1592 Draw3x3(ScreenRect.Left, ScreenRect.Bottom,
1593 ScreenRect.Width, ScreenRect.Height,
1594 Corner[0], Corner[1], Corner[2], Corner[3],
1595 ImageRect.Left, ImageRect.Bottom, ImageRect.Width, ImageRect.Height);
1596 end;
1597
1598 procedure TDrawableImage.Draw3x3(const X, Y, DrawWidth, DrawHeight: Single;
1599 const Corner: TVector4Integer);
1600 begin
1601 Draw3x3(X, Y, DrawWidth, DrawHeight,
1602 Corner[0], Corner[1], Corner[2], Corner[3]);
1603 end;
1604
1605 procedure TDrawableImage.Draw3x3(const ScreenRect: TRectangle;
1606 const Corner: TVector4Integer);
1607 begin
1608 Draw3x3(ScreenRect.Left, ScreenRect.Bottom,
1609 ScreenRect.Width, ScreenRect.Height,
1610 Corner[0], Corner[1], Corner[2], Corner[3]);
1611 end;
1612
1613 procedure TDrawableImage.Draw3x3(const ScreenRect: TFloatRectangle;
1614 const Corner: TVector4Integer);
1615 begin
1616 Draw3x3(ScreenRect.Left, ScreenRect.Bottom,
1617 ScreenRect.Width, ScreenRect.Height,
1618 Corner[0], Corner[1], Corner[2], Corner[3]);
1619 end;
1620
1621 procedure TDrawableImage.Draw3x3(const ScreenRect: TFloatRectangle;
1622 const Corner: TVector4);
1623 begin
1624 Draw3x3(ScreenRect.Left, ScreenRect.Bottom,
1625 ScreenRect.Width, ScreenRect.Height,
1626 Corner[0], Corner[1], Corner[2], Corner[3]);
1627 end;
1628
1629 function TDrawableImage.CurrentFilter: TTextureFilter;
1630 begin
1631 if SmoothScaling then
1632 begin
1633 Result.Minification := minLinear;
1634 Result.Magnification := magLinear;
1635 end else
1636 begin
1637 Result.Minification := minNearest;
1638 Result.Magnification := magNearest;
1639 end;
1640 end;
1641
1642 function TDrawableImage.CurrentWrap: TTextureWrap2D;
1643
1644 function RepeatToGL(const IsRepeat: Boolean): TGLenum;
1645 begin
1646 if IsRepeat then
1647 Result := GL_REPEAT
1648 else
1649 Result := GLFeatures.CLAMP_TO_EDGE;
1650 end;
1651
1652 begin
1653 Result.Data[0] := RepeatToGL(RepeatS);
1654 Result.Data[1] := RepeatToGL(RepeatT);
1655 end;
1656
1657 procedure TDrawableImage.SetSmoothScaling(const Value: boolean);
1658 begin
1659 if FSmoothScaling <> Value then
1660 begin
1661 BatchingFlushIfNeeded;
1662 FSmoothScaling := Value;
1663 if FTexture <> 0 then
1664 begin
1665 glBindTexture(GL_TEXTURE_2D, FTexture);
1666 SetTextureFilter(GL_TEXTURE_2D, CurrentFilter);
1667 end;
1668 end;
1669 end;
1670
1671 function TDrawableImage.Rect: TRectangle;
1672 begin
1673 Result := Rectangle(0, 0, Width, Height);
1674 end;
1675
1676 procedure TDrawableImage.PrepareResources;
1677 begin
1678 if ApplicationProperties.IsGLContextOpen then
1679 begin
1680 { initialize OpenGL resources on-demand }
1681 if not StaticResourcesReady then
1682 StaticGLContextOpen;
1683 if FTexture = 0 then
1684 GLContextOpen(FImage);
1685 end;
1686 end;
1687
1688 function TDrawableImage.GetContents(const ImageClass: TCastleImageClass): TCastleImage;
1689 begin
1690 PrepareResources;
1691 if FTexture = 0 then
1692 raise ECannotSaveTextureContents.Create('TDrawableImage texture was not created for some reason');
1693 Result := ImageClass.Create(Width, Height);
1694 SaveTextureContents(Result, FTexture);
1695 end;
1696
1697 procedure TDrawableImage.GLContextCloseEvent(Sender: TObject);
1698 begin
1699 GLContextClose;
1700 RenderToImageFree;
1701 end;
1702
1703 procedure TDrawableImage.RenderToImageBegin(const SetAndRestoreViewport: boolean);
1704
1705 procedure RenderToImageCreate;
1706 begin
1707 FRenderToImage := TGLRenderToTexture.Create(Width, Height);
1708 FRenderToImage.Buffer := tbColor;
1709 FRenderToImage.SetTexture(FTexture, GL_TEXTURE_2D);
1710 FRenderToImage.GLContextOpen;
1711 end;
1712
1713 begin
1714 PrepareResources;
1715 Assert(FTexture <> 0);
1716
1717 if (FRenderToImage = nil) or
1718 (FRenderToImage.Width <> Width) or
1719 (FRenderToImage.Height <> Height) then
1720 begin
1721 RenderToImageFree;
1722 RenderToImageCreate;
1723 end;
1724
1725 FRenderToImage.RenderBegin;
1726
1727 if SetAndRestoreViewport then
1728 begin
1729 HasViewportToRestore := true;
1730 ViewportToRestore := RenderContext.Viewport;
1731 RenderContext.Viewport := Rectangle(0, 0, Width, Height);
1732 end;
1733 end;
1734
1735 procedure TDrawableImage.RenderToImageEnd;
1736 begin
1737 FRenderToImage.RenderEnd;
1738
1739 if HasViewportToRestore then
1740 begin
1741 RenderContext.Viewport := ViewportToRestore;
1742 HasViewportToRestore := false;
1743 end;
1744 end;
1745
1746 procedure TDrawableImage.RenderToImageFree;
1747 begin
1748 FreeAndNil(FRenderToImage);
1749 end;
1750
1751 procedure TDrawableImage.DrawFrom(const SourceImage: TDrawableImage;
1752 const DestinationRect, SourceRect: TFloatRectangle);
1753 begin
1754 RenderToImageBegin;
1755 SourceImage.Draw(DestinationRect, SourceRect);
1756 RenderToImageEnd;
1757 end;
1758
1759 function TDrawableImage.GetCenterX: Single;
1760 begin
1761 Result := FRotationCenter.X;
1762 end;
1763
1764 function TDrawableImage.GetCenterY: Single;
1765 begin
1766 Result := FRotationCenter.Y;
1767 end;
1768
1769 procedure TDrawableImage.SetCenterX(const Value: Single);
1770 begin
1771 RotationCenter := Vector2(Value, RotationCenter.Y);
1772 end;
1773
1774 procedure TDrawableImage.SetCenterY(const Value: Single);
1775 begin
1776 RotationCenter := Vector2(RotationCenter.X, Value);
1777 end;
1778
1779 procedure TDrawableImage.SetRepeatS(const Value: Boolean);
1780 begin
1781 if FRepeatS <> Value then
1782 begin
1783 BatchingFlushIfNeeded;
1784 FRepeatS := Value;
1785 if FTexture <> 0 then
1786 begin
1787 glBindTexture(GL_TEXTURE_2D, FTexture);
1788 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, CurrentWrap.Data[0]);
1789 end;
1790 end;
1791 end;
1792
1793 procedure TDrawableImage.SetRepeatT(const Value: Boolean);
1794 begin
1795 if FRepeatT <> Value then
1796 begin
1797 BatchingFlushIfNeeded;
1798 FRepeatT := Value;
1799 if FTexture <> 0 then
1800 begin
1801 glBindTexture(GL_TEXTURE_2D, FTexture);
1802 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, CurrentWrap.Data[1]);
1803 end;
1804 end;
1805 end;
1806
1807 procedure TDrawableImage.SetUrl(const Value: String);
1808 var
1809 NewImage: TEncodedImage;
1810 begin
1811 if FUrl <> Value then
1812 begin
1813 if Value = '' then
1814 begin
1815 // following CGE conventions, we allow to set Url to '' to clear loaded contentds
1816 Load(nil);
1817 FUrl := Value;
1818 FOwnsImage := true;
1819 end else
1820 begin
1821 NewImage := LoadEncodedImage(Value); // make exception from loading before changing URL
1822 FUrl := Value;
1823 Load(NewImage);
1824 FOwnsImage := true; // change it after Load(), so that Load frees previous image if needed
1825 end;
1826 end;
1827 end;
1828
1829 procedure TDrawableImage.SetColor(const Value: TCastleColor);
1830 begin
1831 { Assign field, calling BatchingFlushIfNeeded }
1832 if not TCastleColor.PerfectlyEquals(FColor, Value) then
1833 begin
1834 BatchingFlushIfNeeded;
1835 FColor := Value;
1836 end;
1837 end;
1838
1839 procedure TDrawableImage.SetRotation(const Value: Single);
1840 begin
1841 { Assign field, calling BatchingFlushIfNeeded }
1842 if FRotation <> Value then
1843 begin
1844 BatchingFlushIfNeeded;
1845 FRotation := Value;
1846 end;
1847 end;
1848
1849 procedure TDrawableImage.SetRotationCenter(const Value: TVector2);
1850 begin
1851 { Assign field, calling BatchingFlushIfNeeded }
1852 if not TVector2.PerfectlyEquals(FRotationCenter, Value) then
1853 begin
1854 BatchingFlushIfNeeded;
1855 FRotationCenter := Value;
1856 end;
1857 end;
1858
1859 procedure TDrawableImage.SetAlpha(const Value: TAutoAlphaChannel);
1860 begin
1861 { Assign field, calling BatchingFlushIfNeeded }
1862 if FAlpha <> Value then
1863 begin
1864 BatchingFlushIfNeeded;
1865 FAlpha := Value;
1866 end;
1867 end;
1868
1869 procedure TDrawableImage.SetBlendingSourceFactor(const Value: TBlendingSourceFactor);
1870 begin
1871 { Assign field, calling BatchingFlushIfNeeded }
1872 if FBlendingSourceFactor <> Value then
1873 begin
1874 BatchingFlushIfNeeded;
1875 FBlendingSourceFactor := Value;
1876 end;
1877 end;
1878
1879 procedure TDrawableImage.SetBlendingDestinationFactor(const Value: TBlendingDestinationFactor);
1880 begin
1881 { Assign field, calling BatchingFlushIfNeeded }
1882 if FBlendingDestinationFactor <> Value then
1883 begin
1884 BatchingFlushIfNeeded;
1885 FBlendingDestinationFactor := Value;
1886 end;
1887 end;
1888
1889 procedure TDrawableImage.SetBlendingConstantColor(const Value: TCastleColor);
1890 begin
1891 { Assign field, calling BatchingFlushIfNeeded }
1892 if not TCastleColor.PerfectlyEquals(FBlendingConstantColor, Value) then
1893 begin
1894 BatchingFlushIfNeeded;
1895 FBlendingConstantColor := Value;
1896 end;
1897 end;
1898
1899 procedure TDrawableImage.SetClip(const Value: Boolean);
1900 begin
1901 { Assign field, calling BatchingFlushIfNeeded }
1902 if FClip <> Value then
1903 begin
1904 BatchingFlushIfNeeded;
1905 FClip := Value;
1906 end;
1907 end;
1908
1909 procedure TDrawableImage.SetClipLine(const Value: TVector3);
1910 begin
1911 { Assign field, calling BatchingFlushIfNeeded }
1912 if not TVector3.PerfectlyEquals(FClipLine, Value) then
1913 begin
1914 BatchingFlushIfNeeded;
1915 FClipLine := Value;
1916 end;
1917 end;
1918
1919 procedure TDrawableImage.BatchingFlushIfNeeded;
1920 begin
1921 if (BatchingLevel <> 0) and (BatchingLastImage = Self) then
1922 BatchingFlush;
1923 end;
1924
1925 class procedure TDrawableImage.BatchingBegin;
1926 begin
1927 if BatchingLevel = 0 then
1928 begin
1929 Assert(BatchingLastImage = nil);
1930 Assert(BatchingLastImageRects = nil);
1931 Assert(BatchingLastScreenRects = nil);
1932
1933 BatchingLastImageRects := TFloatRectangleList.Create;
1934 BatchingLastScreenRects := TFloatRectangleList.Create;
1935 end;
1936
1937 Inc(BatchingLevel);
1938 end;
1939
1940 class procedure TDrawableImage.BatchingEnd;
1941 begin
1942 case BatchingLevel of
1943 0: raise Exception.Create('Calling BatchingEnd without matching BatchingBegin');
1944 1: begin
1945 BatchingFlush;
1946 Assert(BatchingLastImage = nil);
1947 FreeAndNil(BatchingLastImageRects);
1948 FreeAndNil(BatchingLastScreenRects);
1949 end;
1950 else ; // no nothing
1951 end;
1952 Dec(BatchingLevel);
1953 end;
1954
1955 class procedure TDrawableImage.BatchingFlush;
1956 begin
1957 if BatchingLastImage <> nil then
1958 begin
1959 Assert(BatchingLastImageRects.Count = BatchingLastScreenRects.Count);
1960 BatchingLastImage.DrawNoBatch(
1961 PFloatRectangleArray(BatchingLastScreenRects.L),
1962 PFloatRectangleArray(BatchingLastImageRects.L),
1963 BatchingLastImageRects.Count);
1964 BatchingLastScreenRects.Clear;
1965 BatchingLastImageRects.Clear;
1966 BatchingLastImage := nil;
1967 end;
1968 end;
1969
1970 function TDrawableImageRenderStatistics.ToString: String;
1971 begin
1972 Result := Format('Draw calls: %d, Image draws: %d', [
1973 DrawCalls,
1974 ImageDraws
1975 ]);
1976 end;
1977
1978 {$endif read_implementation}