Debian Codegraph @

src/images/castleimages.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 (*Loading, saving, and processing of images (TEncodedImage,
17 TCastleImage and other classes).
18 This unit deals with images, stored in normal memory (not on GPU).
19 Images can be loaded and saved from/to various formats
20 and processed in a lot of ways.
21 For example you can resize images, you can draw one image on another,
22 convert to grayscale and so on.
23
24 The "image" as understood by this unit may have some interesting features
25 useful with modern GPUs: image data may be compressed for GPU
26 (@link(TGPUCompressedImage)), image data may be 3D
27 (every image has @code(Depth), in addition to
28 @code(Width) and @code(Height)).
29
30 The most important class here is @link(TCastleImage).
31 It represents an image as a simple uncompressed array of pixels.
32 Descendants of TCastleImage define what exactly is a "pixel".
33
34 @unorderedList(
35 @item(We have 8-bit color images:
36 @orderedList(
37 @item(@link(TGrayscaleImage) - 1 channel,
38 can be interpreted as luminance or alpha channel depending on
39 @link(TGrayscaleImage.TreatAsAlpha).)
40
41 @item(@link(TGrayscaleAlphaImage) - 2 channels: luminance and alpha.)
42
43 @item(@link(TRGBImage) - 3 channels: red, green, blue.)
44
45 @item(@link(TRGBAlphaImage) - 4 channels: red, green, blue, alpha.)
46 )
47 )
48
49 @item(We also have an images with floating-point precision and range:
50 @orderedList(
51 @item(@link(TGrayscaleFloatImage) - 1 channel: luminance.)
52
53 @item(@link(TGrayscaleAlphaFloatImage) - 2 channels: luminance and alpha.)
54
55 @item(@link(TRGBFloatImage) - 3 channels: red, green, blue.)
56
57 @item(@link(TRGBAlphaFloatImage) - 4 channels: red, green, blue, alpha.)
58 )
59 )
60 )
61
62 There is also a more abstract image class @link(TEncodedImage),
63 representing either uncompressed image (@link(TCastleImage))
64 or an image with data compressed for GPU (@link(TGPUCompressedImage)).
65
66 When reading and writing image files, we understand various image
67 formats. See
68 @url(https://castle-engine.io/castle-image-viewer Castle Image Viewer)
69 documentation for a current list of supported image formats.
70
71 The basic loading and saving procedures are LoadImage and SaveImage.
72 Example usage:
73
74 @longCode(#
75 var
76 Image: TCastleImage;
77 begin
78 Image := LoadImage('image.png');
79 { scale the image to be 2x smaller }
80 Image.Resize(Image.Width div 2, Image.Height div 2);
81 SaveImage(Image, 'newimage.png');
82 end;
83 #)
84
85 This unit is not dependent on OpenGL or any other rendering
86 library. See @link(CastleGLImages) for OpenGL image operations
87 (for textures and others).
88 *)
89
90 unit CastleImages;
91
92 {$include castleconf.inc}
93
94 interface
95
96 uses SysUtils, Classes, Math, Generics.Collections,
97 {$ifdef FPC}
98 { FPImage and related units }
99 FPImage, FPReadPCX, FPReadGIF, FPReadPSD, FPReadTGA, FPReadTiff, FPReadXPM,
100 FPReadBMP, FPWriteBMP,
101 FPReadJPEG, FPWriteJPEG,
102 FPReadPNM, FPWritePNM,
103 FPReadPNG, FPWritePNG,
104 {$else}
105 { Delphi units }
106 {$ifndef USE_VAMPYRE_IMAGING}
107 { Vcl.Imaging.PngImage works fine, but disabled now:
108 CastleImages must be used with FMX too,
109 without depending on VCL units. }
110 Vcl.Imaging.PngImage,
111 {$endif}
112 {$endif}
113 { CGE units }
114 CastleInternalPng, CastleUtils, CastleVectors, CastleRectangles,
115 CastleFileFilters, CastleClassUtils, CastleColors;
116
117 {$define read_interface} // to include "interface" part of various includes
118
119 type
120 { TODO: This should be merged with TAlphaMode, these types say the same. }
121 { How is the alpha channel of an image treated. }
122 TAutoAlphaChannel = (acAuto, acNone, acTest, acBlending);
123 { See TCastleImage.AlphaChannel. }
124 TAlphaChannel = acNone .. acBlending;
125
126 const
127 acSimpleYesNo = acTest deprecated 'use acTest';
128 acFullRange = acBlending deprecated 'use acBlending';
129 { Default parameters for TEncodedImage.AlphaChannel,
130 decide how to detect textures alpha channel. }
131 DefaultAlphaTolerance = 5;
132
133 { Check if the two RGB colors are equal, ignoring small differences.
134 All three color components may differ by at most Tolerance.
135 When Tolerance is 0, this is a normal (exact) comparison. }
136 function EqualRGB(const Color1, Color2: TVector3Byte; Tolerance: Byte): boolean;
137
138 type
139 { Raised by @link(TCastleImage.MakeExtracted) when coordinates on image
140 are wrong.
141 Possibly I will use it in more routines in the future. }
142 EImagePosOutOfRange = class(Exception);
143
144 EImageLerpError = class(Exception);
145 EImageLerpInvalidClasses = class(EImageLerpError);
146 EImageLerpDifferentSizes = class(EImageLerpError);
147
148 EImageAssignmentError = class(Exception);
149
150 EImageCannotConvertFpImage = class(Exception);
151
152 EImageDrawError = class(Exception);
153
154 {$ifdef FPC}
155 { An internal class to communicate image data
156 between CastleImages and fcl-image efficiently.
157 @exclude }
158 TInternalCastleFpImage = class(TFPCompactImgRGBA8Bit)
159 strict private
160 function GetColors8Bit(const x, y: integer): TFPCompactImgRGBA8BitValue;
161 procedure SetColors8Bit(const x, y: integer; const Value: TFPCompactImgRGBA8BitValue);
162 public
163 property Colors8Bit[X, Y: Integer]: TFPCompactImgRGBA8BitValue
164 read GetColors8Bit write SetColors8Bit;
165 end;
166 {$endif}
167
168 { Abstract class for an image with unspecified, possibly compressed,
169 memory format. Both uncompressed images (TCastleImage)
170 and images compressed for GPU (TGPUCompressedImage) are derived from this
171 base class. }
172 TEncodedImage = class
173 private
174 FWidth, FHeight, FDepth: Cardinal;
175 FUrl: String;
176 procedure NotImplemented(const AMethodName: string);
177 {$ifdef FPC}
178 procedure FromFpImage(const FPImage: TInternalCastleFpImage); virtual;
179 {$endif}
180 protected
181 { Operate on this by Get/Realloc/FreeMem.
182 It's always freed and nil'ed in destructor. }
183 FRawPixels: Pointer;
184 public
185 { Url from which this image was loaded, if any. }
186 property Url: String read FUrl write FUrl;
187
188 destructor Destroy; override;
189
190 property Width: Cardinal read FWidth;
191 property Height: Cardinal read FHeight;
192
193 { Depth of the image.
194 For 2D images (most common) this is just 1.
195
196 All images in CastleImages can be potentially 3D, which means they
197 can have Depth > 1.
198 A 3D image is just a 3-dimensional array of pixels,
199 and you can use it e.g. as a texture with 3D texture coordinates.
200 A sample use-cases for 3D textures are:
201
202 @unorderedList(
203 @item(Generated colors of some material that you can imagine as
204 a 3D volume, like a volume of wood or marble. This is nice to apply
205 on any complicated 3D shape, because the necessary
206 3D texture coordinates are trivial,
207 since 3D position of a point on the shape
208 can be used as a reasonable 3D texture coordinate.)
209 @item(Medical data, some scans are 3D.)
210 @item(Noise (like Perlin noise) used for various
211 effects in shaders.)
212 @item(Specialized noise, e.g. a volume of smoke, or a volume of clouds.)
213 )
214 }
215 property Depth: Cardinal read FDepth;
216
217 { Image data. The layout of this memory is defined by descendants.
218 For example, for TCastleImage it's a simple array of pixels
219 (see TCastleImage docs for exact description of the memory layout),
220 for TGPUCompressedImage it's a compressed data for GPU.
221
222 Note that this may be @nil, if Width * Height * Depth = 0.
223 In this case, IsEmpty returns @true. }
224 property RawPixels: Pointer read FRawPixels;
225
226 { Size of image contents in bytes. }
227 function Size: Cardinal; virtual; abstract;
228
229 { Get a 3D vector with @link(Width), @link(Height), @link(Depth). }
230 function Dimensions: TVector3Cardinal;
231
232 { Is an image empty.
233
234 @true means that RawPixels = @nil,
235 and Width * Height * Depth = 0
236 (so either Width = 0 or Height = 0 or Depth = 0).
237
238 @false means that RawPixels <> nil and Width * Height * Depth <> 0
239 (so all Width > 0 and Height > 0 and Depth > 0, since they are
240 Cardinal (unsigned) always). }
241 function IsEmpty: boolean;
242
243 { Does an image have an alpha channel.
244
245 You may also be interested in the @link(AlphaChannel) that can
246 make a distinction between alpha channel for blending and for alpha test.
247 AlphaChannel answers always atNone if HasAlpha = false,
248 and always acTest or acBlending if HasAlpha = true.
249 But AlphaChannel may perform longer analysis of pixels
250 (to differ between acTest and acBlending), while this
251 function always executes ultra-fast (as it's constant for each
252 TCastleImage descendant).
253
254 @italic(Descendants implementors notes:) in this class, TCastleImage,
255 this returns @false. Override to return @true for images with
256 alpha channel. }
257 function HasAlpha: boolean; virtual;
258
259 { Analyze image contents to determine if, and what kind, of alpha channel
260 it has.
261
262 This may be a time-consuming operation. When the image has alpha channel
263 and we need
264 to decide whether it's suitable for "alpha test" (only fully opaque
265 or fully transparent pixels) or "alpha blending" (any alpha value makes sense)
266 then this method needs to iterate over image pixels.
267
268 For this reason, the result of this operation is cached at various
269 levels, e.g. TImageTextureNode and TDrawableImage cache it internally.
270
271 We determine "alpha test - simple yes/no alpha channel" if all the alpha values
272 (for every pixel) are 0, or 255, or (when AlphaTolerance <> 0)
273 are close to them by AlphaTolerance. So, to be precise,
274 alpha value must be <= AlphaTolerance, or >= 255 - AlphaTolerance.
275 If any alpha value is between [AlphaTolerance + 1, 255 - AlphaTolerance - 1]
276 then we return "alpha blending - full range alpha channel".
277
278 Note that big values of AlphaTolerance make it easier to quality image
279 as "alpha test - simple yes/no alpha channel".
280 When AlphaTolerance >= 128, all images are treated as
281 "simple yes/no alpha". Usually, you want to keep AlphaTolerance small.
282
283 @italic(Descendants implementors notes:) in this class, this simply
284 always returns atNone. For descendants that have alpha channel,
285 implement it, honouring AlphaTolerance as described. }
286 function AlphaChannel(
287 const AlphaTolerance: Byte = DefaultAlphaTolerance):
288 TAlphaChannel; virtual;
289
290 { Rectangle representing the inside of this image.
291 Always (Left,Bottom) are zero, and (Width,Height) correspond to image
292 sizes. }
293 function Rect: TRectangle;
294
295 { Create a new image object that has exactly the same class
296 and the same data (size, pixels) as this image. }
297 function CreateCopy: TEncodedImage; virtual; abstract;
298
299 { Mirror image vertically. }
300 procedure FlipVertical; virtual; abstract;
301
302 {$ifdef FPC}
303 { Convert image contents to FpImage instance.
304 The resulting instance is owned by the caller. }
305 function ToFpImage: TInternalCastleFpImage; virtual; deprecated 'interoperability with FpImage may be dropped in the future';
306 {$endif}
307 end;
308
309 { Resize interpolation modes, see TCastleImage.Resize and TCastleImage.MakeResized. }
310 TResizeInterpolation = (
311 { Fastest interpolation mode. }
312 riNearest,
313 { Bilinear interpolation mode, quite fast. }
314 riBilinear,
315 { Slower but prettier interpolation modes.
316 All the following interpolation modes are slower,
317 not only because their equations are more complicated (and using more inputs),
318 but also because their current implementation involves round-trip to FpImage
319 format.
320 Use these if speed is not a concern, but quality is crucial. }
321 riMitchel,
322 riBlackman,
323 riBlackmanSinc,
324 riBlackmanBessel,
325 riGaussian,
326 riHermite,
327 riLanczos,
328 riQuadratic,
329 riCubic,
330 riCatrom,
331 riHanning,
332 riHamming
333 );
334
335 TResizeInterpolationInternal = Low(TResizeInterpolation) .. riBilinear;
336 TResizeInterpolationFpImage = Succ(riBilinear) .. High(TResizeInterpolation);
337
338 { Drawing mode used by image-on-image drawing methods
339 (@link(TCastleImage.DrawFrom) and @link(TCastleImage.DrawTo)). }
340 TDrawMode = (
341 { Normal drawing mode, where the image contents are blended using
342 the opacity (alpha) of the source image. That is,
343
344 @preformatted(
345 destination.rgb := destination.rgb * (1 - source.alpha) + source.rgb * source.alpha;
346 destination.alpha := destination.alpha; // never changed by this drawing mode
347 )
348
349 An image type without alpha (like TRGBImage or TGrayscaleImage)
350 is always treated like it has alpha = 1.0 (fully opaque) everywhere.
351 In particular, this means that when drawing @italic(an image
352 without alpha over any other image), source RGB contents will
353 simply replace the destination RGB contents. }
354 dmBlend,
355
356 { An advanced blending mode, capable of blending 2 images with alpha channel
357 better than dmBlend.
358 Based on https://en.wikipedia.org/wiki/Alpha_compositing formula for alpha-blending.
359 This one is much less efficient than dmBlend and should be used only in case
360 several layers of semi-transparent images should overlay one another and it
361 matters to accurately account for both images alpha channel. Implemented for
362 all @link(TRGBAlphaImage) and @link(TGrayscaleAlphaImage) combinations.
363 }
364 dmBlendSmart,
365
366 { Multiply two images. Simply multiply source with destination, channel by channel:
367
368 @preformatted(
369 destination.rgba := destination.rgba * source.rgba;
370 )
371
372 The exception is when the source image has alpha channel,
373 but destination does not. For example, when source is TRGBAlphaImage
374 or TGrayscaleAlphaImage and destination is TRGBImage or TGrayscaleImage.
375 In this case the multiplication is followed by a simple blending,
376 to apply the effects of source alpha:
377
378 @preformatted(
379 destination.rgb :=
380 source.rgb * destination.rgb * source.alpha +
381 destination.rgb * (1 - source.alpha);
382 )
383
384 Note that if source.alpha = 1 (source is opaque) that this is equivalent
385 to the previous simple multiply equation. }
386 dmMultiply,
387
388 { Overwrite drawing mode, where the image contents of destination image
389 is replaced with contents of source image. That is,
390
391 @preformatted(
392 destination.rgba := source.rgba;
393 )
394 }
395 dmOverwrite,
396
397 { Additive drawing mode, where the image contents of source image
398 are added to the existing destination image. That is,
399
400 @preformatted(
401 destination.rgb := destination.rgb + source.rgb * source.alpha;
402 destination.alpha := destination.alpha; // never changed by this drawing mode
403 )
404
405 So when drawing @italic(an image with alpha over an image without alpha),
406 the colors will be added according to the above equation, only source
407 is multiplied by alpha. To speed this operation, one can use
408 @link(TRGBAlphaImage.PremultiplyAlpha) on the source image first,
409 very useful if you plan to draw the same source image many times. }
410 dmAdd
411 );
412
413 { An abstract class representing image as a simple array of pixels.
414 RawPixels is a pointer to Width * Height * Depth of pixels.
415
416 What exactly is a "pixel" is undefined in this class. Each descendant
417 of TCastleImage defines it's own pixel encoding and interpretation.
418 The only requirement is that all pixels have the same size (PixelSize).
419 For example, for TRGBImage a "pixel" is a TVector3Byte type
420 representing a (red, green, blue) color value.
421
422 When Depth > 1, the image is actually a 3D (not just 2D!) image.
423 We call the particular 2D layers then "slices".
424 Although some TCastleImage methods (and functions in other units, like CastleGLImages)
425 still operate only on the 1st "slice", that is the 2D image on Depth = 0
426 --- be careful. But many methods correctly take the depth into consideration.
427
428 Pixels in RawPixels are ordered in slices, each slice is ordered in rows,
429 in each row pixels are specified
430 from left to right, rows are specified starting from lower row to upper.
431 This means that you can think of RawPixels as
432
433 @longCode(#
434 ^(packed array[0..Depth - 1, 0..Height - 1, 0..Width - 1] of TPixel)
435 #)
436
437 Assuming the above definition, RawPixels^[z, y, x]
438 is color of pixel at position z, x, y.
439
440 Note that specifying rows from lower to upper follows an OpenGL standard,
441 this makes using this unit with OpenGL straightforward.
442
443 Don't ever operate on RawPixels pointer directly --- allocating, reallocating,
444 freeing memory pointed to by RawPixels is handled inside this class.
445 You must only worry to always free created TCastleImage instances
446 (like with any class).
447
448 Note that the only valid states of instances of this class
449 are when (Width * Height * Depth > 0 and RawPixels <> nil) or
450 (Width * Height * Depth = 0 and RawPixels = nil). Otherwise the fundamental
451 assumption that RawPixels is a pointer to Width * Height * Depth pixels would
452 be broken (as nil pointer cannot point to anything, and on the other
453 side it's rather useless to have a pointer to 0 bytes (since you
454 can never dereference it anyway) even if theoretically every PtrInt
455 value can be treated as valid pointer to 0 bytes).
456
457 Note about coordinates:
458
459 @orderedList(
460 @item(All X, Y, Z coordinates of pixels are 0-based
461 (X in range 0..Width-1, and Y in 0..Height-1, and Z in 0..Depth-1).)
462
463 @item(If documentation for some method does not specify otherwise,
464 correctness of coordinates is *not* checked in method,
465 which can lead to various errors at runtime if you will pass
466 incorrect coordinates to given routine.)
467 )
468 }
469 TCastleImage = class(TEncodedImage)
470 protected
471 { Check that both images have the same sizes and Second image class
472 descends from First image class. If not, raise appropriate ELerpXxx
473 exceptions.
474
475 Some implementation of TRGBImage.LerpWith may require
476 other checks (since LerpWith may be sometimes allowed between unequal
477 classes), so this doesn't have to be used by all TRGBImage.LerpWith
478 implementations (although it's comfortable for simple implementations). }
479 procedure LerpSimpleCheckConditions(SecondImage: TCastleImage);
480
481 { Like DrawFrom, but can assume that all coordinates and sizes are valid.
482 Override this to add copying using some more sophisticated method
483 than just memory copying (so also for handling mode other than
484 dmBlend). }
485 procedure DrawFromCore(Source: TCastleImage;
486 X, Y, SourceX, SourceY, SourceWidth, SourceHeight: Integer;
487 const Mode: TDrawMode); virtual;
488
489 {$ifdef FPC}
490 function MakeResizedToFpImage(ResizeWidth, ResizeHeight: Cardinal;
491 const Interpolation: TResizeInterpolation): TInternalCastleFpImage;
492 {$endif FPC}
493
494 function GetColors(const X, Y, Z: Integer): TCastleColor; virtual;
495 procedure SetColors(const X, Y, Z: Integer; const C: TCastleColor); virtual;
496
497 { Assign properties (other than @link(Url), sizes and pixel contents).
498
499 Used when creating a copy like @link(MakeCopy), @link(MakeRotated),
500 @link(MakeResized) and so on.
501 This is not used by @link(Assign), so @link(Assign) implementation
502 overrides must make sure to do the same thing (or call AssignProperties
503 in descendants). }
504 procedure AssignProperties(const Source: TCastleImage); virtual;
505 public
506 { Constructor without parameters creates image with Width = Height = Depth = 0
507 and RawPixels = nil, so IsEmpty will return @true. }
508 constructor Create; overload; virtual;
509 constructor Create(const AWidth, AHeight: Cardinal; const ADepth: Cardinal = 1); overload;
510
511 { This is equivalent to SetSize(0, 0, 0).
512 It sets Width = Height = 0 and RawPixels = nil. }
513 procedure Empty;
514
515 { Change size (Width and Height and Depth).
516 Previous pixel contents (RawPixels) are lost,
517 and the contents of new pixels are undefined.
518
519 Use other method, like @link(Resize), if you want to change image size
520 preserving it's contents. }
521 procedure SetSize(
522 const AWidth, AHeight: Cardinal;
523 const ADepth: Cardinal = 1); overload;
524 procedure SetSize(const Source: TCastleImage); overload;
525
526 { Size of TPixel in bytes for this TCastleImage descendant. }
527 class function PixelSize: Cardinal; virtual; abstract;
528
529 { Size of image contents in bytes. }
530 function Size: Cardinal; override;
531
532 { Deprecated name for ImageSize. }
533 function ImageSize: Cardinal; deprecated;
534
535 { Number of color components in TPixel.
536
537 E.g. RGB is 3 components and RGB+Alpha is 4 components,
538 RGB+Exponent is 3 components (because it describes only
539 Red, Green and Blue values (Exponent value is just used
540 to correctly interpret these, it's not a 4th component)). }
541 class function ColorComponentsCount: Cardinal; virtual; abstract;
542
543 { Pointer to the (x, y, z) pixel of image.
544
545 Note that they don't check X, Y, Z correctness in any way,
546 it's your responsibility to always pass 0 <= X < Width and
547 0 <= Y < Height and 0 <= Z < Depth.
548
549 Note that this function @italic(should) be reintroduced in descendants
550 to return the same value but typecasted to something better then Pointer
551 (something like ^TPixel). }
552 function PixelPtr(const X, Y: Cardinal; const Z: Cardinal = 0): Pointer;
553
554 { Pointer to the first pixel in the Y row of the image.
555 Same thing as @link(PixelPtr) but always with X = 0.
556
557 Note that this function @italic(should) be reintroduced in descendants
558 to return the same value but typecasted to something better then Pointer,
559 preferably something like ^(array of TPixel). }
560 function RowPtr(const Y: Cardinal; const Z: Cardinal = 0): Pointer;
561
562 { Inverts all colors (RGB or grayscale, but doesn't touch alpha channel).
563 "Inverting" means changing color C in range [0..1] to 1-C,
564 so black becomes white, white becomes black etc.
565
566 @italic(For descendants implementors:)
567 Override it if necessary, otherwise the default implementation in this class
568 will raise EInternalError. }
569 procedure InvertColors; virtual;
570
571 { Get or set the color of the pixel.
572
573 In case of descendants without alpha, we may drop this information.
574
575 In case of grayscale descendants, when getting or setting we convert
576 the color to/from grayscale as necessary. This means that setting
577 RGB color on a grayscale image may lose information -- we will convert
578 your color to grayscale.
579
580 Caller is responsible for checking the correctness of given
581 X, Y, Z coordinates. For speed, we may not check them inside (so nasty
582 memory errors will occur in case of invalid coordinates). }
583 property Colors [const X, Y, Z: Integer]: TCastleColor read GetColors write SetColors;
584
585 procedure SetColorRGB(const X, Y: Integer; const v: TVector3);
586 deprecated 'use Colors[X, Y, 0] to get or set colors';
587
588 { Create a new image object that has exactly the same class
589 and the same data (size, pixels) as this image.
590
591 (Design note: this function is *not* a constructor, because it's implemented
592 in TCastleImage, but it always returns some descendant of TCastleImage.) }
593 function MakeCopy: TCastleImage;
594
595 { Create a new image object that has exactly the same class
596 and the same data (size, pixels) as this image.
597
598 Equivalent to MakeCopy, but virtual and declared as returning TEncodedImage class. }
599 function CreateCopy: TEncodedImage; override;
600
601 { Change Width and Height and appropriately stretch
602 image contents.
603
604 If ResizeWidth or ResizeHeight is 0 then it means to take
605 Width or Height, respectively.
606 So e.g. using ResizeWidth = ResizeHeight = 0 is the same thing
607 as using ResizeWidth = Width and ResizeHeight = Height and this is NOP.
608
609 Remember that resizing may change RawPixels pointer, so all pointers
610 that you aquired using functions like
611 RawPixels, Pixels, PixelsArray, RowPtr, PixelPtr
612 may be invalid after calling Resize. }
613 procedure Resize(ResizeWidth, ResizeHeight: Cardinal;
614 const Interpolation: TResizeInterpolation = riBilinear);
615
616 { Change Width and Height and appropriately stretch image contents.
617
618 This scales the image in almost the same way as standard @link(Resize).
619 However, this is aware of the image corners and edges, which is good
620 if you plan to use this image with @link(TDrawableImage.Draw3x3) drawing.
621
622 The Corners parameter specifies the corners size, in the same
623 clockwise order as for @link(TDrawableImage.Draw3x3): top, right, bottom, left.
624 The corners will be scaled (proportially to image scaling),
625 and new Corners size returned.
626 Additionally it makes sure that filtering (especially bilinear)
627 does not "leak" colors from one image area to another.
628 Effectively, the image is scaled like a 9 separate parts,
629 and colors cannot bleed from one part to another.
630
631 Both ResizeWidth, ResizeHeight parameters must be provided and non-zero.
632
633 For now, only a subset of TResizeInterpolation values
634 are supported by this method, namely the ones in TResizeInterpolationInternal. }
635 procedure Resize3x3(const ResizeWidth, ResizeHeight: Cardinal;
636 var Corners: TVector4Integer;
637 const Interpolation: TResizeInterpolationInternal);
638 deprecated 'This method is seldom useful, and it is confused with TCastleImage.DrawFrom3x3 and TDrawableImage.Draw3x3 too often. Please report if you have a use-case when this method is useful, otherwise it may get removed from the engine one day.';
639
640 { Create a new TCastleImage instance with size ResizeWidth, ResizeHeight
641 and pixels copied from the input and appropriately stretched.
642 The exact class of the new instance is the same as our class.
643
644 As with @link(Resize) method, when the parameter ResizeTo* is 0
645 it means to use current Width/Height.
646 So e.g. using MakeResized(0, 0) is the same thing as using CreateCopy. }
647 function MakeResized(ResizeWidth, ResizeHeight: Cardinal;
648 const Interpolation: TResizeInterpolation = riBilinear): TCastleImage;
649
650 { Mirror image horizotally (that is right edge is swapped with left edge). }
651 procedure FlipHorizontal;
652
653 { Mirror image vertically. }
654 procedure FlipVertical; override;
655
656 { Make rotated version of the image.
657 See @link(Rotate) for description of parameters. }
658 function MakeRotated(Angle: Integer): TCastleImage;
659
660 { Rotate image by Angle * 90 degrees, clockwise.
661 For example, 0 does nothing. 1 rotates by 90 degrees, 2 rotates
662 by 180, 3 rotates by 270. All other values (negative too) are circular
663 (modulo), so e.g. 4 again does nothing, 5 rotates by 90 degrees and so on. }
664 procedure Rotate(const Angle: Integer);
665
666 { Create a new instance with the same class, and size
667 TileX * Width and TileY * Height and contents being our contents
668 duplicated (tiled).
669 Must be TileX, TileY > 0. }
670 function MakeTiled(TileX, TileY: Cardinal): TCastleImage;
671
672 { Extract rectangular area of this image.
673 X0 and Y0 are start position (lower-left corner),
674 ExtractWidth, ExtractHeight specify size of area.
675
676 This checks parameters for correctness -- if start position is not
677 correct or ExtractWidth/Height are too large then exception
678 @link(EImagePosOutOfRange) is raised. }
679 function MakeExtracted(X0, Y0, ExtractWidth, ExtractHeight: Cardinal): TCastleImage;
680
681 { Set all image pixels to the same color. }
682 procedure Clear(const Pixel: TVector4Byte); overload; virtual;
683 procedure Clear(const Pixel: TCastleColor); overload;
684
685 { Check do all image pixels have the same color. }
686 function IsClear(const Pixel: TVector4Byte): boolean; overload; virtual;
687
688 { Multiply each RGB color by a matrix.
689 This is a useful routine for many various conversions of image colors.
690 Every pixel's RGB color is multiplied by given Matrix,
691 i.e. PixelRGBColor := Matrix * PixelRGBColor.
692
693 If some value in some channel will be < 0, it will be set to 0.
694 And if it will be > High(Byte), it will be set to High(Byte).
695
696 Examples: when
697 Matrix = TMatrix3.Identity, this is NOOP.
698 Matrix = ((2, 0, 0), (0, 1, 0), (0, 0, 1))
699 red channel is made lighter.
700 Matrix = ((0, 0, 1), (0, 1, 0), (1, 0, 0))
701 swaps red and blue channel.
702 Matrix = ((0.33, 0.33, 0.33),
703 (0.33, 0.33, 0.33),
704 (0.33, 0.33, 0.33))
705 is a simple conversion to grayscale (actually incorrect, even if often
706 visually acceptable; actually instead of 0.33 one has to use
707 GrayscaleFloat/ByteValues, this is already implemented
708 in ImageTransformColorsVar function)
709
710 Note: it's often more optimal to hard-code necessary color transformations
711 as TColorModulatorFunc and use ModulateRGB.
712
713 This function is only implemented for images that represent Pixel
714 as RGB values, for now this means TRGBImage and TRGBAlphaImage.
715 In case of TRGBAlphaImage (or any other class that represents
716 colors as RGB + something more) alpha channel (i.e. "something more")
717 is ignored (i.e. left without any modification).
718
719 In this class this simply raises EInternalError to say 'not implemented'.
720 This also means that you must not call inherited in
721 descendants when overriding this method. }
722 procedure TransformRGB(const Matrix: TMatrix3); virtual;
723
724 { Process each pixel by given function.
725 If ColorModulator = nil then this procedure does nothing.
726 Else, every RGB color value of an image will be transformed using
727 ColorModulator.
728
729 Like TransformRGB:
730 This function is only implemented for images that represent Pixel
731 as RGB values, for now this means TRGBImage and TRGBAlphaImage.
732 In case of TRGBAlphaImage (or any other class that represents
733 colors as RGB + something more) alpha channel (i.e. "something more")
734 is ignored (i.e. left without any modification).
735
736 In this class this simply raises EInternalError to say 'not implemented'.
737 This also means that you must not call inherited in
738 descendants when overriding this method. }
739 procedure ModulateRGB(const ColorModulator: TColorModulatorByteFunc); virtual;
740
741 { Just like ModulateRGB, but this returns new image, not changing initial
742 image. This means that if ColorModulator = nil this is
743 equivalent to CreateCopy.
744
745 Implemented if and only if ModulateRGB is implemented. }
746 function MakeModulatedRGB(
747 const ColorModulator: TColorModulatorByteFunc): TCastleImage;
748
749 { Convert image colors to grayscale.
750
751 Implemented if and only if ModulateRGB is implemented.
752 When image has alpha channel, alpha channel value
753 (or just anything beyond 3 rgb components) is ignored (not modified).
754
755 This changes color to grayscale, but format of memory storage is the same.
756 For example, for TRGBImage, they are still kept in RGB format
757 (just Red = Green = Blue). If you want to convert to true Grayscale format,
758 you should use TRGBImage.ToGrayscale that will create new
759 TGrayscaleImage instance. }
760 procedure Grayscale;
761
762 { Convert every image color using Color*Convert function from CastleVectors.
763 "Channel" parameter determines which Color*Convert function to use
764 (Red, Green or Blue), must be 0, 1 or 2.
765
766 Implemented if and only if ModulateRGB is implemented. }
767 procedure ConvertToChannelRGB(Channel: Integer);
768
769 { Converts every image color using Color*Strip function from CastleVectors.
770 "Channel" parameter determines which Color*Strip function to use
771 (Red, Green or Blue), must be 0, 1 or 2.
772
773 Implemented if and only if ModulateRGB is implemented. }
774 procedure StripToChannelRGB(Channel: Integer);
775
776 { Check if given Image has the same class, the same sizes
777 (Width, Height) and contains exactly the same pixel values. }
778 function IsEqual(Image: TCastleImage): boolean;
779
780 { This is like IsEqual, but is compares only given parts of the images.
781 Note that it's your responsibility to make sure that given areas
782 are really within the sizes of Self or Image.
783
784 Overloaded version without SelfXxx parameters compares whole Self
785 to given part of Image. Analogously, version without ImageXxx parameters
786 compares whole Image to part of Self.
787
788 @groupBegin }
789 function ArePartsEqual(
790 const SelfX0, SelfY0, SelfWidth, SelfHeight: Cardinal;
791 Image: TCastleImage;
792 const ImageX0, ImageY0, ImageWidth, ImageHeight: Cardinal): boolean; overload;
793
794 function ArePartsEqual(
795 Image: TCastleImage;
796 const ImageX0, ImageY0, ImageWidth, ImageHeight: Cardinal): boolean; overload;
797
798 function ArePartsEqual(
799 const SelfX0, SelfY0, SelfWidth, SelfHeight: Cardinal;
800 Image: TCastleImage): boolean; overload;
801 { @groupEnd }
802
803 { Draw one image part on another image.
804 X, Y is the lower-left position on the destination image where we draw.
805 Optional SourceX, SourceY, SourceWidth, SourceHeight specify
806 to use only a part of the source image (without them, we take whole source
807 image).
808 The pixel on source image (SourceX, SourceY) will be drawn
809 on destination image on (X, Y).
810
811 The coordinates and sizes are carefully checked, so that we do not
812 try to take some pixels outside of the source or destination image.
813
814 @italic(Warning: It is not efficient to use this drawing method.)
815 This drawing is performed on CPU and cannot be fast.
816 If possible, use instead @link(TDrawableImage.DrawFrom),
817 that performs image-on-image drawing using GPU,
818 or just draw @link(TDrawableImage) straight to the screen by @link(TDrawableImage.Draw).
819 See examples/images_videos/draw_images_on_gpu.lpr for an example of
820 @link(TDrawableImage.DrawFrom).
821 Using this method makes most sense in image manipulation tools,
822 or during the loading / preparation stage of your game,
823 not during actual game.
824
825 @italic(Note for descendants implementors:)
826 The default implementation of this function in TCastleImage
827 can only directly copy the pixels, regardless
828 of what information they have. This makes it very fast,
829 but not suitable if the source image has some alpha channel
830 and you want to apply it over a destination image with blending
831 (adding scaled source to a destination color),
832 and not suitable when Mode is <> dmBlend.
833 Descendants with alpha channel should override @link(DrawFromCore)
834 to handle drawing with blending (for dmBlend),
835 all descendants should override @link(DrawFromCore)
836 to handle drawing with Mode <> dmBlend.
837
838 @raises(EImageDrawError When drawing cannot be performed,
839 for example because drawing with this Mode,
840 and/or for this Source and destination classes,
841 is not implemented yet.)
842
843 @groupBegin }
844 procedure DrawFrom(Source: TCastleImage; const X, Y: Integer;
845 const Mode: TDrawMode = dmBlend); overload;
846 procedure DrawFrom(Source: TCastleImage;
847 X, Y, SourceX, SourceY, SourceWidth, SourceHeight: Integer;
848 const Mode: TDrawMode = dmBlend); overload;
849 procedure DrawTo(Destination: TCastleImage; const X, Y: Integer;
850 const Mode: TDrawMode = dmBlend);
851 { @groupEnd }
852
853 { Draw the Source image on this image,
854 dividing the source image into 3x3 parts for corners,
855 sides, and inside.
856
857 The source image is divided into 3 * 3 = 9 parts:
858
859 @unorderedList(
860 @item(4 corners, used to fill the corners of the DestinationRect.
861 They are not stretched.)
862 @item(4 sides, used to fill the sides of the DestinationRect
863 between the corners. They are scaled in one dimension, to fill
864 the space between corners completely.)
865 @item(the inside. Used to fill the rectangular inside.
866 Scaled in both dimensions as necessary.)
867 )
868
869 The size of corners is specified in the SourceCorners parameter,
870 in the order: top, right, bottom, left.
871 (It's the same order as e.g. CSS margins.)
872
873 @italic(Warning: It is not efficient to use this drawing method.)
874 This drawing is performed on CPU and cannot be fast.
875 If possible, use instead @link(TDrawableImage),
876 and either draw it to the screen by @link(TDrawableImage.Draw3x3),
877 or draw it to another @link(TDrawableImage) by combining @link(TDrawableImage.Draw3x3)
878 with @link(TDrawableImage.RenderToImageBegin).
879 Using this method makes most sense in image manipulation tools,
880 or during the loading / preparation stage of your game,
881 not during actual game.
882 }
883 procedure DrawFrom3x3(const DestinationRect: TRectangle;
884 const Source: TCastleImage; const SourceCorners: TVector4Integer;
885 const DrawMode: TDrawMode;
886 const Interpolation: TResizeInterpolation = riBilinear);
887
888 { Makes linear interpolation of colors from this image and the SecondImage.
889 Intuitively, every pixel in new image is set to
890
891 @preformatted(
892 (1 - Value) * Self[pixel] + Value * SecondImage[pixel]
893 )
894
895 Both images need to have the exact same size.
896 If they are not, EImageLerpDifferentSizes is raised.
897
898 Not all TCastleImage combinations are allowed. Every subclass is required
899 to override this to at least handle Lerp between itself.
900 That is, TRGBImage.Lerp has to handle Lerp with other TRGBImage,
901 TRGBAlphaImage.Lerp has to handle Lerp with other TRGBAlphaImage etc.
902 Other combinations may be permitted, if useful and implemented.
903 EImageLerpInvalidClasses is raised if given class combinations are
904 not allowed.
905
906 In this class, this simply always raises EImageLerpInvalidClasses.
907
908 @raises(EImageLerpDifferentSizes When SecondImage size differs
909 from this image.)
910 @raises(EImageLerpInvalidClasses When Lerp between this TCastleImage
911 descendant class and SecondImage class is not implemented.) }
912 procedure LerpWith(const Value: Single; SecondImage: TCastleImage); virtual;
913
914 { Mix 4 colors, with 4 weights, into a resulting color.
915 All 4 Colors and OutputColor must be pointers to a pixel of current
916 image class, that is they must point to PixelSize bytes of memory.
917
918 @raises(EImageLerpInvalidClasses When mixing is not implemented
919 for this image class.) }
920 class procedure MixColors(const OutputColor: Pointer;
921 const Weights: TVector4; const AColors: TVector4Pointer); virtual;
922
923 { Copy size and contents from Source.
924 This sets our size (Width, Height and Depth)
925 to match Source image, and copies pixels from the Source image,
926 converting them as closely as possible.
927 For example, converting RGBA to RGB will strip alpha channel,
928 but copy RGB values.
929
930 When implementing descendants: the base implementation of this method
931 in TCastleImage handles only the case when Image class equals our own class.
932 And raises EImageAssignmentError in other cases.
933 Override this method if you want to actually handle some conversions
934 when assignning.
935
936 @raises(EImageAssignmentError If it's not possible to convert from
937 Source class to us.)
938 }
939 procedure Assign(const Source: TCastleImage); virtual;
940
941 { Append code to embed this image inside Pascal source code. }
942 procedure SaveToPascalCode(const ImageName: string;
943 var CodeInterface, CodeImplementation, CodeInitialization, CodeFinalization: string);
944
945 { Set the RGB colors for transparent pixels to the nearest non-transparent
946 colors. This fixes problems with black/white borders around the texture
947 regions, when the texture is scaled down (by any means --
948 on CPU, during rendering on GPU...).
949
950 @bold(The algorithm implemented here, for now, is really slow
951 (but also really correct).)
952 It should only be used as a last resort, when your normal tool
953 (like Spine atlas packer) cannot do a decent job on a given image.
954 You should use this when creating assets, and save the resulting
955 image to disk (avoid doing this at runtime during the game,
956 since it's really really slow).
957
958 @groupBegin }
959 procedure AlphaBleed(const ProgressTitle: string = ''); virtual;
960 function MakeAlphaBleed(const ProgressTitle: string = ''): TCastleImage; virtual;
961 { @groupEnd }
962 public
963 { Draw simple geometric shapes like circles, rectangles, lines, etc.
964 @groupBegin }
965 procedure FillEllipse(const x, y: single; const aRadiusX, aRadiusY: single;
966 const aColor: TCastleColor); virtual;
967 procedure Ellipse(const x, y: single; const aRadiusX, aRadiusY: single;
968 const aWidth: single; const aColor: TCastleColor); virtual;
969 procedure FillRectangle(const x1, y1, x2, y2: single;
970 const aColor: TCastleColor); virtual;
971 procedure Rectangle(const x1, y1, x2, y2: single;
972 const aWidth: single; const aColor: TCastleColor); virtual;
973 procedure Line(const x1, y1, x2, y2: single;
974 const aWidth: single; const aColor: TCastleColor); virtual;
975 procedure FloodFill(const x, y: integer; const aColor: TCastleColor;
976 const aThreshold: single = 0);
977 { @groupEnd }
978 end;
979
980 TCastleImageList = {$ifdef FPC}specialize{$endif} TObjectList<TCastleImage>;
981
982 TEncodedImageList = {$ifdef FPC}specialize{$endif} TObjectList<TEncodedImage>;
983
984 { Possible compression of textures for GPU.
985 The compressed texture formats may be automatically created for you by CGE,
986 see https://castle-engine.io/creating_data_auto_generated_textures.php . }
987 TTextureCompression = (
988 { S3TC DXT1 compression, @bold(for opaque RGB images (no alpha channel)).
989 This compression format is often supported by desktop OpenGL implementations.
990 See http://en.wikipedia.org/wiki/S3_Texture_Compression about S3TC.
991 It is also supported by a small number of Android devices.
992
993 Note that the tcDxt1_RGB and tcDxt1_RGBA are the same compression method.
994 Their behavior only differs when rendering:
995 in case of tcDxt1_RGB, the alpha information is not used,
996 while in case of tcDxt1_RGBA, the renderer is using alpha-testing. }
997 tcDxt1_RGB,
998
999 { S3TC DXT1 compression, @bold(for RGBA images with simple yes/no alpha channel).
1000 The renderer will use alpha-testing when rendering such images.
1001 See above tcDxt1_RGB description for details. }
1002 tcDxt1_RGBA,
1003
1004 { S3TC DXT3 compression, @bold(for RGBA images with full alpha channel),
1005 best for images with sharp alpha transitions.
1006 This compression format is often supported by desktop OpenGL implementations.
1007 See http://en.wikipedia.org/wiki/S3_Texture_Compression about S3TC. }
1008 tcDxt3,
1009
1010 { S3TC DXT5 compression, @bold(for RGBA images with full alpha channel),
1011 best for images with smooth alpha transitions.
1012 This compression format is often supported by desktop OpenGL implementations.
1013 See http://en.wikipedia.org/wiki/S3_Texture_Compression about S3TC. }
1014 tcDxt5,
1015
1016 { PowerVR texture compression (PVRTC) format.
1017 Supported by some Android and iOS devices,
1018 using PowerVR GPU by Imagination Technologies.
1019 See http://en.wikipedia.org/wiki/PVRTC . }
1020 tcPvrtc1_4bpp_RGB,
1021 tcPvrtc1_2bpp_RGB,
1022 tcPvrtc1_4bpp_RGBA,
1023 tcPvrtc1_2bpp_RGBA,
1024 tcPvrtc2_4bpp,
1025 tcPvrtc2_2bpp,
1026
1027 { ATI texture compression format, @bold(for RGB images without alpha).
1028 Supported by some Android devices (Adreno GPU from Qualcomm). }
1029 tcATITC_RGB,
1030
1031 { ATI texture compression format, @bold(with sharp alpha).
1032 Supported by some Android devices (Adreno GPU from Qualcomm). }
1033 tcATITC_RGBA_ExplicitAlpha,
1034
1035 { ATI texture compression format, @bold(with smooth alpha).
1036 Supported by some Android devices (Adreno GPU from Qualcomm). }
1037 tcATITC_RGBA_InterpolatedAlpha,
1038
1039 { ETC texture compression, @bold(without alpha).
1040 See http://en.wikipedia.org/wiki/Ericsson_Texture_Compression .
1041 Available on almost all Android OpenGLES 2.0 devices,
1042 unfortunately it doesn't support alpha channel. }
1043 tcETC1,
1044
1045 { ASTC compression with alpha - should be available on all modern mobile GPU.
1046 See https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_texture_compression_astc_hdr.txt}
1047 tcASTC_4x4_RGBA,
1048 tcASTC_5x4_RGBA,
1049 tcASTC_5x5_RGBA,
1050 tcASTC_6x5_RGBA,
1051 tcASTC_6x6_RGBA,
1052 tcASTC_8x5_RGBA,
1053 tcASTC_8x6_RGBA,
1054 tcASTC_8x8_RGBA,
1055 tcASTC_10x5_RGBA,
1056 tcASTC_10x6_RGBA,
1057 tcASTC_10x8_RGBA,
1058 tcASTC_10x10_RGBA,
1059 tcASTC_12x10_RGBA,
1060 tcASTC_12x12_RGBA,
1061 tcASTC_4x4_SRGB8_ALPHA8,
1062 tcASTC_5x4_SRGB8_ALPHA8,
1063 tcASTC_5x5_SRGB8_ALPHA8,
1064 tcASTC_6x5_SRGB8_ALPHA8,
1065 tcASTC_6x6_SRGB8_ALPHA8,
1066 tcASTC_8x5_SRGB8_ALPHA8,
1067 tcASTC_8x6_SRGB8_ALPHA8,
1068 tcASTC_8x8_SRGB8_ALPHA8,
1069 tcASTC_10x5_SRGB8_ALPHA8,
1070 tcASTC_10x6_SRGB8_ALPHA8,
1071 tcASTC_10x8_SRGB8_ALPHA8,
1072 tcASTC_10x10_SRGB8_ALPHA8,
1073 tcASTC_12x10_SRGB8_ALPHA8,
1074 tcASTC_12x12_SRGB8_ALPHA8
1075 );
1076 TTextureCompressions = set of TTextureCompression;
1077
1078 {$I castleimages_class_gpu_compressed.inc}
1079
1080 { Deprecated alias for TGPUCompressedImage }
1081 TS3TCImage = TGPUCompressedImage deprecated;
1082
1083 ECannotDecompressTexture = class(Exception);
1084
1085 TDecompressTextureFunction = function (const Image: TGPUCompressedImage): TCastleImage;
1086
1087 var
1088 { Assign here texture decompression function that is available.
1089 This way the "decompressor" is pluggable, which means that
1090 you can even use OpenGL to decompress textures, if you're going
1091 to load images while some OpenGL context is active. }
1092 DecompressTexture: TDecompressTextureFunction;
1093
1094 { TCastleImageClass and arrays of TCastleImageClasses ----------------------------- }
1095
1096 type
1097 { }
1098 TCastleImageClass = class of TCastleImage;
1099 TEncodedImageClass = class of TEncodedImage;
1100
1101 { Check is ImageClass one of the items in the ImageClasses array,
1102 or a descendant of one of them. }
1103 function InImageClasses(ImageClass: TEncodedImageClass;
1104 const ImageClasses: array of TEncodedImageClass): boolean; overload;
1105
1106 { Check is Image class one of the items in the ImageClasses array,
1107 or a descendant of one of them.
1108 This is a shortcut for InImageClasses(Image.ClassType, ImageClasses). }
1109 function InImageClasses(Image: TEncodedImage;
1110 const ImageClasses: array of TEncodedImageClass): boolean; overload;
1111
1112 (*Check if both arrays contain exactly the same classes in the same order.
1113
1114 May be extended in the future to do better checks and return true
1115 also if both array contain the same classes but in different order,
1116 and one array may contain the same classes duplicated any times.
1117 So the intention is that you should treat both arrays as sets
1118 (i.e. order of elements is ignored).
1119
1120 The problem is that this function should be lighting fast.
1121 As the main purpose of it is to use it in constructions like
1122 setting property values, e.g.
1123
1124 @longCode(#
1125 if ImageClassesArraysEqual(Value, SomeProperty) then
1126 begin
1127 SomeProperty := Value;
1128 { ... do some lengthy operations to update new value of SomeProperty ... }
1129 end;
1130 #)
1131
1132 Doing smarter checks may cost us a little time.
1133
1134 So for now this function returns
1135 @unorderedList(
1136 @item @true if for sure both arrays contain the same classes and
1137 @item @false if @italic(possibly) they don't contain the same classes.
1138 ) *)
1139 function ImageClassesEqual(const Ar1, Ar2: array of TEncodedImageClass): boolean;
1140
1141 { TCastleImage basic descendants --------------------------------------------- }
1142
1143 type
1144 TRGBAlphaImage = class;
1145 TRGBFloatImage = class;
1146 TGrayscaleImage = class;
1147 TGrayscaleAlphaImage = class;
1148
1149 {$I castleimages_class_grayscale.inc}
1150 {$I castleimages_class_grayscale_alpha.inc}
1151 {$I castleimages_class_rgb.inc}
1152 {$I castleimages_class_rgb_alpha.inc}
1153
1154 {$I castleimages_class_grayscale_float.inc}
1155 {$I castleimages_class_grayscale_alpha_float.inc}
1156 {$I castleimages_class_rgb_float.inc}
1157 {$I castleimages_class_rgb_alpha_float.inc}
1158
1159 { RGBE <-> 3 Single color conversion --------------------------------- }
1160
1161 { Encode RGB color as Red + Green + Blue + Exponent format.
1162 This allows you to encode high-precision colors in 4 bytes,
1163 see ifRGBE image format for pointers why this is useful.
1164
1165 Each component of V (red, green, blue) must be from range
1166 [0, +infinity), not merely from [0, 1].
1167 That is, V must have only nonnegative values. }
1168 function Vector3ToRGBE(const v: TVector3): TVector4Byte; deprecated 'RGBE compression should be internal in CGE or Vampyre';
1169
1170 { Decode Red + Green + Blue + Exponent back into RGB (3 floats). }
1171 function VectorRGBETo3Single(const v: TVector4Byte): TVector3; deprecated 'RGBE compression should be internal in CGE or Vampyre';
1172
1173 { File formats managing ----------------------------------------------------- }
1174
1175 { Does this MIME type correspond to image. }
1176 function IsImageMimeType(const MimeType: string;
1177 const OnlyLoadable, OnlySaveable: boolean): boolean;
1178
1179 { Add all image MIME types to the list (unless they are already there). }
1180 procedure AddImageMimeTypes(const MimeTypes: TStrings;
1181 const OnlyLoadable, OnlySaveable: boolean);
1182
1183 { Add all image extensions (with leading dots) (unless they are already there). }
1184 procedure AddImageExtensions(const Extensions: TStrings;
1185 const OnlyLoadable, OnlySaveable: boolean);
1186
1187 { List available image file formats.
1188
1189 This is basically for debug/info purposes, you can show this to user
1190 to let him know which formats are supported (and by which extensions
1191 they are recognized). Although almost always a better way to show
1192 this to user is just to use SaveImage_FileFilters with a save dialog
1193 like TCastleWindow.FileDialog,
1194 this shows file types in the open/save dialog,
1195 so it's most natural and convenient to user.
1196
1197 ListImageExtsLong produces a multiline info (separated by NL, last line not terminated
1198 by NL), shows all extensions and FormatName for each file format.
1199 Each line starts with LinePrefix.
1200
1201 ListImageExtsShort writes all recognized extensions separated by comma (', ').
1202
1203 @groupBegin }
1204 function ListImageExtsLong(OnlyLoadable, OnlySaveable: boolean; const LinePrefix: string): string;
1205 function ListImageExtsShort(OnlyLoadable, OnlySaveable: boolean): string;
1206 { @groupEnd }
1207
1208 { Guess MIME type from image extension. Empty string if cannot guess. }
1209 function ImageExtToMimeType(Ext: string): string; deprecated 'use UriMimeType';
1210
1211 { loading image -------------------------------------------------------------- }
1212
1213 type
1214 { }
1215 EImageLoadError = class(Exception);
1216 EInvalidImageFormat = class(EImageLoadError);
1217 EUnableToLoadImage = class(EImageLoadError);
1218
1219 EImageFormatNotSupported = class(Exception);
1220
1221 type
1222 TLoadImageOption = (liFlipVertically);
1223 TLoadImageOptions = set of TLoadImageOption;
1224
1225 { TODO: add LoadImageGuess which guesses the format based on content. }
1226
1227 (*The ultimate procedure to load an image from a file or URL.
1228
1229 URL is downloaded using CastleDownload unit.
1230 As always, if you all you care about is loading normal files, then just pass
1231 a normal filename (absolute or relative to the current directory)
1232 as the URL parameter.
1233
1234 Simple examples:
1235
1236 @longCode(#
1237 { When you don't care what TCastleImage descendant you get: }
1238 Image := LoadImage('image.png');
1239
1240 { When you insist on getting TRGBImage, that is 8-bit color image
1241 without an alpha channel. }
1242 ImageRGB := LoadImage('image.png', [TRGBImage]) as TRGBImage;
1243 #)
1244
1245 Image file format may be given explicitly (overloaded version with
1246 Format parameter), or guessed based on URL extension
1247 (which can be given explicitly by TypeExt,
1248 or automatically calculated from full URL).
1249 For now, we cannot guess the file format based on file contents
1250 or MIME type (the latter case would be sensible for http URLs).
1251
1252 AllowedImageClasses says what image classes are allowed.
1253 As a special case, AllowedImageClasses = [] is equivalent to
1254 AllowedImageClasses = [TCastleImage] which says that all TCastleImage descendants
1255 are allowed. Then this function will do everything it can to load
1256 any image into the best subclass of TCastleImage, losing as little image
1257 information it can.
1258
1259 Example: consider you're loading a PNG file. Let's suppose you're
1260 loading it with AllowedImageClasses = []. Then you can get
1261 TGrayscaleImage, TGrayscaleAlphaImage, TRGBImage, TRGBAlphaImage,
1262 depending on whether PNG file is grayscale or not and has alpha or not.
1263 Now let's suppose you specified AllowedImageClasses = [TRGBImage].
1264 If PNG file will not be grayscale and not have alpha channel,
1265 LoadImage will return TRGBImage descendant, as before.
1266 But if PNG fill *will* have alpha channel then
1267 LoadImage will simply ignore (strip) alpha channel and return you TRGBImage.
1268
1269 Similar thing for grayscale: if image file was grayscale but you requested
1270 only TRGBImage, then grayscale may be "expanded" into full three-channel
1271 RGB.
1272
1273 There can also happen reverse situation: you e.g. insist that
1274 AllowedImageClasses = [TRGBAlphaImage] but given PNG image does not
1275 have alpha channel. In this case LoadImage may add "dummy" alpha channel
1276 (everywhere equal to 1.0 or High(Byte)).
1277 Similar thing when you e.g. gave AllowedImageClasses = [TRGBFloatImage]
1278 but you're loading from PNG image. In this case you want float precision,
1279 but image file cannot offer it. So LoadImage can simply convert
1280 discreet values to appropriating floating point values.
1281
1282 If at any point LoadImage will find that it's unable to satisfy
1283 AllowedImageClasses, it will raise @link(EUnableToLoadImage).
1284
1285 @raises(EUnableToLoadImage If Image cannot be loaded into
1286 allowed AllowedImageClasses.)
1287
1288 @raises(EImageFormatNotSupported If image file format cannot be loaded at all.
1289 This can happen if format is totally unknown (not recognized
1290 MIME type, derived from file extension in case of local files)
1291 or if this image format cannot be loaded at all.)
1292
1293 @raises(EImageLoadError If the image file cannot be processed for some reason.)
1294
1295 @raises(Exception Various TStream instances (used internally by the
1296 @link(Download) function) may raise exceptions in case the stream cannot
1297 be created for reading.
1298 Right now, we simply let these exceptions to "pass through" from this function
1299 (instead of catching and re-raising).
1300 So be ready that this function may raise @italic(any) Exception class.
1301 In case of local files (file:// URLs), the typical exceptions are
1302 EFOpenError and EReadError.)
1303
1304 @seealso LoadEncodedImage
1305
1306 @groupBegin *)
1307 function LoadImage(Stream: TStream; const MimeType: string;
1308 const AllowedImageClasses: array of TEncodedImageClass)
1309 :TCastleImage; overload;
1310
1311 function LoadImage(const Url: String): TCastleImage; overload;
1312 function LoadImage(const Url: String;
1313 const AllowedImageClasses: array of TEncodedImageClass)
1314 :TCastleImage; overload;
1315 function LoadImage(const Url: String;
1316 const AllowedImageClasses: array of TEncodedImageClass;
1317 const ResizeWidth, ResizeHeight: Cardinal;
1318 const Interpolation: TResizeInterpolation = riBilinear;
1319 const Options: TLoadImageOptions = []): TCastleImage; overload;
1320 { @groupEnd }
1321
1322 { Load image to TEncodedImage format.
1323 This allows loading image compressed with GPU, which is good for optimally
1324 loading it to GPU. However, the operations on GPU-compressed image are very
1325 limited, we generally cannot do much with GPU-compressed data except
1326 rendering it.
1327
1328 @seealso LoadImage
1329
1330 @groupBegin }
1331 function LoadEncodedImage(Stream: TStream; const MimeType: string;
1332 const AllowedImageClasses: array of TEncodedImageClass;
1333 const Options: TLoadImageOptions = [])
1334 :TEncodedImage; overload;
1335 function LoadEncodedImage(const Url: String;
1336 const Options: TLoadImageOptions = []): TEncodedImage; overload;
1337 function LoadEncodedImage(Url: String;
1338 const AllowedImageClasses: array of TEncodedImageClass;
1339 const Options: TLoadImageOptions = [])
1340 :TEncodedImage; overload;
1341 { @groupEnd }
1342
1343 { saving image --------------------------------------------------------------- }
1344
1345 type
1346 { Raised by SaveImage when it's not possible to save image. }
1347 EImageSaveError = class(Exception);
1348
1349 { Save image to a file. Takes URL as parameter, you can give @code(file) URL
1350 or just a normal filename.
1351
1352 File format is determined by looking at URL (guessing MIME type using
1353 UriMimeType), or given explicitly as MimeType,
1354 or just given explicitly as Format parameter.
1355
1356 Image class does @bold(not)
1357 affect the created image file format, on the assumption that the
1358 "memory format" of the image (what TCastleImage descendant is used)
1359 can be orthogonal to the actual "file format" used to save this file.
1360
1361 Tries to write the image preserving it as closely as possible in this
1362 image format. When it's not possible, according conversions may be done:
1363 floating point precision of TRGBFloatImage may be lost (if saving
1364 to any file format besides RGBE file, although saving to OpenEXR may also
1365 preserve it once implemented), alpha channel may be lost,
1366 grayscale may be expanded and such.
1367
1368 Although not absolutely all conversions are implemented for now.
1369 You can be sure that
1370 all image formats (that allow any saving at all) can be saved
1371 from TRGBImage. Also TRGBFloatImage can be saved to RGBE file.
1372 Also PNG format supports full collection (grayscale/rgb, alpha/no alpha
1373 are all perfectly possible in PNG file; and TRGBFloatImage will be just converted
1374 to 8-bit RGB before saving to PNG).
1375
1376 @raises(EImageSaveError When it's not possible to save image,
1377 because of Img class (memory format) and/or image file format.)
1378
1379 @groupBegin }
1380 procedure SaveImage(const Img: TEncodedImage; const MimeType: string; Stream: TStream); overload;
1381 procedure SaveImage(const Img: TEncodedImage; const Url: String); overload;
1382 { @groupEnd }
1383
1384 { Other TCastleImage processing ---------------------------------------------------- }
1385
1386 { Choose TCastleImage descendant best matching for this image file format.
1387 The only purpose of this for now is to pick TRGBFloatImage for RGBE files,
1388 chooses TRGBImage for anything else.
1389
1390 For the overloaded version with URL, file format is determined
1391 by guessing based on file extension.
1392
1393 @groupBegin }
1394 function ImageClassBestForSavingToFormat(const Url: String): TCastleImageClass;
1395 deprecated 'implement this logic yourself; the fact that this may return TRGBImage, disregarging possible alpha, is misleading';
1396 { @groupEnd }
1397
1398 var
1399 { File filters if you want to choose a file that can be loaded/saved
1400 by appropriate functions from Images unit.
1401
1402 These objects should be treated as read-only outside this unit.
1403 Initialization / finalization of this unit automatically take care of them.
1404
1405 @groupBegin }
1406 LoadImage_FileFilters: TFileFilterList;
1407 SaveImage_FileFilters: TFileFilterList;
1408 { @groupEnd }
1409
1410 { Maximum alpha channel type. Chooses "full range" if anything is "full range",
1411 otherwise choose "simple yes/no" if anything is "simple yes/no",
1412 otherwise returns "no alpha channel". }
1413 procedure AlphaMaxVar(var A: TAlphaChannel; const B: TAlphaChannel);
1414
1415 function StringToAlpha(S: string; var WarningDone: boolean): TAutoAlphaChannel;
1416
1417 const
1418 AlphaToString: array [TAutoAlphaChannel] of string =
1419 ('AUTO', 'NONE', 'TEST', 'BLENDING');
1420
1421 type
1422 TTextureCompressionInfo = {$ifdef FPC} object {$else} record {$endif}
1423 Name: string;
1424 RequiresPowerOf2: boolean;
1425 AlphaChannel: TAlphaChannel;
1426
1427 { When generating to DDS (that has reverted row order with respect to OpenGL),
1428 most of the compressed textures should be stored as flipped.
1429 When reading, we expect them to be already flipped.
1430 When loading to OpenGL, they will effectively be flipped again
1431 (since OpenGL expects bottom-to-top order, while we load it
1432 image in top-to-bottom order), thus making the image correct.
1433
1434 The exceptions are DXT* formats, that we can read correctly (unflipped)
1435 from DDS.
1436
1437 This is only a limitation of the DDS format.
1438
1439 For KTX, we can generate KTX images using PowerVR Texture Tools
1440 that already have a correct (bottom-to-top) orientation.
1441 So we can have textures compressed to PVRTC1_4bpp_RGB
1442 with correct orientation.
1443
1444 This field is ignored if FileExtension is not .dds. }
1445 DDSFlipped: boolean;
1446
1447 { File extension/format the engine expects when try load GPU compressed
1448 version of texture. }
1449 FileExtension: String;
1450 end;
1451
1452 const
1453 TextureCompressionInfo: array [TTextureCompression] of TTextureCompressionInfo =
1454 ( (Name: 'DXT1_RGB' ; RequiresPowerOf2: false; AlphaChannel: acNone ; DDSFlipped: false; FileExtension: '.dds'),
1455 (Name: 'DXT1_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acTest ; DDSFlipped: false; FileExtension: '.dds'),
1456 (Name: 'DXT3' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: false; FileExtension: '.dds'),
1457 (Name: 'DXT5' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: false; FileExtension: '.dds'),
1458 { See http://community.imgtec.com/files/pvrtc-texture-compression-user-guide/
1459 "PVRTC2 vs PVRTC1" section --- PVRTC1 require power-of-two. } { }
1460 (Name: 'PVRTC1_4bpp_RGB' ; RequiresPowerOf2: true ; AlphaChannel: acNone ; DDSFlipped: true; FileExtension: '.dds'),
1461 (Name: 'PVRTC1_2bpp_RGB' ; RequiresPowerOf2: true ; AlphaChannel: acNone ; DDSFlipped: true; FileExtension: '.dds'),
1462 (Name: 'PVRTC1_4bpp_RGBA' ; RequiresPowerOf2: true ; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: '.dds'),
1463 (Name: 'PVRTC1_2bpp_RGBA' ; RequiresPowerOf2: true ; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: '.dds'),
1464 (Name: 'PVRTC2_4bpp' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: '.dds'),
1465 (Name: 'PVRTC2_2bpp' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: '.dds'),
1466 { Tests show that ATITC does not need power-of-two sizes. }
1467 (Name: 'ATITC_RGB' ; RequiresPowerOf2: false; AlphaChannel: acNone ; DDSFlipped: true; FileExtension: '.dds'),
1468 (Name: 'ATITC_RGBA_ExplicitAlpha' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: '.dds'),
1469 (Name: 'ATITC_RGBA_InterpolatedAlpha'; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: '.dds'),
1470 { TODO: unconfirmed RequiresPowerOf2 for ETC1. } { }
1471 (Name: 'ETC1' ; RequiresPowerOf2: true ; AlphaChannel: acNone ; DDSFlipped: true; FileExtension: '.ktx'),
1472
1473 (Name: 'ASTC_4x4_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1474 (Name: 'ASTC_5x4_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1475 (Name: 'ASTC_5x5_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1476 (Name: 'ASTC_6x5_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1477 (Name: 'ASTC_6x6_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1478 (Name: 'ASTC_8x5_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1479 (Name: 'ASTC_8x6_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1480 (Name: 'ASTC_8x8_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1481 (Name: 'ASTC_10x5_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1482 (Name: 'ASTC_10x6_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1483 (Name: 'ASTC_10x8_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1484 (Name: 'ASTC_10x10_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1485 (Name: 'ASTC_12x10_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1486 (Name: 'ASTC_12x12_RGBA' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1487 (Name: 'ASTC_4x4_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1488 (Name: 'ASTC_5x4_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1489 (Name: 'ASTC_5x5_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1490 (Name: 'ASTC_6x5_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1491 (Name: 'ASTC_6x6_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1492 (Name: 'ASTC_8x5_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1493 (Name: 'ASTC_8x6_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1494 (Name: 'ASTC_8x8_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1495 (Name: 'ASTC_10x5_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1496 (Name: 'ASTC_10x6_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1497 (Name: 'ASTC_10x8_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1498 (Name: 'ASTC_10x10_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1499 (Name: 'ASTC_12x10_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif}),
1500 (Name: 'ASTC_12x12_SRGB8_ALPHA8' ; RequiresPowerOf2: false; AlphaChannel: acBlending; DDSFlipped: true; FileExtension: {$ifdef USE_ASTCENC} '.atcs' {$else} '.ktx' {$endif})
1501 );
1502
1503 { Convert TTextureCompression enum to string. }
1504 function TextureCompressionToString(const TextureCompression: TTextureCompression): string;
1505
1506 { Convert string to TTextureCompression enum. Possible values correspond
1507 to names listed in TextureCompressionInfo array, they are also equal
1508 to enum Pascal names without leading "tc".
1509 Compares given strig ignoring the case.
1510 @raises(Exception If the string value does not name any
1511 TTextureCompression value.) }
1512 function StringToTextureCompression(const S: string): TTextureCompression;
1513
1514 type
1515 { Listener type for @link(AddLoadImageListener). }
1516 TLoadImageEvent = procedure (var ImageUrl: String) of object;
1517
1518 var
1519 { Is the value of @link(SupportedTextureCompression) determined
1520 by the renderer (like OpenGL context) parameters. }
1521 SupportedTextureCompressionKnown: boolean;
1522
1523 { Which texture compression values are supported by
1524 the renderer (like OpenGL context). }
1525 SupportedTextureCompression: TTextureCompressions;
1526
1527 (*All image URLs are processed by this event before loading.
1528 This allows to globally modify / observe your images paths,
1529 e.g. to use GPU compressed alternative versions.
1530
1531 The URL processing is automatically used by all image loaders.
1532 This includes @link(LoadImage), @link(LoadEncodedImage)
1533 and (internal) @code(TCompositeImage.LoadFromFile).
1534
1535 The URL processing is automatically used to automatically use GPU compressed textures.
1536 See https://castle-engine.io/creating_data_auto_generated_textures.php .
1537
1538 @italic(An example:) To work on any GPU, you want to have various
1539 versions of your textures (uncompressed, and also compressed with
1540 various GPU algorithms) in your data.
1541 Use this procedure to redirect all image loading to use your
1542 compressed versions, when they are supported by the GPU.
1543 By doing it like this we capture all kinds of image loading --- from TDrawableImage,
1544 from TCastleScene and so on.
1545
1546 @longCode(#
1547 uses ..., CastleUriUtils, CastleGLUtils, CastleLog, CastleStringUtils,
1548 CastleFilesUtils;
1549
1550 procedure TTextureUtils.GPUTextureAlternative(var ImageUrl: String);
1551 begin
1552 if IsPrefix('castle-data:/animation/dragon/', ImageUrl) then
1553 begin
1554 if GLFeatures = nil then
1555 WritelnWarning('TextureCompression', 'Cannot determine whether to use GPU compressed version for ' + ImageUrl + ' because the image is loaded before GPU capabilities are known') else
1556 if tcPvrtc1_4bpp_RGBA in GLFeatures.TextureCompression then
1557 begin
1558 ImageUrl := ExtractURIPath(ImageUrl) + 'compressed/pvrtc1_4bpp_rgba/' +
1559 ExtractURIName(ImageUrl) + '.dds';
1560 WritelnLog('TextureCompression', 'Using compressed alternative ' + ImageUrl);
1561 end;
1562 end;
1563 end;
1564
1565 initialization
1566 AddLoadImageListener({$ifdef FPC}@{$endif} MyTextureUtils.GPUTextureAlternative);
1567 finalization
1568 RemoveLoadImageListener({$ifdef FPC}@{$endif} MyTextureUtils.GPUTextureAlternative);
1569 end.
1570 #)
1571 *)
1572 procedure AddLoadImageListener(const Event: TLoadImageEvent);
1573
1574 { Remove listener added by @link(AddLoadImageListener). }
1575 procedure RemoveLoadImageListener(const Event: TLoadImageEvent);
1576
1577 { Process URL through events registered by @link(AddLoadImageListener).
1578 This is used internally by the engine. }
1579 function ProcessImageUrl(const Url: String): string;
1580
1581 { @exclude }
1582 function InternalDetectClassPNG(const Stream: TStream): TEncodedImageClass;
1583
1584 {$undef read_interface}
1585
1586 implementation
1587
1588 uses {$ifdef FPC} ExtInterpolation, FPCanvas, FPImgCanv, {$endif}
1589 {$ifdef USE_VAMPYRE_IMAGING} Imaging, ImagingClasses, ImagingTypes,
1590 { Using ImagingExtFileFormats explicitly is not actually necessary anymore --
1591 Imaging unit automatically uses it.
1592 It was necessary in the past, because we used VampyreImagingPackage.lpk,
1593 which defined DONT_LINK_EXTRAS. }
1594 ImagingExtFileFormats,
1595 {$endif}
1596 CastleInternalZLib, CastleStringUtils, CastleFilesUtils, CastleLog, CastleDynLib,
1597 CastleInternalCompositeImage, CastleDownload, CastleUriUtils, CastleTimeUtils,
1598 CastleStreamUtils, CastleInternalDataCompression;
1599
1600 { Like GrayscaleValue, but also convert input Byte to output Single
1601 (converting 0..255 to 0..1). }
1602 function GrayscaleValueFromByteToSingle(const V: TVector3Byte): Single; overload; forward;
1603
1604 { Like GrayscaleValue, but also convert input Byte to output Single
1605 (converting 0..255 to 0..1). }
1606 function GrayscaleValueFromByteToSingle(const V: TVector4Byte): Single; overload; forward;
1607
1608 { parts ---------------------------------------------------------------------- }
1609
1610 {$define read_implementation}
1611 {$I castleimages_vampyre_imaging.inc}
1612 {$I castleimages_file_formats.inc} // must be included after castleimages_vampyre_imaging.inc
1613 {$I castleimages_draw.inc}
1614 {$I castleimages_paint.inc}
1615 {$I castleimages_astc.inc}
1616 {$I castleimages_libpng.inc}
1617 {$I castleimages_fpimage.inc}
1618 {$I castleimages_loading_saving_func.inc}
1619 {$I castleimages_vcl_imaging.inc}
1620 {$I castleimages_png.inc} // must be included after castleimages_libpng.inc and castleimages_fpimage.inc
1621 {$I castleimages_composite.inc}
1622 {$I castleimages_assign.inc}
1623
1624 {$I castleimages_class_gpu_compressed.inc}
1625
1626 // Byte image formats
1627 {$I castleimages_class_grayscale.inc}
1628 {$I castleimages_class_grayscale_alpha.inc}
1629 {$I castleimages_class_rgb.inc}
1630 {$I castleimages_class_rgb_alpha.inc}
1631
1632 // Floating-point (Single) image formats
1633 {$I castleimages_class_grayscale_float.inc}
1634 {$I castleimages_class_grayscale_alpha_float.inc}
1635 {$I castleimages_class_rgb_float.inc}
1636 {$I castleimages_class_rgb_alpha_float.inc}
1637
1638 { Colors ------------------------------------------------------------------ }
1639
1640 function EqualRGB(const Color1, Color2: TVector3Byte; Tolerance: Byte): boolean;
1641 begin
1642 result:=(Abs(Smallint(Color1.X) - Color2.X) <= Tolerance) and
1643 (Abs(Smallint(Color1.Y) - Color2.Y) <= Tolerance) and
1644 (Abs(Smallint(Color1.Z) - Color2.Z) <= Tolerance);
1645 end;
1646
1647 function GrayscaleValueFromByteToSingle(const V: TVector3Byte): Single; overload;
1648 begin
1649 // force multiplication as Word
1650 Result := (
1651 Word(54 ) * V.X +
1652 Word(183) * V.Y +
1653 Word(19 ) * V.Z
1654 ) / (256 * 256);
1655 end;
1656
1657 function GrayscaleValueFromByteToSingle(const V: TVector4Byte): Single; overload;
1658 var
1659 Rgb: TVector3Byte absolute V;
1660 begin
1661 Result := GrayscaleValueFromByteToSingle(Rgb);
1662 end;
1663
1664 { TEncodedImage -------------------------------------------------------------- }
1665
1666 destructor TEncodedImage.Destroy;
1667 begin
1668 FreeMemNiling(FRawPixels);
1669 inherited;
1670 end;
1671
1672 function TEncodedImage.Dimensions: TVector3Cardinal;
1673 begin
1674 Result.X := Width;
1675 Result.Y := Height;
1676 Result.Z := Depth;
1677 end;
1678
1679 function TEncodedImage.IsEmpty: boolean;
1680 begin
1681 Result := RawPixels = nil;
1682 end;
1683
1684 function TEncodedImage.HasAlpha: boolean;
1685 begin
1686 Result := false;
1687 end;
1688
1689 function TEncodedImage.AlphaChannel(
1690 const AlphaTolerance: Byte): TAlphaChannel;
1691 begin
1692 Result := acNone;
1693 end;
1694
1695 function TEncodedImage.Rect: TRectangle;
1696 begin
1697 Result := Rectangle(0, 0, Width, Height);
1698 end;
1699
1700 procedure TEncodedImage.NotImplemented(const AMethodName: string);
1701 begin
1702 raise EInternalError.Create(AMethodName +
1703 ' method not implemented for the image class ' + ClassName);
1704 end;
1705
1706 { TCastleImage --------------------------------------------------------------- }
1707
1708 constructor TCastleImage.Create;
1709 begin
1710 inherited;
1711 { Everything is already initialized to nil and 0. }
1712 end;
1713
1714 constructor TCastleImage.Create(
1715 const AWidth, AHeight: Cardinal;
1716 const ADepth: Cardinal = 1);
1717 begin
1718 Create;
1719 SetSize(AWidth, AHeight, ADepth);
1720 end;
1721
1722 procedure TCastleImage.Empty;
1723 begin
1724 FreeMemNiling(FRawPixels);
1725 FWidth := 0;
1726 FHeight := 0;
1727 FDepth := 0;
1728 end;
1729
1730 procedure TCastleImage.SetSize(const AWidth, AHeight: Cardinal;
1731 const ADepth: Cardinal = 1);
1732 begin
1733 if (FWidth <> AWidth) or
1734 (FHeight <> AHeight) or
1735 (FDepth <> ADepth) then
1736 begin
1737 FreeMemNiling(FRawPixels);
1738 FWidth := AWidth;
1739 FHeight := AHeight;
1740 FDepth := ADepth;
1741 if (AWidth <> 0) and (AHeight <> 0) and (ADepth <> 0) then
1742 FRawPixels := GetMem(PixelSize * AWidth * AHeight * ADepth);
1743 end;
1744 end;
1745
1746 procedure TCastleImage.SetSize(const Source: TCastleImage);
1747 begin
1748 SetSize(Source.Width, Source.Height, Source.Depth);
1749 end;
1750
1751 function TCastleImage.PixelPtr(const X, Y: Cardinal; const Z: Cardinal = 0): Pointer;
1752 begin
1753 Result := PointerAdd(RawPixels, PixelSize * (Width * (Height * Z + Y) + X));
1754 end;
1755
1756 function TCastleImage.RowPtr(const Y: Cardinal; const Z: Cardinal = 0): Pointer;
1757 begin
1758 Result := PointerAdd(RawPixels, PixelSize * (Width * (Height * Z + Y)));
1759 end;
1760
1761 procedure TCastleImage.InvertColors;
1762 begin
1763 NotImplemented('InvertColors');
1764 end;
1765
1766 procedure TCastleImage.SetColorRGB(const X, Y: Integer; const V: TVector3);
1767 begin
1768 SetColors(X, Y, 0, Vector4(V, 1));
1769 end;
1770
1771 function TCastleImage.GetColors(const X, Y, Z: Integer): TCastleColor;
1772 begin
1773 NotImplemented('GetColor');
1774 Result := TVector4.Zero; // silence warning
1775 end;
1776
1777 procedure TCastleImage.SetColors(const X, Y, Z: Integer; const C: TCastleColor);
1778 begin
1779 NotImplemented('SetColor');
1780 end;
1781
1782 function TCastleImage.Size: Cardinal;
1783 begin
1784 Result := Width * Height * Depth * PixelSize;
1785 end;
1786
1787 function TCastleImage.ImageSize: Cardinal;
1788 begin
1789 Result := Size;
1790 end;
1791
1792 function TCastleImage.MakeCopy: TCastleImage;
1793 begin
1794 Result := CreateCopy as TCastleImage;
1795 end;
1796
1797 function TCastleImage.CreateCopy: TEncodedImage;
1798 begin
1799 Result := TCastleImageClass(Self.ClassType).Create;
1800 TCastleImage(Result).Assign(Self);
1801 end;
1802
1803 type
1804 TMixColorsFunction = procedure (const OutputColor: Pointer;
1805 const Weights: TVector4; const AColors: TVector4Pointer) of object;
1806
1807 { This does the real resizing work.
1808 It assumes that SourceData and DestinData pointers are already allocated.
1809 DestinWidth, DestinHeight must not be 0. }
1810 procedure InternalResize(PixelSize: Cardinal;
1811 const SourceData: Pointer; const SourceRect: TRectangle; const SourceWidth, SourceHeight: Cardinal;
1812 const DestinData: Pointer; const DestinRect: TRectangle; const DestinWidth, DestinHeight: Cardinal;
1813 const Interpolation: TResizeInterpolationInternal;
1814 const MixColors: TMixColorsFunction);
1815 var
1816 DestinY: Integer;
1817
1818 procedure MakeLineNearest;
1819 { write row DestinY of DestinData }
1820 var
1821 DestinX, SourceX, SourceY: Integer;
1822 SourceRow, DestinRow: PtrUInt;
1823 begin
1824 SourceY := SourceRect.ClampY(DestinY * SourceHeight div DestinHeight);
1825 SourceRow := PtrUInt(SourceData) + SourceWidth * SourceY * PixelSize;
1826 DestinRow := PtrUInt(DestinData) + DestinWidth * DestinY * PixelSize;
1827
1828 for DestinX := DestinRect.Left to DestinRect.Right - 1 do
1829 begin
1830 SourceX := SourceRect.ClampX(DestinX * SourceWidth div DestinWidth);
1831 Move(Pointer(PtrUInt(SourceRow + SourceX * PixelSize))^,
1832 Pointer(PtrUInt(DestinRow + DestinX * PixelSize))^,
1833 PixelSize);
1834 end;
1835 end;
1836
1837 procedure MakeLineBilinear;
1838 var
1839 { For every destination pixel, we consider 4 neighbor source pixels.
1840 - SourceX1 / SourceX2 are smaller / larger X coordinates in source.
1841 - SourceY1 / SourceY2 are smaller / larger Y coordinates in source.
1842 - SourceXFrac / SourceYFrac are fractional parts (in [0..1])
1843 that say how close our perfect point (from which we should take
1844 destination color) is to 4 neighbor pixels. }
1845 DestinX, SourceX1, SourceX2, SourceY1, SourceY2: Integer;
1846 Source1Row, Source2Row, DestinRow: PtrUInt;
1847 SourceXFrac, SourceYFrac: Single;
1848 Weights: TVector4;
1849 Colors: TVector4Pointer;
1850 begin
1851 SourceYFrac := DestinY * SourceHeight / DestinHeight;
1852 SourceY1 := Max(Trunc(SourceYFrac), SourceRect.Bottom);
1853 SourceY2 := Min(SourceY1 + 1, SourceRect.Top - 1);
1854 SourceYFrac := Frac(SourceYFrac);
1855 Source1Row := PtrUInt(SourceData) + SourceWidth * SourceY1 * PixelSize;
1856 Source2Row := PtrUInt(SourceData) + SourceWidth * SourceY2 * PixelSize;
1857 DestinRow := PtrUInt(DestinData) + DestinWidth * DestinY * PixelSize;
1858
1859 for DestinX := DestinRect.Left to DestinRect.Right - 1 do
1860 begin
1861 SourceXFrac := DestinX * SourceWidth / DestinWidth;
1862
1863 SourceX1 := Trunc(SourceXFrac);
1864 if SourceX1 < SourceRect.Left then
1865 SourceX1 := SourceRect.Left;
1866
1867 SourceX2 := SourceX1 + 1;
1868 if SourceX2 >= SourceRect.Right then
1869 SourceX2 := SourceRect.Right - 1;
1870
1871 SourceX1 := SourceX1 * PixelSize;
1872 SourceX2 := SourceX2 * PixelSize;
1873
1874 SourceXFrac := Frac(SourceXFrac);
1875 Weights.X := SourceXFrac * SourceYFrac;
1876 Colors.X := Pointer(PtrUInt(Source2Row + SourceX2));
1877 Weights.Y := (1 - SourceXFrac) * SourceYFrac;
1878 Colors.Y := Pointer(PtrUInt(Source2Row + SourceX1));
1879 Weights.Z := (1 - SourceXFrac) * (1 - SourceYFrac);
1880 Colors.Z := Pointer(PtrUInt(Source1Row + SourceX1));
1881 Weights.W := SourceXFrac * (1 - SourceYFrac);
1882 Colors.W := Pointer(PtrUInt(Source1Row + SourceX2));
1883 MixColors(Pointer(PtrUInt(DestinRow + DestinX * PixelSize)), Weights, Colors);
1884 end;
1885 end;
1886
1887 begin
1888 case Interpolation of
1889 riNearest:
1890 for DestinY := DestinRect.Bottom to DestinRect.Top - 1 do
1891 MakeLineNearest;
1892 riBilinear:
1893 for DestinY := DestinRect.Bottom to DestinRect.Top - 1 do
1894 MakeLineBilinear;
1895 {$ifndef COMPILER_CASE_ANALYSIS}
1896 else raise EInternalError.Create('Unknown Interpolation for InternalResize');
1897 {$endif}
1898 end;
1899 end;
1900
1901 procedure TCastleImage.Resize(ResizeWidth, ResizeHeight: Cardinal;
1902 const Interpolation: TResizeInterpolation);
1903 var
1904 NewPixels: Pointer;
1905 {$ifdef FPC}
1906 NewFpImage: TInternalCastleFpImage;
1907 {$endif FPC}
1908 begin
1909 if (Interpolation >= Low(TResizeInterpolationFpImage)) and
1910 (Interpolation <= High(TResizeInterpolationFpImage)) then
1911 begin
1912 {$ifdef FPC}
1913 NewFpImage := MakeResizedToFpImage(ResizeWidth, ResizeHeight, Interpolation);
1914 try
1915 FromFpImage(NewFpImage);
1916 finally FreeAndNil(NewFpImage) end;
1917 {$else FPC}
1918 WritelnWarning('Resizing with interpolation %d not supported with Delphi, falling back to bilinear', [
1919 Ord(Interpolation)
1920 ]);
1921 Resize(ResizeWidth, ResizeHeight, riBilinear);
1922 {$endif FPC}
1923 end else
1924 begin
1925 if ((ResizeWidth <> 0) and (ResizeWidth <> Width)) or
1926 ((ResizeHeight <> 0) and (ResizeHeight <> Height)) then
1927 begin
1928 { Make both ResizeTo* non-zero. }
1929 if ResizeWidth = 0 then ResizeWidth := Width;
1930 if ResizeHeight = 0 then ResizeHeight := Height;
1931
1932 NewPixels := GetMem(ResizeWidth * ResizeHeight * PixelSize);
1933 InternalResize(PixelSize,
1934 RawPixels, Rect, Width, Height,
1935 NewPixels, CastleRectangles.Rectangle(0, 0, ResizeWidth, ResizeHeight), ResizeWidth, ResizeHeight,
1936 Interpolation, {$ifdef FPC}@{$endif} MixColors);
1937 FreeMemNiling(FRawPixels);
1938
1939 FRawPixels := NewPixels;
1940 FWidth := ResizeWidth;
1941 FHeight := ResizeHeight;
1942 end;
1943 end;
1944 end;
1945
1946 function TCastleImage.MakeResized(ResizeWidth, ResizeHeight: Cardinal;
1947 const Interpolation: TResizeInterpolation): TCastleImage;
1948 {$ifdef FPC}
1949 var
1950 NewFpImage: TInternalCastleFpImage;
1951 {$endif FPC}
1952 begin
1953 if (Interpolation >= Low(TResizeInterpolationFpImage)) and
1954 (Interpolation <= High(TResizeInterpolationFpImage)) then
1955 begin
1956 {$ifdef FPC}
1957 NewFpImage := MakeResizedToFpImage(ResizeWidth, ResizeHeight, Interpolation);
1958 try
1959 // since we request our own class as output, CreateFromFpImage must return some TCastleImage
1960 Result := CreateFromFpImage(NewFpImage, [TCastleImageClass(ClassType)]) as TCastleImage;
1961 Result.AssignProperties(Self);
1962 finally FreeAndNil(NewFpImage) end;
1963 {$else FPC}
1964 WritelnWarning('Resizing with interpolation %d not supported with Delphi, falling back to bilinear', [
1965 Ord(Interpolation)
1966 ]);
1967 Result := MakeResized(ResizeWidth, ResizeHeight, riBilinear);
1968 {$endif FPC}
1969 end else
1970 begin
1971 { Make both ResizeTo* non-zero. }
1972 if ResizeWidth = 0 then ResizeWidth := Width;
1973 if ResizeHeight = 0 then ResizeHeight := Height;
1974
1975 Result := TCastleImageClass(ClassType).Create(ResizeWidth, ResizeHeight);
1976 try
1977 Result.FUrl := Url;
1978 if not IsEmpty then
1979 InternalResize(PixelSize,
1980 RawPixels, Rect, Width, Height,
1981 Result.RawPixels, Result.Rect, Result.Width, Result.Height,
1982 Interpolation, {$ifdef FPC}@{$endif} MixColors);
1983 Result.AssignProperties(Self)
1984 except Result.Free; raise end;
1985 end;
1986 end;
1987
1988 procedure TCastleImage.Resize3x3(const ResizeWidth, ResizeHeight: Cardinal;
1989 var Corners: TVector4Integer;
1990 const Interpolation: TResizeInterpolationInternal);
1991 var
1992 NewPixels: Pointer;
1993 NewCorners: TVector4Integer;
1994 { Position that delimit parts along X or Y, for source and destination images. }
1995 SourceXs, SourceYs, DestXs, DestYs: TVector4Integer;
1996 type
1997 TPart = 0..2;
1998
1999 procedure ResizePart(const X, Y: TPart);
2000 var
2001 SourceRect, DestRect: TRectangle;
2002 begin
2003 SourceRect := CastleRectangles.Rectangle(SourceXs.Data[X], SourceYs.Data[Y],
2004 SourceXs.Data[Integer(X) + 1] - SourceXs.Data[X],
2005 SourceYs.Data[Integer(Y) + 1] - SourceYs.Data[Y]);
2006 DestRect := CastleRectangles.Rectangle(DestXs.Data[X], DestYs.Data[Y],
2007 DestXs.Data[Integer(X) + 1] - DestXs.Data[X],
2008 DestYs.Data[Integer(Y) + 1] - DestYs.Data[Y]);
2009 InternalResize(PixelSize,
2010 RawPixels, SourceRect, Width, Height,
2011 NewPixels, DestRect, ResizeWidth, ResizeHeight,
2012 Interpolation, {$ifdef FPC}@{$endif} MixColors);
2013 end;
2014
2015 var
2016 X, Y: TPart;
2017 begin
2018 if (ResizeWidth <> Width) or (ResizeHeight <> Height) then
2019 begin
2020 NewCorners.X := Corners.X * ResizeWidth div Width;
2021 NewCorners.Y := Corners.Y * ResizeHeight div Height;
2022 NewCorners.Z := Corners.Z * ResizeWidth div Width;
2023 NewCorners.W := Corners.W * ResizeHeight div Height;
2024
2025 if not ( (Corners.W + Corners.Y < Width) and
2026 (Corners.Z + Corners.X < Height) and
2027 (NewCorners.W + NewCorners.Y < ResizeWidth) and
2028 (NewCorners.Z + NewCorners.X < ResizeHeight) ) then
2029 raise Exception.CreateFmt('TCastleImage.Resize3x3: Cannot resize image with corners because corners are larger then image size. Source corners: %s, source size: %dx%d, destination corners: %s, destination size: %dx%d',
2030 [Corners.ToString, Width, Height,
2031 NewCorners.ToString, ResizeWidth, ResizeHeight]);
2032
2033 SourceXs.X := 0;
2034 SourceXs.Y := Corners.W;
2035 SourceXs.Z := Width - Corners.Y;
2036 SourceXs.W := Width;
2037
2038 SourceYs.X := 0;
2039 SourceYs.Y := Corners.Z;
2040 SourceYs.Z := Height - Corners.X;
2041 SourceYs.W := Height;
2042
2043 DestXs.X := 0;
2044 DestXs.Y := NewCorners.W;
2045 DestXs.Z := ResizeWidth - NewCorners.Y;
2046 DestXs.W := ResizeWidth;
2047
2048 DestYs.X := 0;
2049 DestYs.Y := NewCorners.Z;
2050 DestYs.Z := ResizeHeight - NewCorners.X;
2051 DestYs.W := ResizeHeight;
2052
2053 NewPixels := GetMem(ResizeWidth * ResizeHeight * PixelSize);
2054 for X := Low(TPart) to High(TPart) do
2055 for Y := Low(TPart) to High(TPart) do
2056 ResizePart(X, Y);
2057 FreeMemNiling(FRawPixels);
2058
2059 FRawPixels := NewPixels;
2060 FWidth := ResizeWidth;
2061 FHeight := ResizeHeight;
2062 Corners := NewCorners;
2063 end;
2064 end;
2065
2066 function TCastleImage.MakeRotated(Angle: Integer): TCastleImage;
2067
2068 procedure Rotate90;
2069 var
2070 X, Y: Integer;
2071 begin
2072 Result := TCastleImageClass(ClassType).Create(Height, Width);
2073 { It is nice to keep URL meaningful,
2074 shown e.g. for rotated cubemap sides loaded to OpenGL, in TextureProfiler. }
2075 Result.Url := Url + '[rotated]';
2076 for X := 0 to Width - 1 do
2077 for Y := 0 to Height - 1 do
2078 Move(PixelPtr(X, Y)^, Result.PixelPtr(Y, Width - 1 - X)^, PixelSize);
2079 Result.AssignProperties(Self);
2080 end;
2081
2082 procedure Rotate180;
2083 var
2084 X, Y: Integer;
2085 begin
2086 Result := TCastleImageClass(ClassType).Create(Width, Height);
2087 Result.Url := Url + '[rotated]';
2088 for X := 0 to Width - 1 do
2089 for Y := 0 to Height - 1 do
2090 Move(PixelPtr(X, Y)^, Result.PixelPtr(Width - 1 - X, Height - 1 - Y)^, PixelSize);
2091 Result.AssignProperties(Self);
2092 end;
2093
2094 procedure Rotate270;
2095 var
2096 X, Y: Integer;
2097 begin
2098 Result := TCastleImageClass(ClassType).Create(Height, Width);
2099 Result.Url := Url + '[rotated]';
2100 for X := 0 to Width - 1 do
2101 for Y := 0 to Height - 1 do
2102 Move(PixelPtr(X, Y)^, Result.PixelPtr(Height - 1 - Y, X)^, PixelSize);
2103 Result.AssignProperties(Self);
2104 end;
2105
2106 begin
2107 { convert Angle to 0..3 range }
2108 Angle := Angle mod 4;
2109 if Angle < 0 then Angle := Angle + 4;
2110
2111 case Angle of
2112 1: Rotate90;
2113 2: Rotate180;
2114 3: Rotate270;
2115 else Result := MakeCopy; // else Angle = 0
2116 end;
2117 end;
2118
2119 procedure TCastleImage.AssignProperties(const Source: TCastleImage);
2120 begin
2121 // No need to do anything in TCastleImage
2122 end;
2123
2124 procedure TCastleImage.Rotate(const Angle: Integer);
2125 var
2126 New: TCastleImage;
2127 begin
2128 if Angle mod 4 = 0 then Exit; // nothing to do
2129
2130 New := MakeRotated(Angle);
2131 try
2132 Assign(New);
2133 finally FreeAndNil(New) end;
2134 end;
2135
2136 procedure TCastleImage.FlipHorizontal;
2137 var
2138 ImageRow, TmpPixel, Pix1, Pix2: Pointer;
2139 x, y: Integer;
2140 begin
2141 TmpPixel := GetMem(PixelSize);
2142 try
2143 for Y := 0 to Height-1 do
2144 begin
2145 ImageRow := RowPtr(y);
2146 for x := 0 to (Width - 1) div 2 do
2147 begin
2148 Pix1 := PointerAdd(ImageRow, Cardinal(x) * PixelSize);
2149 Pix2 := PointerAdd(ImageRow, (Width - 1 - Cardinal(x)) * PixelSize);
2150 Move(Pix1^, TmpPixel^, PixelSize);
2151 Move(Pix2^, Pix1^, PixelSize);
2152 Move(TmpPixel^, Pix2^, PixelSize);
2153 end;
2154 end;
2155 finally FreeMem(TmpPixel) end;
2156 end;
2157
2158 procedure TCastleImage.FlipVertical;
2159 var
2160 TmpRow, Row1, Row2: Pointer;
2161 Y, RowSize: Integer;
2162 begin
2163 RowSize := PixelSize * Width;
2164 TmpRow := GetMem(RowSize);
2165 try
2166 for Y := 0 to Height div 2 - 1 do
2167 begin
2168 Row1 := RowPtr(Y);
2169 Row2 := RowPtr(Height - Y - 1);
2170 Move(Row1^, TmpRow^, RowSize);
2171 Move(Row2^, Row1^, RowSize);
2172 Move(TmpRow^, Row2^, RowSize);
2173 end;
2174 finally FreeMem(TmpRow) end;
2175 end;
2176
2177 function TCastleImage.MakeTiled(TileX, TileY: Cardinal): TCastleImage;
2178 var
2179 i, j: Cardinal;
2180 begin
2181 Result := TCastleImageClass(ClassType).Create(TileX * Width, TileY * Height);
2182 try
2183 { Correct but naive version:
2184
2185 for i := 0 to result.Width-1 do
2186 for j := 0 to result.Height-1 do
2187 move(Image.PixelPtr(i mod Image.Width, j mod Image.Height)^,
2188 Result.PixelPtr( i, j)^,
2189 Result.PixelSize );
2190
2191 This can be speeded up copying whole rows at once: }
2192
2193 for i := 0 to TileX - 1 do
2194 for j := 0 to Result.Height - 1 do
2195 Move(PixelPtr(0, j mod Height)^,
2196 Result.PixelPtr(i * Width, j)^,
2197 PixelSize * Width );
2198
2199 Result.AssignProperties(Self);
2200 except Result.Free; raise end;
2201 end;
2202
2203 function TCastleImage.MakeExtracted(X0, Y0, ExtractWidth, ExtractHeight: Cardinal): TCastleImage;
2204 var
2205 y: Cardinal;
2206 begin
2207 if x0 + ExtractWidth > Width then
2208 raise EImagePosOutOfRange.Create('x0 in MakeExtracted out of range');
2209 if y0 + ExtractHeight > Height then
2210 raise EImagePosOutOfRange.Create('y0 in MakeExtracted out of range');
2211
2212 Result := TCastleImageClass(ClassType).Create(ExtractWidth, ExtractHeight);
2213 try
2214 for Y := 0 to ExtractHeight - 1 do
2215 Move(PixelPtr(x0, y + y0)^, Result.RowPtr(y)^, PixelSize * ExtractWidth);
2216 Result.AssignProperties(Self);
2217 except Result.Free; raise end;
2218 end;
2219
2220 procedure TCastleImage.Clear(const Pixel: TVector4Byte);
2221 begin
2222 NotImplemented('Clear');
2223 end;
2224
2225 procedure TCastleImage.Clear(const Pixel: TCastleColor);
2226 begin
2227 Clear(Vector4Byte(Pixel));
2228 end;
2229
2230 function TCastleImage.IsClear(const Pixel: TVector4Byte): boolean;
2231 begin
2232 NotImplemented('IsClear');
2233 { code will never get here (NotImplemented always raises an exception),
2234 and code "Result := false;" below is only to avoid compiler warning
2235 that function result is undefined. }
2236 Result := false;
2237 end;
2238
2239 procedure TCastleImage.TransformRGB(const Matrix: TMatrix3);
2240 begin
2241 NotImplemented('TransformRGB');
2242 end;
2243
2244 procedure TCastleImage.ModulateRGB(const ColorModulator: TColorModulatorByteFunc);
2245 begin
2246 NotImplemented('ModulateRGB');
2247 end;
2248
2249 function TCastleImage.MakeModulatedRGB(
2250 const ColorModulator: TColorModulatorByteFunc): TCastleImage;
2251 begin
2252 Result := MakeCopy;
2253 Result.ModulateRGB(ColorModulator);
2254 end;
2255
2256 procedure TCastleImage.Grayscale;
2257 begin
2258 ModulateRGB({$ifdef FPC}@{$endif} ColorGrayscaleByte);
2259 end;
2260
2261 procedure TCastleImage.ConvertToChannelRGB(Channel: Integer);
2262 begin
2263 case Channel of
2264 0: ModulateRGB({$ifdef FPC}@{$endif} ColorRedConvertByte);
2265 1: ModulateRGB({$ifdef FPC}@{$endif} ColorGreenConvertByte);
2266 2: ModulateRGB({$ifdef FPC}@{$endif} ColorBlueConvertByte);
2267 else raise EInternalError.Create(
2268 'ConvertToChannelRGB: Channel must be 0, 1 or 2');
2269 end;
2270 end;
2271
2272 procedure TCastleImage.StripToChannelRGB(Channel: Integer);
2273 begin
2274 case Channel of
2275 0: ModulateRGB({$ifdef FPC}@{$endif} ColorRedStripByte);
2276 1: ModulateRGB({$ifdef FPC}@{$endif} ColorGreenStripByte);
2277 2: ModulateRGB({$ifdef FPC}@{$endif} ColorBlueStripByte);
2278 else raise EInternalError.Create(
2279 'StripToChannelRGB: Channel must be 0, 1 or 2');
2280 end;
2281 end;
2282
2283 function TCastleImage.IsEqual(Image: TCastleImage): boolean;
2284 begin
2285 Result :=
2286 (Image.ClassType = ClassType) and
2287 (Image.Width = Width) and
2288 (Image.Height = Height) and
2289 (Image.Depth = Depth) and
2290 (CompareMem(Image.RawPixels, RawPixels, Size));
2291 end;
2292
2293 function TCastleImage.ArePartsEqual(
2294 const SelfX0, SelfY0, SelfWidth, SelfHeight: Cardinal;
2295 Image: TCastleImage;
2296 const ImageX0, ImageY0, ImageWidth, ImageHeight: Cardinal): boolean;
2297 var
2298 Y: Integer;
2299 SelfPtr: Pointer;
2300 ImagePtr: Pointer;
2301 SelfRowByteWidth, ImageRowByteWidth, RowByteWidth: Cardinal;
2302 begin
2303 Result :=
2304 (Image.ClassType = ClassType) and
2305 (SelfWidth = ImageWidth) and
2306 (SelfHeight = ImageHeight);
2307 if Result then
2308 begin
2309 SelfPtr := PixelPtr(SelfX0, SelfY0);
2310 ImagePtr := Image.PixelPtr(ImageX0, ImageY0);
2311 RowByteWidth := ImageWidth * PixelSize;
2312 SelfRowByteWidth := Self.Width * PixelSize;
2313 ImageRowByteWidth := Image.Width * Image.PixelSize;
2314 for Y := 0 to Integer(ImageHeight) - 1 do
2315 begin
2316 if not CompareMem(SelfPtr, ImagePtr, RowByteWidth) then
2317 begin
2318 Result := false;
2319 Exit;
2320 end;
2321 PtrUInt(SelfPtr) := PtrUInt(SelfPtr) + SelfRowByteWidth;
2322 PtrUInt(ImagePtr) := PtrUInt(ImagePtr) + ImageRowByteWidth;
2323 end;
2324 end;
2325 end;
2326
2327 function TCastleImage.ArePartsEqual(
2328 Image: TCastleImage;
2329 const ImageX0, ImageY0, ImageWidth, ImageHeight: Cardinal): boolean;
2330 begin
2331 Result := ArePartsEqual(
2332 0, 0, Width, Height,
2333 Image,
2334 ImageX0, ImageY0, ImageWidth, ImageHeight);
2335 end;
2336
2337 function TCastleImage.ArePartsEqual(
2338 const SelfX0, SelfY0, SelfWidth, SelfHeight: Cardinal;
2339 Image: TCastleImage): boolean;
2340 begin
2341 Result := ArePartsEqual(
2342 SelfX0, SelfY0, SelfWidth, SelfHeight,
2343 Image,
2344 0, 0, Image.Width, Image.Height);
2345 end;
2346
2347 procedure TCastleImage.LerpSimpleCheckConditions(SecondImage: TCastleImage);
2348 begin
2349 if (Width <> SecondImage.Width) or
2350 (Height <> SecondImage.Height) then
2351 raise EImageLerpDifferentSizes.CreateFmt('Linear interpolation not possible, images have different sizes: first has %d x %d, second has %d x %d',
2352 [Width, Height, SecondImage.Width, SecondImage.Height]);
2353
2354 if not (SecondImage is Self.ClassType) then
2355 raise EImageLerpInvalidClasses.CreateFmt('Linear interpolation between %s and %s class not possible',
2356 [ClassName, SecondImage.ClassName]);
2357 end;
2358
2359 procedure TCastleImage.LerpWith(const Value: Single; SecondImage: TCastleImage);
2360 begin
2361 raise EImageLerpInvalidClasses.Create('Linear interpolation (TCastleImage.LerpWith) not possible with the base TCastleImage class');
2362 end;
2363
2364 class procedure TCastleImage.MixColors(const OutputColor: Pointer;
2365 const Weights: TVector4; const AColors: TVector4Pointer);
2366 begin
2367 raise EImageLerpInvalidClasses.Create('Mixing colors (TCastleImage.MixColors) not possible with the base TCastleImage class');
2368 end;
2369
2370 procedure TCastleImage.SaveToPascalCode(const ImageName: string;
2371 var CodeInterface, CodeImplementation, CodeInitialization, CodeFinalization: string);
2372
2373 { Add to Pascal code in Builder a constant that defines an array of bytes,
2374 with name from NameChannelData, with contents from ChannelData. }
2375 procedure AddChannelData(const ChannelData: TMemoryStream;
2376 const NameChannelData: String; const Builder: TStringBuilder);
2377 var
2378 PB: PByte;
2379 I: Integer;
2380 begin
2381 Builder.Append(
2382 ' ' + NameChannelData +
2383 ': array[0 .. ' + IntToStr(ChannelData.Size) + ' - 1] of Byte = (' + NL +
2384 ' ');
2385 PB := PByte(ChannelData.Memory);
2386 for I := 1 to ChannelData.Size do
2387 begin
2388 Builder.Append(Format('%4d', [PB^]));
2389 if I < ChannelData.Size then
2390 Builder.Append(',');
2391 if (I mod 12) = 0 then
2392 Builder.Append(NL + ' ')
2393 else
2394 Builder.Append(' ');
2395 Inc(PB);
2396 end;
2397 Builder.Append(NL + ' );' + NL);
2398 end;
2399
2400 var
2401 NameChannelData: String;
2402 CodeImplementationBuilder: TStringBuilder;
2403 Split: TChannelsSplit;
2404 ChannelCompressed: TMemoryStream;
2405 Channel: Integer;
2406 TotalCompressedSize: Int64;
2407 begin
2408 CodeInterface := CodeInterface +
2409 'function ' +ImageName+ ': ' +ClassName+ ';' +nl + nl;
2410
2411 CodeImplementationBuilder := TStringBuilder.Create;
2412 CodeImplementationBuilder.Append(
2413 SReplacePatterns(
2414 'var' + NL +
2415 ' F${IMAGE_NAME}: ${IMAGE_CLASS};' + NL +
2416 'const' + NL +
2417 ' ${IMAGE_NAME}Width = ' +IntToStr(Width)+ ';' + NL +
2418 ' ${IMAGE_NAME}Height = ' +IntToStr(Height)+ ';' + NL +
2419 ' ${IMAGE_NAME}Depth = ' +IntToStr(Depth)+ ';' + NL +
2420 NL,
2421 [
2422 '${IMAGE_NAME}',
2423 '${IMAGE_CLASS}'
2424 ], [
2425 ImageName,
2426 ClassName
2427 ], { ignore case when replacing } false)
2428 );
2429
2430 // add compressed data for all channels
2431 TotalCompressedSize := 0;
2432 Split := DataChannelsSplit(RawPixels, Size, PixelSize);
2433 try
2434 ChannelCompressed := TMemoryStream.Create;
2435 try
2436 for Channel := 0 to PixelSize - 1 do
2437 begin
2438 // reset ChannelCompressed contents
2439 ChannelCompressed.Size := 0;
2440 ChannelCompressed.Position := 0;
2441
2442 // generate ChannelCompressed contents
2443 RleCompress(Split.Data[Channel], Split.DataSize, ChannelCompressed);
2444
2445 // write ChannelCompressed to CodeImplementationBuilder
2446 NameChannelData := ImageName + 'ChannelData' + IntToStr(Channel);
2447 AddChannelData(ChannelCompressed, NameChannelData, CodeImplementationBuilder);
2448
2449 // update stats
2450 TotalCompressedSize := TotalCompressedSize + ChannelCompressed.Size;
2451 end;
2452 finally FreeAndNil(ChannelCompressed) end;
2453 finally FreeAndNil(Split) end;
2454 WritelnLog('Compress', 'Compressed size of ' +ImageName+ ' is ' +IntToStr(TotalCompressedSize)+ ' bytes, achieving compression ratio (lower the better) %f', [
2455 TotalCompressedSize / Size
2456 ]);
2457
2458 // add code to decompress data and combine channels when the generated Pascal code is used
2459 CodeImplementationBuilder.Append(
2460 SReplacePatterns(
2461 NL +
2462 'function ${IMAGE_NAME}: ${IMAGE_CLASS};' + NL +
2463 'var' + NL +
2464 ' Split: TChannelsSplit;' + NL +
2465 'begin' + NL +
2466 ' if F${IMAGE_NAME} = nil then' + NL +
2467 ' begin' + NL +
2468 ' F${IMAGE_NAME} := ${IMAGE_CLASS}.Create(${IMAGE_NAME}Width, ${IMAGE_NAME}Height, ${IMAGE_NAME}Depth);' + NL +
2469 ' Split := TChannelsSplit.Create;' + NL +
2470 ' try' + NL +
2471 ' SetLength(Split.Data, F${IMAGE_NAME}.PixelSize);' + NL +
2472 ' Split.DataSize := F${IMAGE_NAME}.Size div F${IMAGE_NAME}.PixelSize;' + NL +
2473 ' Split.DataAllocate;' + NL,
2474 [
2475 '${IMAGE_NAME}',
2476 '${IMAGE_CLASS}'
2477 ], [
2478 ImageName,
2479 ClassName
2480 ], { ignore case when replacing } false));
2481
2482 for Channel := 0 to PixelSize - 1 do
2483 begin
2484 NameChannelData := ImageName + 'ChannelData' + IntToStr(Channel);
2485 CodeImplementationBuilder.Append(
2486 SReplacePatterns(
2487 ' RleDecompress(@${CHANNEL_DATA}, SizeOf(${CHANNEL_DATA}), Split.Data[${CHANNEL}], Split.DataSize);' + NL,
2488 [
2489 '${CHANNEL_DATA}',
2490 '${CHANNEL}'
2491 ], [
2492 NameChannelData,
2493 IntToStr(Channel)
2494 ], { ignore case when replacing } false));
2495 end;
2496
2497 CodeImplementationBuilder.Append(
2498 SReplacePatterns(
2499 ' DataChannelsCombine(F${IMAGE_NAME}.RawPixels, F${IMAGE_NAME}.Size,' + NL +
2500 ' F${IMAGE_NAME}.PixelSize, Split);' + NL +
2501 ' Split.DataFree;' + NL +
2502 ' finally FreeAndNil(Split) end;' + NL +
2503 ' F${IMAGE_NAME}.Url := ''embedded-image:/${IMAGE_NAME}'';' + NL +
2504 ' end;' + NL +
2505 ' Result := F${IMAGE_NAME};' + NL +
2506 'end;' + NL +
2507 NL,
2508 [
2509 '${IMAGE_NAME}'
2510 ], [
2511 ImageName
2512 ], { ignore case when replacing } false));
2513 CodeImplementation := CodeImplementation +
2514 CodeImplementationBuilder.ToString;
2515
2516 CodeFinalization := CodeFinalization +
2517 ' FreeAndNil(F' + ImageName + ');' +nl;
2518 end;
2519
2520 procedure TCastleImage.AlphaBleed(const ProgressTitle: string);
2521 begin
2522 { default implementation does nothing.
2523 This is OK for images without alpha channel. }
2524 end;
2525
2526 function TCastleImage.MakeAlphaBleed(const ProgressTitle: string): TCastleImage;
2527 begin
2528 { default implementation returns a copy.
2529 This is OK for images without alpha channel. }
2530 Result := MakeCopy;
2531 end;
2532
2533 procedure TCastleImage.DrawFrom3x3(const DestinationRect: TRectangle;
2534 const Source: TCastleImage; const SourceCorners: TVector4Integer;
2535 const DrawMode: TDrawMode; const Interpolation: TResizeInterpolation);
2536
2537 procedure Draw(
2538 const DestX, DestY, DestWidth, DestHeight: Integer;
2539 const SourceX, SourceY, SourceWidth, SourceHeight: Integer);
2540 var
2541 Temp: TCastleImage;
2542 begin
2543 if (DestWidth = SourceWidth) and (DestHeight = SourceHeight) then
2544 { Optimized version -- no need to scale.
2545 This should happen at least for 4 corners. }
2546 DrawFrom(Source, DestX, DestY, SourceX, SourceY, SourceWidth, SourceHeight, DrawMode)
2547 else
2548 begin
2549 // create Temp with the same type as Source, to make Draw with dmOverwrite fast
2550 Temp := TCastleImageClass(Source.ClassType).Create(SourceWidth, SourceHeight);
2551 try
2552 Temp.DrawFrom(Source, 0, 0, SourceX, SourceY, SourceWidth, SourceHeight, dmOverwrite);
2553 Temp.Resize(DestWidth, DestHeight, Interpolation);
2554 DrawFrom(Temp, DestX, DestY, 0, 0, DestWidth, DestHeight, DrawMode);
2555 finally FreeAndNil(Temp) end;
2556 end;
2557 end;
2558
2559 var
2560 CornerTop, CornerRight, CornerBottom, CornerLeft: Integer;
2561 DestWidth, DestHeight: Integer;
2562 XDestLeft, XDestRight, YDestBottom, YDestTop,
2563 HorizontalDestSize, VerticalDestSize: Integer;
2564 XSourceLeft, XSourceRight, YSourceBottom, YSourceTop,
2565 HorizontalSourceSize, VerticalSourceSize: Integer;
2566 begin
2567 CornerTop := SourceCorners[0];
2568 CornerRight := SourceCorners[1];
2569 CornerBottom := SourceCorners[2];
2570 CornerLeft := SourceCorners[3];
2571
2572 DestWidth := DestinationRect.Width;
2573 DestHeight := DestinationRect.Height;
2574
2575 if not ( (CornerLeft + CornerRight < Source.Width) and
2576 (CornerLeft + CornerRight < DestWidth) and
2577 (CornerBottom + CornerTop < Source.Height) and
2578 (CornerBottom + CornerTop < DestHeight)) then
2579 begin
2580 WritelnLog('TCastleImage.Dest3x3', 'Image corners are too large to draw it: corners are %d %d %d %d, image size is %d %d, draw area size is %d %d',
2581 [CornerTop, CornerRight, CornerBottom, CornerLeft,
2582 Source.Width, Source.Height,
2583 DestWidth, DestHeight]);
2584 Exit;
2585 end;
2586
2587 XDestLeft := DestinationRect.Left;
2588 XSourceLeft := 0;
2589 XDestRight := DestinationRect.Left + DestWidth - CornerRight;
2590 XSourceRight := Source.Width - CornerRight;
2591
2592 YDestBottom := DestinationRect.Bottom;
2593 YSourceBottom := 0;
2594 YDestTop := DestinationRect.Bottom + DestHeight - CornerTop;
2595 YSourceTop := Source.Height - CornerTop;
2596
2597 { 4 corners }
2598 Draw(XDestLeft , YDestBottom , CornerLeft, CornerBottom,
2599 XSourceLeft, YSourceBottom, CornerLeft, CornerBottom);
2600 Draw(XDestRight , YDestBottom , CornerRight, CornerBottom,
2601 XSourceRight, YSourceBottom, CornerRight, CornerBottom);
2602 Draw(XDestRight , YDestTop , CornerRight, CornerTop,
2603 XSourceRight, YSourceTop, CornerRight, CornerTop);
2604 Draw(XDestLeft , YDestTop , CornerLeft, CornerTop,
2605 XSourceLeft, YSourceTop, CornerLeft, CornerTop);
2606
2607 { 4 sides }
2608 HorizontalDestSize := DestWidth - CornerLeft - CornerRight;
2609 HorizontalSourceSize := Source.Width - CornerLeft - CornerRight;
2610 VerticalDestSize := DestHeight - CornerTop - CornerBottom;
2611 VerticalSourceSize := Source.Height - CornerTop - CornerBottom;
2612
2613 Draw(XDestLeft + CornerLeft, YDestBottom , HorizontalDestSize, CornerBottom,
2614 XSourceLeft + CornerLeft, YSourceBottom, HorizontalSourceSize, CornerBottom);
2615 Draw(XDestLeft + CornerLeft, YDestTop , HorizontalDestSize, CornerTop,
2616 XSourceLeft + CornerLeft, YSourceTop, HorizontalSourceSize, CornerTop);
2617
2618 Draw(XDestLeft , YDestBottom + CornerBottom, CornerLeft, VerticalDestSize,
2619 XSourceLeft, YSourceBottom + CornerBottom, CornerLeft, VerticalSourceSize);
2620 Draw(XDestRight , YDestBottom + CornerBottom, CornerRight, VerticalDestSize,
2621 XSourceRight, YSourceBottom + CornerBottom, CornerRight, VerticalSourceSize);
2622
2623 Draw(DestinationRect.Left + CornerLeft, DestinationRect.Bottom + CornerBottom, HorizontalDestSize, VerticalDestSize,
2624 CornerLeft, CornerBottom, HorizontalSourceSize, VerticalSourceSize);
2625 end;
2626
2627 { TCastleImageClass and arrays of TCastleImageClasses ----------------------------- }
2628
2629 function InImageClasses(ImageClass: TEncodedImageClass;
2630 const ImageClasses: array of TEncodedImageClass): boolean;
2631 var
2632 i: Integer;
2633 begin
2634 for i := 0 to High(ImageClasses) do
2635 if ImageClass.InheritsFrom(ImageClasses[i]) then
2636 begin
2637 Result := true;
2638 Exit;
2639 end;
2640 Result := false;
2641 end;
2642
2643 function InImageClasses(Image: TEncodedImage;
2644 const ImageClasses: array of TEncodedImageClass): boolean;
2645 begin
2646 Result := InImageClasses(TEncodedImageClass(Image.ClassType), ImageClasses);
2647 end;
2648
2649 function ImageClassesEqual(const Ar1, Ar2: array of TEncodedImageClass): boolean;
2650 var
2651 i: Integer;
2652 begin
2653 if High(Ar1) <> High(Ar2) then
2654 begin
2655 Result := false;
2656 Exit;
2657 end;
2658
2659 for i := 0 to High(Ar1) do
2660 if Ar1[I] <> Ar2[I] then
2661 begin
2662 Result := false;
2663 Exit;
2664 end;
2665
2666 Result := true;
2667 end;
2668
2669 { RGBE <-> 3 Single color conversion --------------------------------- }
2670
2671 const
2672 { do signed Exponent dodaj RGBEExponentOffset zeby zapisac exponent jako Byte }
2673 RGBEExponentOffset = 128;
2674 { RGBEMin/MaxExponent = min i max wartosci dla exponent ktore moga dac
2675 (Exponent + RGBEExponentOffset) w zakresie Byte.
2676 Czyli RGBEMinExponent + RGBEExponentOffset = 0,
2677 RGBEMaxExponent + RGBEExponentOffset = High(Byte),
2678 stad RGBEMinExponent = -RGBEExponentOffset,
2679 RGBEMaxExponent = High(Byte) - RGBEExponentOffset }
2680 RGBEMinExponent = -RGBEExponentOffset;
2681 RGBEMaxExponent = High(Byte) - RGBEExponentOffset;
2682
2683 { zero musi byc reprezentowane w specjalny sposob w formacie RGBE,
2684 podobnie jak w kazdym formacie zmiennoprzec. }
2685 RGBEZero: TVector4Byte = (X: 0; Y: 0; Z: 0; W: 0);
2686 RGBELow : TVector4Byte = (X: 0; Y: 0; Z: 0; W: 0); { = RGBEZero }
2687 RGBEHigh: TVector4Byte = (X: High(Byte); Y: High(Byte); Z: High(Byte); W: High(Byte));
2688
2689 function Vector3ToRGBE(const v: TVector3): TVector4Byte;
2690 { implementacja : jak Graphic Gems II.5 ale z poprawkami -
2691 - nazwy MaxVal i V sa osobne (dla czytelnosci),
2692 - checki czy Exponent jest w granicach RGBEMin/MaxExponent }
2693 { uwagi : moznaby sadzic ze Multiplier powinien byc liczony jako
2694 Mantissa * 255 / MaxVal (255 = High(Byte) zamiast 256),
2695 zeby poprawnie mapowac zakres 0..1 na zakres bajta.
2696 Ale,
2697 - po pierwsze, specyfikacja formatu RGBE (czyli Graphic Gems II.5)
2698 mowi zeby uzywac 256
2699 - po drugie, uzywanie 256 podaje nam prosty warunek na sprawdzenie
2700 czy czworka bajtow jest poprawnym RGBE : mianowicie, przynajmniej
2701 jeden z pierwszych trzech bajtow musi byc >= 128
2702 (czyli musi miec najstarszy bit = 1). Tym samym ten bajt jest >= 0.5
2703 a wiec jest poprawna mantysa. Ten prosty test na poprawnosc ma zastosowanie
2704 przy kodowaniu plikow rgbe przy uzyciu prostego RLE, gdzie wykorzystujemy
2705 takie niepoprawne czworki RGBE to kodowania specjalnych informacji.
2706 - po trzecie i chyba najwazniejsze, gdyby uzywac 256 to wartosc
2707 mantysy = 255 byla bezuzyteczna bo odpowiadalaby wartosci float = 1.0
2708 a mantysa zawsze musi byc ostro mniejsza od 1, z definicji.
2709 I to jest chyba koronny argument za mnozeniem tutaj przez 256.
2710 }
2711 var
2712 MaxVal, Multiplier: Single;
2713 Mantissa: Extended;
2714 Exponent: Integer;
2715 begin
2716 MaxVal := V.Max;
2717
2718 { rozpatrujemy tu nie tylko przypadek gdy liczba jest = 0 ale takze
2719 gdy jest bliska zeru. To jest standardowe zachowanie, ale uwaga -
2720 - w tym przypadku mogloby sie (blednie) wydawac ze mozemy tutaj zrobic
2721 wyjatek i sprawdzac ponizej tylko MaxVal = 0.0 (dokladna rownosc)
2722 a sprawdzanie bliskosci do zera zrzucic na test Exponent < RGBEMinExponent
2723 ponizej. ALE to nie jest prawda - test Exponent < RGBEMinExponent przejdzie
2724 dopiero dla niesamowicie mikroskopijnych liczb (< 1 / 2^127) podczas gdy liczby
2725 pomiedzy tymi "mikroskopijnie malymi" a SINGLE_EQUALITY_EPSILON ciagle
2726 beda powodowac problemy (bo przy liczeniu Multiplier dzielimy przez MaxVal
2727 wiec male MaxVal -> Float overflow). }
2728 if IsZero(MaxVal) then begin Result := RGBEZero; Exit end;
2729
2730 Frexp(MaxVal, Mantissa, Exponent);
2731
2732 if Exponent < RGBEMinExponent then begin result := RGBELow; Exit end;
2733 if Exponent > RGBEMaxExponent then begin result := RGBEHigh; Exit end;
2734
2735 Multiplier := Mantissa * 256 / MaxVal;
2736
2737 { MaxVal * Multiplier daje Mantissa * High(byte) a wiec cos w zakresie
2738 0 .. High(Byte) bo Mantissa <= 1 (de facto, Mantissa >= 0.5 wiec
2739 mozna podac dokladniejsze ograniczenie na Mantissa * High(byte)).
2740 Wszystkie pozostale v[] sa mniejsze od MaxVal wiec one tez dadza cos
2741 w zakresie bajta. }
2742 Result.X := Clamped(Round(v.X * Multiplier), 0, High(Byte));
2743 Result.Y := Clamped(Round(v.Y * Multiplier), 0, High(Byte));
2744 Result.Z := Clamped(Round(v.Z * Multiplier), 0, High(Byte));
2745
2746 { sprawdzajac czy Exponent in RGBEMin/MaxExponent wczesniej juz zapewnilem
2747 sobie ze ponizsze przypisanie jest Ok, wynik zmiesci sie w zakresie bajta. }
2748 Result.W := Exponent + RGBEExponentOffset;
2749 end;
2750
2751 function VectorRGBETo3Single(const v: TVector4Byte): TVector3;
2752 { Implementation like in Graphic Gems II.5.
2753
2754 Note: Multiplier is from 1/256 (not 1/255).
2755 Same reasons as in Vector3ToRGBE implementation. }
2756 var
2757 Multiplier: Single;
2758 begin
2759 if v.W = 0 then begin Result := TVector3.Zero; Exit end;
2760
2761 Multiplier := Ldexp(1 / 256, Integer(v.W) - RGBEExponentOffset);
2762 Result.X := v.X * Multiplier;
2763 Result.Y := v.Y * Multiplier;
2764 Result.Z := v.Z * Multiplier;
2765 end;
2766
2767 { TLoadImageEventList -------------------------------------------------------- }
2768
2769 type
2770 { List of TLoadImageEvent methods. }
2771 TLoadImageEventList = class({$ifdef FPC}specialize{$endif} TList<TLoadImageEvent>)
2772 procedure Execute(var Url: String);
2773 end;
2774
2775 procedure TLoadImageEventList.Execute(var Url: String);
2776 var
2777 I: Integer;
2778 begin
2779 for I := 0 to Count - 1 do
2780 Items[I](Url);
2781 end;
2782
2783 var
2784 LoadImageEvents: TLoadImageEventList;
2785
2786 { LoadEncodedImage ----------------------------------------------------------- }
2787
2788 function LoadEncodedImage(Stream: TStream; const StreamFormat: TImageFormat;
2789 const AllowedImageClasses: array of TEncodedImageClass;
2790 const Options: TLoadImageOptions = []): TEncodedImage; overload;
2791
2792 procedure FixImageClass;
2793
2794 { ClassAllowed is only a shortcut to global utility. }
2795 function ClassAllowed(ImageClass: TEncodedImageClass): boolean;
2796 begin
2797 Result := CastleImages.ClassAllowed(ImageClass, AllowedImageClasses);
2798 end;
2799
2800 { Input: TGPUCompressedImage, output: anything else than TGPUCompressedImage. }
2801 procedure ImageDecompressVar(var Image: TEncodedImage);
2802 var
2803 NewResult: TEncodedImage;
2804 begin
2805 NewResult := (Image as TGPUCompressedImage).Decompress;
2806
2807 FreeAndNil(Image);
2808 Image := NewResult;
2809 end;
2810
2811 procedure ReplaceResult(const NewResultClass: TCastleImageClass);
2812 var
2813 NewResult: TCastleImage;
2814 begin
2815 NewResult := NewResultClass.Create;
2816 NewResult.Assign(Result as TCastleImage);
2817
2818 FreeAndNil(Result);
2819 Result := NewResult;
2820 end;
2821
2822 begin
2823 if not ClassAllowed(TEncodedImageClass(Result.ClassType)) then
2824 begin
2825 if Result is TGPUCompressedImage then
2826 begin
2827 ImageDecompressVar(Result);
2828 if ClassAllowed(TEncodedImageClass(Result.ClassType)) then
2829 Exit; // ClassAllowed was fixed by just decompressing GPU image, testcase: castle-image-viewer
2830 end;
2831
2832 { For each possible Result class,
2833 try various possible target classes we can convert to
2834 (using castleimages_assign.inc)
2835 in the order from the most preferred (sensible/losssless) conversion
2836 to least preferred. }
2837
2838 if (Result is TRGBAlphaImage) and ClassAllowed(TRGBImage) then
2839 ReplaceResult(TRGBImage)
2840 else
2841 if (Result is TRGBAlphaImage) and ClassAllowed(TGrayscaleAlphaImage) then
2842 ReplaceResult(TGrayscaleAlphaImage)
2843 else
2844 if (Result is TRGBAlphaImage) and ClassAllowed(TGrayscaleImage) then
2845 ReplaceResult(TGrayscaleImage)
2846 else
2847 if (Result is TRGBAlphaImage) and ClassAllowed(TRGBFloatImage) then
2848 ReplaceResult(TRGBFloatImage)
2849 else
2850
2851 if (Result is TRGBImage) and ClassAllowed(TRGBAlphaImage) then
2852 ReplaceResult(TRGBAlphaImage)
2853 else
2854 if (Result is TRGBImage) and ClassAllowed(TGrayscaleImage) then
2855 ReplaceResult(TGrayscaleImage)
2856 else
2857 if (Result is TRGBImage) and ClassAllowed(TGrayscaleAlphaImage) then
2858 ReplaceResult(TGrayscaleAlphaImage)
2859 else
2860 if (Result is TRGBImage) and ClassAllowed(TRGBFloatImage) then
2861 ReplaceResult(TRGBFloatImage)
2862 else
2863
2864 if (Result is TGrayscaleAlphaImage) and ClassAllowed(TRGBAlphaImage) then
2865 ReplaceResult(TRGBAlphaImage)
2866 else
2867 if (Result is TGrayscaleAlphaImage) and ClassAllowed(TGrayscaleImage) then
2868 ReplaceResult(TGrayscaleImage)
2869 else
2870 if (Result is TGrayscaleAlphaImage) and ClassAllowed(TRGBImage) then
2871 ReplaceResult(TRGBImage)
2872 else
2873 if (Result is TGrayscaleAlphaImage) and ClassAllowed(TRGBFloatImage) then
2874 ReplaceResult(TRGBFloatImage)
2875 else
2876
2877 if (Result is TGrayscaleImage) and ClassAllowed(TGrayscaleAlphaImage) then
2878 ReplaceResult(TGrayscaleAlphaImage)
2879 else
2880 if (Result is TGrayscaleImage) and ClassAllowed(TRGBAlphaImage) then
2881 ReplaceResult(TRGBAlphaImage)
2882 else
2883 if (Result is TGrayscaleImage) and ClassAllowed(TRGBImage) then
2884 ReplaceResult(TRGBImage)
2885 else
2886 if (Result is TGrayscaleImage) and ClassAllowed(TRGBFloatImage) then
2887 ReplaceResult(TRGBFloatImage)
2888 else
2889
2890 if (Result is TRGBFloatImage) and ClassAllowed(TRGBImage) then
2891 ReplaceResult(TRGBImage)
2892 else
2893 if (Result is TRGBFloatImage) and ClassAllowed(TRGBAlphaImage) then
2894 ReplaceResult(TRGBAlphaImage)
2895 else
2896 if (Result is TRGBFloatImage) and ClassAllowed(TGrayscaleImage) then
2897 ReplaceResult(TGrayscaleImage)
2898 else
2899 if (Result is TRGBFloatImage) and ClassAllowed(TGrayscaleAlphaImage) then
2900 ReplaceResult(TGrayscaleAlphaImage)
2901 else
2902
2903 if ClassAllowed(TGrayscaleFloatImage) then
2904 ReplaceResult(TGrayscaleFloatImage)
2905 else
2906 if ClassAllowed(TGrayscaleAlphaFloatImage) then
2907 ReplaceResult(TGrayscaleAlphaFloatImage)
2908 else
2909 if ClassAllowed(TRGBAlphaFloatImage) then
2910 ReplaceResult(TRGBAlphaFloatImage)
2911 else
2912
2913 raise EUnableToLoadImage.CreateFmt('LoadEncodedImage cannot satisfy the requested output format, we got %s, but we want %s. Use less restrictive AllowedImageClasses argument.', [
2914 Result.ClassName,
2915 LoadEncodedImageParams(AllowedImageClasses)
2916 ]);
2917 end;
2918 end;
2919
2920 var
2921 Load: TImageLoadFunc;
2922 begin
2923 Result := nil;
2924 try
2925 if Assigned(ImageFormatInfos[StreamFormat].Load) then
2926 begin
2927 Load := ImageFormatInfos[StreamFormat].Load;
2928 Result := Load(Stream, AllowedImageClasses);
2929
2930 { Fix the loaded image class.
2931 Although loaders should also attempt to do it inside (with better speed),
2932 but it is not required, e.g. Load_VampyreImaging ignores AllowedImageClasses value.
2933 And we want code like
2934
2935 LoadImage('a.png', [TRGBImage]) as TRGBImage
2936
2937 to always work, testcase: examples/fps_game.
2938 }
2939 FixImageClass;
2940 end else
2941 begin
2942 raise EImageFormatNotSupported.CreateFmt('Can''t load image format "%s"', [
2943 ImageFormatInfos[StreamFormat].FormatName
2944 ]);
2945 end;
2946
2947 { TODO: This flip may be implemented at lower level, inside particular image loaders,
2948 some day. It would have 0 cost then. }
2949 if liFlipVertically in Options then
2950 Result.FlipVertical;
2951
2952 except
2953 Result.Free;
2954 raise
2955 end;
2956 end;
2957
2958 function LoadEncodedImage(Stream: TStream; const MimeType: string;
2959 const AllowedImageClasses: array of TEncodedImageClass;
2960 const Options: TLoadImageOptions = [])
2961 :TEncodedImage;
2962 var
2963 iff: TImageFormat;
2964 begin
2965 if MimeTypeToImageFormat(MimeType, true, false, iff) then
2966 result := LoadEncodedImage(Stream, iff, AllowedImageClasses, Options)
2967 else
2968 raise EImageFormatNotSupported.Create('Unrecognized image MIME type: "'+MimeType+'"');
2969 end;
2970
2971 function LoadEncodedImage(Url: String;
2972 const AllowedImageClasses: array of TEncodedImageClass;
2973 const Options: TLoadImageOptions = []): TEncodedImage;
2974 const
2975 SLoadError = 'Error loading image from URL "%s": %s';
2976 var
2977 F: TStream;
2978 MimeType: string;
2979 TimeStart: TCastleProfilerTime;
2980 begin
2981 F := nil;
2982 TimeStart := Profiler.Start('Loading "' + UriDisplay(Url) + '" (CastleImages)');
2983 try
2984 try
2985 LoadImageEvents.Execute(Url);
2986 F := Download(Url, [soForceMemoryStream], MimeType);
2987 Result := LoadEncodedImage(F, MimeType, AllowedImageClasses, Options);
2988 Result.FUrl := Url;
2989 except
2990 { capture some exceptions to add URL to exception message }
2991 on E: EReadError do // maybe be raised by Download
2992 begin
2993 E.Message := Format(SLoadError, [UriDisplay(Url), E.Message]);
2994 raise;
2995 end;
2996 on E: EImageLoadError do
2997 begin
2998 E.Message := Format(SLoadError, [UriDisplay(Url), E.Message]);
2999 raise;
3000 end;
3001 on E: EImageFormatNotSupported do
3002 begin
3003 E.Message := Format(SLoadError, [UriDisplay(Url), E.Message]);
3004 raise;
3005 end;
3006 end;
3007 finally
3008 FreeAndNil(F);
3009 Profiler.Stop(TimeStart);
3010 end;
3011 end;
3012
3013 function LoadEncodedImage(const Url: String;
3014 const Options: TLoadImageOptions = []): TEncodedImage;
3015 begin
3016 Result := LoadEncodedImage(Url, [], Options);
3017 end;
3018
3019 { LoadImage ------------------------------------------------------------------ }
3020
3021 function LoadImage(Stream: TStream; const StreamFormat: TImageFormat;
3022 const AllowedImageClasses: array of TEncodedImageClass): TCastleImage; overload;
3023 var
3024 E: TEncodedImage;
3025 begin
3026 E := LoadEncodedImage(Stream, StreamFormat, AllowedImageClasses);
3027 if not (E is TCastleImage) then
3028 raise EImageLoadError.Create('Image is compressed for GPU, cannot load it to uncompressed format. You can only render such image.');
3029 Result := TCastleImage(E);
3030 end;
3031
3032 function LoadImage(Stream: TStream; const MimeType: string;
3033 const AllowedImageClasses: array of TEncodedImageClass): TCastleImage;
3034 var
3035 E: TEncodedImage;
3036 begin
3037 E := LoadEncodedImage(Stream, MimeType, AllowedImageClasses);
3038 if not (E is TCastleImage) then
3039 raise EImageLoadError.Create('Image is compressed for GPU, cannot load it to uncompressed format. You can only render such image.');
3040 Result := TCastleImage(E);
3041 end;
3042
3043 function LoadImage(const Url: String;
3044 const AllowedImageClasses: array of TEncodedImageClass): TCastleImage;
3045 var
3046 E: TEncodedImage;
3047 begin
3048 E := LoadEncodedImage(Url, AllowedImageClasses);
3049 if not (E is TCastleImage) then
3050 raise EImageLoadError.CreateFmt('Image "%s" is compressed for GPU, cannot load it to uncompressed format. You can only render such image.',
3051 [UriDisplay(Url)]);
3052 Result := TCastleImage(E);
3053 end;
3054
3055 function LoadImage(const Url: String): TCastleImage;
3056 var
3057 E: TEncodedImage;
3058 begin
3059 E := LoadEncodedImage(Url);
3060 if not (E is TCastleImage) then
3061 raise EImageLoadError.CreateFmt('Image "%s" is compressed for GPU, cannot load it to uncompressed format. You can only render such image.',
3062 [UriDisplay(Url)]);
3063 Result := TCastleImage(E);
3064 end;
3065
3066 function LoadImage(const Url: String;
3067 const AllowedImageClasses: array of TEncodedImageClass;
3068 const ResizeWidth, ResizeHeight: Cardinal;
3069 const Interpolation: TResizeInterpolation = riBilinear;
3070 const Options: TLoadImageOptions = []): TCastleImage; overload;
3071 var
3072 E: TEncodedImage;
3073 begin
3074 E := LoadEncodedImage(Url, AllowedImageClasses, Options);
3075 if not (E is TCastleImage) then
3076 raise EImageLoadError.CreateFmt('Image "%s" is compressed for GPU, cannot load it to uncompressed format. You can only render such image.',
3077 [UriDisplay(Url)]);
3078 Result := TCastleImage(E);
3079 Result.Resize(ResizeWidth, ResizeHeight, Interpolation);
3080 end;
3081
3082 { SaveImage on TEncodedImage ---------------------------------------------------- }
3083
3084 procedure SaveImage(const Img: TEncodedImage; const Format: TImageFormat; Stream: TStream); overload;
3085 var
3086 Save: TImageSaveFunc;
3087 begin
3088 if Assigned(ImageFormatInfos[Format].Save) then
3089 begin
3090 Save := ImageFormatInfos[Format].Save;
3091 Save(Img, Stream);
3092 end else
3093 raise EImageSaveError.CreateFmt('Saving image class %s not implemented', [Img.ClassName]);
3094 end;
3095
3096 procedure SaveImage(const Img: TEncodedImage; const MimeType: string; Stream: TStream);
3097 var
3098 Format: TImageFormat;
3099 begin
3100 if not MimeTypeToImageFormat(MimeType, false, true, Format) then
3101 raise EImageSaveError.CreateFmt('Unknown image MIME type "%s", cannot save. Make sure the filename/URL you want to save has one of the recognized extensions',
3102 [MimeType]);
3103 SaveImage(Img, Format, Stream);
3104 end;
3105
3106 procedure SaveImage(const Img: TEncodedImage; const Url: String);
3107 var
3108 Stream: TStream;
3109 Format: TImageFormat;
3110 MimeType: string;
3111 begin
3112 { Do not call SaveImage with MimeType: string parameter, instead calculate
3113 Format here. This way we can make better error messaage. }
3114 MimeType := UriMimeType(Url);
3115 if not MimeTypeToImageFormat(MimeType, false, true, Format) then
3116 raise EImageSaveError.CreateFmt('Unknown image MIME type "%s", cannot save URL "%s". Make sure the filename/URL you want to save has one of the recognized extensions',
3117 [MimeType, Url]);
3118
3119 Stream := UrlSaveStream(Url);
3120 try
3121 SaveImage(Img, Format, Stream);
3122 finally FreeAndNil(Stream) end;
3123 end;
3124
3125 { others --------------------------------------------------------------------- }
3126
3127 procedure AlphaMaxVar(var A: TAlphaChannel; const B: TAlphaChannel);
3128 begin
3129 if B > A then A := B;
3130 end;
3131
3132 function StringToAlpha(S: string; var WarningDone: boolean): TAutoAlphaChannel;
3133 begin
3134 S := UpperCase(S);
3135 for Result := Low(Result) to High(Result) do
3136 if S = AlphaToString[Result] then
3137 Exit;
3138
3139 if S = 'SIMPLE_YES_NO' then
3140 begin
3141 if not WarningDone then
3142 begin
3143 WritelnWarning('alphaChannel', '"alphaChannel" value "SIMPLE_YES_NO" is deprecated, use "TEST" instead');
3144 WarningDone := true;
3145 end;
3146 Exit(acTest);
3147 end;
3148
3149 if S = 'FULL_RANGE' then
3150 begin
3151 if not WarningDone then
3152 begin
3153 WritelnWarning('alphaChannel', '"alphaChannel" value "FULL_RANGE" is deprecated, use "BLENDING" instead');
3154 WarningDone := true;
3155 end;
3156 Exit(acBlending);
3157 end;
3158
3159 if not WarningDone then
3160 begin
3161 WritelnWarning('alphaChannel', Format('Invalid "alphaChannel" value "%s"', [S]));
3162 WarningDone := true;
3163 end;
3164 Result := acAuto;
3165 end;
3166
3167 function TextureCompressionToString(const TextureCompression: TTextureCompression): string;
3168 begin
3169 Result := TextureCompressionInfo[TextureCompression].Name;
3170 end;
3171
3172 function StringToTextureCompression(const S: string): TTextureCompression;
3173 var
3174 SLower: string;
3175 begin
3176 SLower := LowerCase(S);
3177 for Result := Low(Result) to High(Result) do
3178 if SLower = LowerCase(TextureCompressionInfo[Result].Name) then
3179 Exit;
3180 raise Exception.CreateFmt('Invalid texture compression name "%s"', [S]);
3181 end;
3182
3183 procedure AddLoadImageListener(const Event: TLoadImageEvent);
3184 begin
3185 LoadImageEvents.Add(Event);
3186 end;
3187
3188 procedure RemoveLoadImageListener(const Event: TLoadImageEvent);
3189 begin
3190 LoadImageEvents.Remove(Event);
3191 end;
3192
3193 function ProcessImageUrl(const Url: String): string;
3194 begin
3195 Result := Url;
3196 LoadImageEvents.Execute(Result);
3197 end;
3198
3199 { unit initialization / finalization ----------------------------------------- }
3200
3201 initialization
3202 RegisterMimeTypes;
3203 InitializeImagesFileFilters;
3204
3205 { If LibPng *can* be available (the LibPng unit is available at compile-time),
3206 do InitializePNGUsingLibpng.
3207
3208 This is determined by "CASTLE_PNG_DYNAMIC or CASTLE_PNG_STATIC"
3209 (at most one of them can be defined, castleconf.inc guarantees it).
3210
3211 However, we actually don't want to call InitializePNGUsingLibpng when
3212 CASTLE_PNG_DYNAMIC is defined, but without ALLOW_DLOPEN_FROM_UNIT_INITIALIZATION.
3213 This would mean that InitializePNGUsingLibpng can only do now a warning
3214 "LibPng not initialized" which would be confusing on platforms without
3215 ALLOW_DLOPEN_FROM_UNIT_INITIALIZATION (like Android) that initialize LibPng
3216 later, and call InitializePNGUsingLibpng from LoadPng. }
3217
3218 {$if (defined(CASTLE_PNG_DYNAMIC) and defined(ALLOW_DLOPEN_FROM_UNIT_INITIALIZATION)) or defined(CASTLE_PNG_STATIC)}
3219 InitializePNGUsingLibpng;
3220 {$endif}
3221 LoadImageEvents := TLoadImageEventList.Create;
3222 finalization
3223 FreeAndNil(LoadImage_FileFilters);
3224 FreeAndNil(SaveImage_FileFilters);
3225 FreeAndNil(LoadImageEvents);
3226 end.