Debian Codegraph @

src/scene/castleinternalmaterialproperties.pas

raw
1 {
2 Copyright 2007-2023 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 { Material and texture properties from material_properties.xml
17 (TMaterialProperty, global MaterialProperties collection). }
18 unit CastleInternalMaterialProperties;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses Classes, DOM, Generics.Collections,
25 CastleUtils, CastleClassUtils, {$ifndef CASTLE_STRICT_CLI} CastleSoundEngine, {$endif}
26 CastleStringUtils, CastleImages, CastleFindFiles, CastleInternalAutoGenerated;
27
28 type
29 { Information for a particular material. }
30 TMaterialProperty = class
31 strict private
32 FTextureBaseName: String;
33 {$ifndef CASTLE_STRICT_CLI}
34 FFootstepsSound: TCastleSound;
35 {$endif}
36 FToxic: Boolean;
37 FToxicDamageConst, FToxicDamageRandom, FToxicDamageTime: Single;
38 FNormalMap: String;
39 FAlphaChannel: String;
40 private
41 procedure LoadFromDOMElement(Element: TDOMElement; const BaseUrl: String);
42 public
43 { Texture basename to associate this property will all appearances
44 using given texture. For now, this is the only way to associate
45 property, but more are possible in the future (like MaterialNodeName).
46
47 @deprecated All properties affected by this filter are deprecated. }
48 property TextureBaseName: String read FTextureBaseName write FTextureBaseName; {$ifdef FPC}deprecated;{$endif}
49
50 {$ifndef CASTLE_STRICT_CLI}
51 { Footsteps sound to make when player is walking on this material.
52 nil if no information is available.
53
54 @deprecated }
55 property FootstepsSound: TCastleSound read FFootstepsSound write FFootstepsSound; {$ifdef FPC}deprecated;{$endif}
56 {$endif}
57
58 { Is the floor toxic when walking on it.
59 Taken into account only if you assign @code(TLevel.Player).
60
61 @deprecated Just like @code(TLevel.Player).
62 @groupBegin }
63 property Toxic: Boolean read FToxic write FToxic; {$ifdef FPC}deprecated;{$endif}
64 property ToxicDamageConst: Single read FToxicDamageConst write FToxicDamageConst; {$ifdef FPC}deprecated;{$endif}
65 property ToxicDamageRandom: Single read FToxicDamageRandom write FToxicDamageRandom; {$ifdef FPC}deprecated;{$endif}
66 property ToxicDamageTime: Single read FToxicDamageTime write FToxicDamageTime; {$ifdef FPC}deprecated;{$endif}
67 { @groupEnd }
68
69 { Normal map texture URL. This is a simple method to activate bump mapping,
70 equivalent to using normalMap field in an Appearance node of VRML/X3D, see
71 https://castle-engine.io/x3d_extensions.php#section_ext_bump_mapping .
72
73 In case both VRML/X3D Appearance specifies normalMap and we have
74 NormalMap defined here, the VRML/X3D Appearance is used.
75
76 @deprecated Normal maps can be specified comfortably in glTF, X3D, Blender files. }
77 property NormalMap: String read FNormalMap write FNormalMap; {$ifdef FPC}deprecated;{$endif}
78
79 { Override alpha channel type for diffuse texture.
80 The meaning and allowed values for this are the same as for
81 alphaChannel field for texture nodes, see
82 https://castle-engine.io/x3d_extensions.php#section_ext_alpha_channel_detection .
83 Empty value (default) doesn't change the alpha channel type
84 (set in VRML/X3D or auto-detected).
85
86 @deprecated Alpha can be specified comfortably in glTF, X3D, Blender files. }
87 property AlphaChannel: String read FAlphaChannel write FAlphaChannel; {$ifdef FPC}deprecated;{$endif}
88 end;
89
90 TMaterialPropertyList = {$ifdef FPC}specialize{$endif} TObjectList<TMaterialProperty>;
91
92 TCompressionsMap = {$ifdef FPC}specialize{$endif} TDictionary<TTextureCompression, TCastlePlatforms>;
93
94 TTextureCompressionsToGenerate = class
95 { Compressions.Keys are the compressed formats to generate.
96 For each compression format, we also specify the platforms on
97 which is should be distributed and used. }
98 Compressions: TCompressionsMap;
99 { In addition to Compressions.Keys,
100 generate also the most suitable variant of DXTn compression. }
101 DxtAutoDetect: Boolean;
102 DxtAutoDetectPlatforms: TCastlePlatforms;
103 constructor Create;
104 destructor Destroy; override;
105 { HasSomeCompression means that some compression is indicated
106 (DxtAutoDetect is true, or Compressions are not empty). }
107 //function HasSomeCompression: Boolean; // unused
108 end;
109
110 { How to scale texture. }
111 TScale = record
112 { The scale (as in ScaledWidth := Width / (2 ^ Scale.Value).
113 Should be intepreted just like TextureLoadingScale.
114 See https://castle-engine.io/creating_data_auto_generated_textures.php#section_texture_scale }
115 Value: Byte;
116 { List of platforms for which this scale should be packaged. }
117 Platforms: TCastlePlatforms;
118 end;
119 TScalesList = {$ifdef FPC}specialize{$endif} TList<TScale>;
120
121 TAutoGeneratedTextures = class
122 strict private
123 const
124 PathsIgnoreCase = true;
125 var
126 FAutoProcessImageUrls: Boolean;
127 IncludePaths: TCastleStringList; // absolute URLs
128 IncludePathsRecursive: TBooleanList;
129 ExcludePaths: TCastleStringList;
130 { necessary for Exclude with relative dirs, like "entites/*", to work }
131 FBaseUrl: String;
132 FCompressedFormatsToGenerate: TTextureCompressionsToGenerate;
133 GatheringResult: TCastleStringList;
134 FScales: TScalesList;
135 FPreferredOutputFormat: String;
136 FTrivialUncompressedConvert: Boolean;
137 FMipmapsLevel: Cardinal;
138 FAutoGeneratedAtLoad: TAutoGenerated;
139 procedure GatherCallback(const FileInfo: TFileInfo; var StopSearch: Boolean);
140 procedure LoadImageEvent(var Url: String);
141 function IsAbsoluteUrlMatchingRelativeMask(const Url, Mask: String): Boolean;
142 private
143 { Largest Scale.Value for this texture. }
144 function LargestScaleValue: Byte;
145 function TextureUrlMatches(const Url: String): Boolean;
146 function AutoGeneratedTextures: TCastleStringList;
147 function CompressedFormatsGenerated: TCompressionsMap;
148 property PreferredOutputFormat: String read FPreferredOutputFormat;
149 public
150 constructor Create(const Element: TDOMElement; const BaseUrl: String;
151 const AnAutoProcessImageUrls: Boolean; const AnAutoGeneratedAtLoad: TAutoGenerated);
152 destructor Destroy; override;
153
154 { For given texture (absolute) URL and compression and scaling,
155 return the proper (absolute) URL of auto-compressed and auto-downscaled counterpart.
156 Scaling is defined just like TextureLoadingScale. }
157 function GeneratedTextureUrl(const Url: String;
158 const UseCompression: Boolean; const TextureCompression: TTextureCompression;
159 const Scaling: Cardinal): String;
160
161 { Automatic compression formats generated for this texture.
162 May return @nil, if there are no compressed formats to generate for this texture.
163 The resulting class instance cannot be modified, and it is owned by this TMaterialProperties
164 instance, so don't free it yourself. }
165 property CompressedFormatsToGenerate: TTextureCompressionsToGenerate
166 read FCompressedFormatsToGenerate;
167
168 { Determine the platforms for which the original texture should be packaged }
169 function OriginalPlatforms: TCastlePlatforms;
170
171 { Which scales to generate for this texture. Read-only. }
172 property Scales: TScalesList read FScales;
173
174 { Perform trivial conversion (that does not compress, does not downscale)
175 for this texture. }
176 property TrivialUncompressedConvert: Boolean read FTrivialUncompressedConvert;
177
178 property MipmapsLevel: Cardinal read FMipmapsLevel;
179 end;
180
181 TAutoGeneratedTexturesList = {$ifdef FPC}specialize{$endif} TObjectList<TAutoGeneratedTextures>;
182
183 { Store information that is naturally associated with a given material
184 or texture in an external file. Documentation and example of such
185 file is on https://castle-engine.io/creating_data_auto_generated_textures.php .
186 Right now this allows to define things like:
187
188 @unorderedList(
189 @itemSpacing compact
190 @item footsteps,
191 @item toxic ground (hurts player),
192 @item bump mapping (normal maps and height maps for given texture),
193 @item texture GPU-compressed and downscaled alternatives.
194 )
195
196 In the future, it should be possible to express all these properties
197 in pure VRML/X3D (inside Appearance / Material / ImageTexture nodes).
198 Right now, you can do this with bump mapping, see
199 https://castle-engine.io/x3d_extensions.php#section_ext_bump_mapping ,
200 but not footsteps or toxic ground.
201 In the future it should also be possible to express these properties
202 in 3D authoring software (like Blender), and easily export them
203 to appropriate VRML/X3D nodes.
204 For now, this TMaterialProperty allows us to easily customize materials
205 in a way that is not possible in Blender.
206
207 Using an external file for material properties has also long-term
208 advantages: it can be shared across many 3D models, for example
209 you can define footsteps sound for all grounds using the @code(grass.png)
210 textures, in all levels, at once.
211
212 You have to load an XML file by setting
213 @link(TMaterialProperties.Url MaterialProperties.Url) property.
214 }
215 TMaterialProperties = class
216 strict private
217 FAutoGeneratedTexturesList: TAutoGeneratedTexturesList;
218 FMaterialPropertyList: TMaterialPropertyList;
219 FUrl: String;
220 FAutoProcessImageUrls: Boolean;
221 { Information about available (already created) compressed/downscaled textures.
222 Obtained from CastleAutoGenerated.xml at the moment of TMaterialProperties.Create
223 (so, at application start in practice). }
224 FAutoGeneratedAtLoad: TAutoGenerated;
225 procedure SetUrl(const Value: String);
226 public
227 constructor Create(const AnAutoProcessImageUrls: Boolean);
228 destructor Destroy; override;
229
230 { Load material properties from given XML file.
231 Set this to empty string to unload previously loaded properties.
232 See Castle1 and fps_game data for examples how this looks like,
233 in @code(material_properties.xml). }
234 property Url: String read FUrl write SetUrl;
235
236 {$ifdef FPC}
237 property FileName: String read FUrl write SetUrl; deprecated 'use Url';
238 {$endif}
239
240 { Find material properties for given texture basename.
241 Returns @nil if no material properties are found
242 (in particular, if @link(Url) was not set yet). }
243 function FindTextureBaseName(const TextureBaseName: String): TMaterialProperty;
244
245 { Get the Urls of all textures that should have automatically
246 generated GPU-compressed and downscaled counterparts.
247 Returns a list of absolute Urls.
248 This actually searches on disk, right now, to find the texture list,
249 applying the include/exclude rules specified in material_properties.xml file.
250
251 This is to be used by "castle-engine auto-generate-textures"
252 tool, or similar tools.
253
254 The objects on this list refer to TAutoGeneratedTextures objects
255 that define @italic(how) to process this texture.
256
257 Caller is responsible for freeing the returned TCastleStringList list. }
258 function AutoGeneratedTextures: TCastleStringList;
259 end;
260
261 { Material and texture properties, see @link(TMaterialProperties).
262 Automatically loaded from castle-data:/material_properties.xml at OpenGL initialization. }
263 function MaterialProperties: TMaterialProperties;
264
265 implementation
266
267 uses SysUtils, XMLRead, StrUtils, Math,
268 CastleXmlUtils, CastleFilesUtils, CastleApplicationProperties, CastleTextureImages,
269 CastleUriUtils, CastleDownload, CastleLog;
270
271 const
272 MaxScale = 32;
273
274 { TMaterialProperty --------------------------------------------------------- }
275
276 procedure TMaterialProperty.LoadFromDOMElement(Element: TDOMElement; const BaseUrl: String);
277 var
278 {$ifndef CASTLE_STRICT_CLI}
279 FootstepsSoundName: String;
280 {$endif}
281 ToxicDamage: TDOMElement;
282 I: TXMLElementIterator;
283 begin
284 if not Element.AttributeString('texture_base_name', FTextureBaseName) then
285 raise Exception.Create('<properties> element must have "texture_base_name" attribute');
286
287 {$ifndef CASTLE_STRICT_CLI}
288 {$warnings off} // using deprecated SoundFromName for deprecated footsteps_sound
289 FootstepsSoundName := '';
290 if Element.AttributeString('footsteps_sound', FootstepsSoundName) and
291 (FootstepsSoundName <> '') then
292 FFootstepsSound := SoundEngine.SoundFromName(FootstepsSoundName)
293 else
294 FFootstepsSound := nil;
295 {$warnings on}
296 {$endif}
297
298 if Element.AttributeString('normal_map', FNormalMap) and (FNormalMap <> '') then
299 FNormalMap := CombineUri(BaseUrl, FNormalMap) else
300 FNormalMap := '';
301
302 if not Element.AttributeString('alpha_channel', FAlphaChannel) then
303 FAlphaChannel := '';
304
305 I := Element.ChildrenIterator;
306 try
307 while I.GetNext do
308 if I.Current.TagName = 'toxic' then
309 begin
310 FToxic := true;
311 ToxicDamage := I.Current.ChildElement('damage');
312 if not ToxicDamage.AttributeSingle('const', FToxicDamageConst) then
313 FToxicDamageConst := 0;
314 if not ToxicDamage.AttributeSingle('random', FToxicDamageRandom) then
315 FToxicDamageRandom := 0;
316 if not ToxicDamage.AttributeSingle('time', FToxicDamageTime) then
317 FToxicDamageTime := 0;
318 end else
319 raise Exception.CreateFmt('Unknown element inside <property>: "%s"',
320 [I.Current.TagName]);
321 finally FreeAndNil(I) end;
322 end;
323
324 { TTextureCompressionsToGenerate ----------------------------------------------------------- }
325
326 constructor TTextureCompressionsToGenerate.Create;
327 begin
328 inherited;
329 Compressions := TCompressionsMap.Create;
330 end;
331
332 destructor TTextureCompressionsToGenerate.Destroy;
333 begin
334 FreeAndNil(Compressions);
335 inherited;
336 end;
337
338 // function TTextureCompressionsToGenerate.HasSomeCompression: Boolean;
339 // begin
340 // Result := (Compressions.Count <> 0) or DxtAutoDetect;
341 // end;
342
343 { TAutoGeneratedTextures ----------------------------------------------------- }
344
345 constructor TAutoGeneratedTextures.Create(
346 const Element: TDOMElement; const BaseUrl: String;
347 const AnAutoProcessImageUrls: Boolean;
348 const AnAutoGeneratedAtLoad: TAutoGenerated);
349
350 function PlatformsOfTextureCompression(const Element: TDOMElement): TCastlePlatforms;
351 var
352 PlatformsElement: TDOMElement;
353 I: TXMLElementIterator;
354 begin
355 PlatformsElement := Element.Child('platforms', false);
356 if PlatformsElement <> nil then
357 begin
358 Result := [];
359 I := PlatformsElement.ChildrenIterator('platform');
360 try
361 while I.GetNext do
362 Include(Result, StrToPlatform(Trim(I.Current.TextData)));
363 finally FreeAndNil(I) end;
364 end else
365 Result := AllPlatforms;
366 end;
367
368 function StrToScale(const AString: String): Cardinal;
369 begin
370 Result := StrToInt(AString);
371 if Result < 1 then
372 raise Exception.CreateFmt('Error reading scale value "%s", the scale must be >= 1.', [AString]);
373 if Result > MaxScale then
374 raise Exception.CreateFmt('Error reading scale value "%s", the scale must be <= %d.', [AString, MaxScale]);
375 end;
376
377 var
378 ChildElements: TXMLElementIterator;
379 ChildElement, CompressElement, ScalesElement, PlatformsElement, PreferredOutputFormatElement, MipmapsElement: TDOMElement;
380 TextureCompressionName: String;
381 ASmallestScale: Cardinal;
382 ScalesIterator, PlatformsIterator: TXMLElementIterator;
383 Scale: TScale;
384 I: Integer;
385 begin
386 inherited Create;
387 FScales := TScalesList.Create;
388 FAutoProcessImageUrls := AnAutoProcessImageUrls;
389 IncludePaths := TCastleStringList.Create;
390 IncludePathsRecursive := TBooleanList.Create;
391 ExcludePaths := TCastleStringList.Create;
392 FCompressedFormatsToGenerate := TTextureCompressionsToGenerate.Create;
393 FBaseUrl := BaseUrl;
394 FAutoGeneratedAtLoad := AnAutoGeneratedAtLoad;
395
396 { read from XML }
397
398 ChildElements := Element.ChildrenIterator('include');
399 try
400 while ChildElements.GetNext do
401 begin
402 ChildElement := ChildElements.Current;
403 IncludePaths.Add(ChildElement.AttributeUrl('path', BaseUrl));
404 IncludePathsRecursive.Add(ChildElement.AttributeBooleanDef('recursive', false));
405 end;
406 finally FreeAndNil(ChildElements) end;
407
408 ChildElements := Element.ChildrenIterator('exclude');
409 try
410 while ChildElements.GetNext do
411 begin
412 ChildElement := ChildElements.Current;
413 ExcludePaths.Add(ChildElement.AttributeString('path'));
414 end;
415 finally FreeAndNil(ChildElements) end;
416
417 // calculate FCompressedFormatsToGenerate
418 CompressElement := Element.ChildElement('compress', false);
419 if CompressElement <> nil then
420 begin
421 ChildElements := CompressElement.ChildrenIterator('format');
422 try
423 while ChildElements.GetNext do
424 begin
425 TextureCompressionName := ChildElements.Current.AttributeString('name');
426 if LowerCase(TextureCompressionName) = 'dxt_autodetect' then
427 begin
428 FCompressedFormatsToGenerate.DxtAutoDetect := true;
429 FCompressedFormatsToGenerate.DxtAutoDetectPlatforms := PlatformsOfTextureCompression(ChildElements.Current);
430 end else
431 FCompressedFormatsToGenerate.Compressions.Add(
432 StringToTextureCompression(TextureCompressionName),
433 PlatformsOfTextureCompression(ChildElements.Current)
434 );
435 end;
436 finally FreeAndNil(ChildElements) end;
437 end;
438
439 ScalesElement := Element.ChildElement('scale', false);
440 if ScalesElement <> nil then
441 begin
442 { Deprecated "scale" element }
443 WriteLnWarning('AutoGeneratedTextures', 'MaterialProperties contains "scale" node which is deprecated, use "scales" instead and list all scales.');
444 if ScalesElement.HasAttribute('smallest') then
445 begin
446 WriteLnWarning('AutoGeneratedTextures', 'MaterialProperties contains "smallest" attribute which is deprecated.');
447 ASmallestScale := ScalesElement.AttributeCardinalDef('smallest', 1);
448 if not Between(ASmallestScale, 1, MaxScale) then
449 raise Exception.CreateFmt('Invalid scale smallest value "%d" (must be an integer number within 1..%d)', [ASmallestScale, MaxScale]);
450 for I := 1 to ASmallestScale do
451 begin
452 Scale.Platforms := AllPlatforms;
453 Scale.Value := I;
454 FScales.Add(Scale);
455 end;
456 end;
457 end;
458
459 ScalesElement := Element.ChildElement('scales', false);
460 if ScalesElement <> nil then
461 begin
462 ScalesIterator := ScalesElement.ChildrenIterator('scale');
463 try
464 while ScalesIterator.GetNext do
465 begin
466 Scale.Value := StrToScale(ScalesIterator.Current.AttributeString('value'));
467 Scale.Platforms := AllPlatforms;
468
469 PlatformsElement := ScalesIterator.Current.ChildElement('platforms', false);
470 if PlatformsElement <> nil then
471 begin
472 Scale.Platforms := [];
473 PlatformsIterator := PlatformsElement.ChildrenIterator('platform');
474 try
475 while PlatformsIterator.GetNext do
476 Include(Scale.Platforms, StrToPlatform(Trim(PlatformsIterator.Current.TextData)));
477 finally
478 FreeAndNil(PlatformsIterator);
479 end;
480 end;
481
482 FScales.Add(Scale);
483 end;
484 finally
485 FreeAndNil(ScalesIterator);
486 end;
487 end;
488
489 // no <scale> or <scales> in material_properties.xml file -> do not downscale
490 if FScales.Count = 0 then
491 begin
492 Scale.Value := 1;
493 Scale.Platforms := AllPlatforms;
494 FScales.Add(Scale);
495 end;
496
497 PreferredOutputFormatElement := Element.ChildElement('preferred_output_format', false);
498 if PreferredOutputFormatElement <> nil then
499 FPreferredOutputFormat := PreferredOutputFormatElement.AttributeStringDef('extension', '')
500 else
501 FPreferredOutputFormat := '.png';
502
503 FTrivialUncompressedConvert := Element.ChildElement('trivial_uncompressed_convert', false) <> nil;
504
505 MipmapsElement := Element.ChildElement('mipmaps', false);
506 if MipmapsElement <> nil then
507 begin
508 FMipmapsLevel := MipmapsElement.AttributeCardinalDef('level', 0);
509 { Mipmaps level = 0 and 1 are equivalent.
510 Make it easier and just always express them as 0 in rest of API. }
511 if FMipmapsLevel = 1 then
512 FMipmapsLevel := 0;
513 end else
514 FMipmapsLevel := 0;
515
516 if FAutoProcessImageUrls then
517 AddLoadImageListener({$ifdef FPC}@{$endif} LoadImageEvent);
518 end;
519
520 function TAutoGeneratedTextures.CompressedFormatsGenerated: TCompressionsMap;
521 begin
522 { TODO: for now, the DxtAutoDetect texture will not be used at all.
523 The actual value of CompressedFormatsGenerated
524 should come from auto_generated.xml. }
525 Result := FCompressedFormatsToGenerate.Compressions;
526 end;
527
528 destructor TAutoGeneratedTextures.Destroy;
529 begin
530 FreeAndNil(FScales);
531 FreeAndNil(IncludePaths);
532 FreeAndNil(IncludePathsRecursive);
533 FreeAndNil(ExcludePaths);
534 FreeAndNil(FCompressedFormatsToGenerate);
535 if FAutoProcessImageUrls then
536 RemoveLoadImageListener({$ifdef FPC}@{$endif} LoadImageEvent);
537 inherited;
538 end;
539
540 function TAutoGeneratedTextures.LargestScaleValue: Byte;
541 var
542 Scale: TScale;
543 begin
544 Result := 1;
545 for Scale in FScales do
546 if Scale.Value > Result then
547 Result := Scale.Value;
548 end;
549
550 procedure TAutoGeneratedTextures.GatherCallback(const FileInfo: TFileInfo; var StopSearch: Boolean);
551 begin
552 if (Pos('/' + TAutoGenerated.AutoGeneratedDirName + '/', FileInfo.Url) = 0) and
553 IsImageMimeType(UriMimeType(FileInfo.Url), false, false) then
554 GatheringResult.Add(FileInfo.Url);
555 end;
556
557 function TAutoGeneratedTextures.IsAbsoluteUrlMatchingRelativeMask(
558 const Url, Mask: String): Boolean;
559 var
560 U: String;
561 begin
562 U := PrefixRemove(ExtractUriPath(FBaseUrl), Url, PathsIgnoreCase);
563 Result := IsWild(U, Mask, PathsIgnoreCase);
564 end;
565
566 function TAutoGeneratedTextures.
567 AutoGeneratedTextures: TCastleStringList;
568
569 procedure Exclude(const ExcludePathMask: String; const Urls: TCastleStringList);
570 var
571 I: Integer;
572 begin
573 I := 0;
574 while I < Urls.Count do
575 begin
576 // Writeln('Excluding ExcludePathMask ' + ExcludePathMask +
577 // ' from ' + PrefixRemove(ExtractUriPath(FBaseUrl), Urls[I], PathsIgnoreCase));
578 if IsAbsoluteUrlMatchingRelativeMask(Urls[I], ExcludePathMask) then
579 Urls.Delete(I) else
580 Inc(I);
581 end;
582 end;
583
584 var
585 I: Integer;
586 FindOptions: TFindFilesOptions;
587 begin
588 Result := TCastleStringList.Create;
589 GatheringResult := Result;
590
591 for I := 0 to IncludePaths.Count - 1 do
592 begin
593 if IncludePathsRecursive[I] then
594 FindOptions := [ffRecursive] else
595 { not recursive, so that e.g. <include path="my_texture.png" />
596 or <include path="subdir/my_texture.png" />
597 should not include *all* my_texture.png files inside. }
598 FindOptions := [];
599 FindFiles(IncludePaths[I], false, {$ifdef FPC}@{$endif} GatherCallback, FindOptions);
600 end;
601
602 GatheringResult := nil;
603
604 for I := 0 to ExcludePaths.Count - 1 do
605 Exclude(ExcludePaths[I], Result);
606 end;
607
608 function TAutoGeneratedTextures.TextureUrlMatches(const Url: String): Boolean;
609
610 { Check is Url not excluded. }
611 function CheckNotExcluded: Boolean;
612 var
613 I: Integer;
614 begin
615 for I := 0 to ExcludePaths.Count - 1 do
616 if IsAbsoluteUrlMatchingRelativeMask(Url, ExcludePaths[I]) then
617 Exit(false);
618 Result := true;
619 end;
620
621 var
622 UrlName, UrlPath: String;
623 I: Integer;
624 IncludePath, IncludeMask: String;
625 PathMatches: Boolean;
626 begin
627 Result := false;
628 UrlPath := ExtractUriPath(Url);
629 UrlName := ExtractUriName(Url);
630 for I := 0 to IncludePaths.Count - 1 do
631 begin
632 IncludePath := ExtractUriPath(IncludePaths[I]);
633 IncludeMask := ExtractUriName(IncludePaths[I]);
634 if IncludePathsRecursive[I] then
635 PathMatches := IsPrefix(IncludePath, UrlPath, PathsIgnoreCase) else
636 PathMatches := AnsiSameText(IncludePath, UrlPath); { assume PathsIgnoreCase=true }
637 if PathMatches and IsWild(UrlName, IncludeMask, PathsIgnoreCase) then
638 begin
639 Result := CheckNotExcluded;
640 Exit;
641 end;
642 end;
643 end;
644
645 procedure TAutoGeneratedTextures.LoadImageEvent(
646 var Url: String);
647
648 { Returns @true if the texture has square size.
649 @false otherwise.
650 If it's unknown, returns @false too.
651
652 This uses CastleAutoGenerated.xml information to work without any file reading.
653 If the Url is in our data, and it is in CastleAutoGenerated.xml,
654 then we check it's size according to CastleAutoGenerated.xml. }
655 function IsSquareTexture(const Url: String): Boolean;
656 var
657 Texture: TAutoGenerated.TTexture;
658 WasInsideData: Boolean;
659 UrlInData: String;
660 begin
661 UrlInData := RelativeToCastleDataUrl(Url, WasInsideData);
662 if not WasInsideData then
663 Exit(false);
664 Texture := FAutoGeneratedAtLoad.Texture(UrlInData, [], false);
665 Result := (Texture <> nil) and (Texture.Width = Texture.Height);
666 end;
667
668 { Texture has GPU-compressed and/or downscaled counterpart, according to include/exclude
669 variables. So try to replace Url with something compressed and downscaled. }
670 procedure ReplaceUrl;
671 var
672 C: TTextureCompression;
673 Scale: Cardinal;
674 CompressionPair: {$ifdef FPC}TCompressionsMap.TDictionaryPair{$else}
675 TPair<TTextureCompression, TCastlePlatforms>{$endif};
676 begin
677 { Do not warn about it, just as we don't warn when TextureLoadingScale = 2
678 but we're loading image not mentioned in <auto_generated_textures>.
679 if TextureLoadingScale > SmallestScale then
680 raise Exception.CreateFmt('Invalid TextureLoadingScale %d, we do not have such downscaled images. You should add or modify the <scale smallest=".." /> declaration in "material_properties.xml", and make sure thar you load the "material_properties.xml" early enough.',
681 [TextureLoadingScale]); }
682 Scale := Min(LargestScaleValue, TextureLoadingScale);
683
684 if not SupportedTextureCompressionKnown then
685 WritelnWarning('MaterialProperties', 'Cannot determine whether to use auto-generated (GPU compressed and/or downscaled) texture version for ' + Url + ' because the image is loaded before GPU capabilities are known')
686 else
687 begin
688 {$ifdef CASTLE_IOS}
689 if not IsSquareTexture(Url) then
690 begin
691 WritelnWarning('MaterialProperties', 'Not using GPU compressed (and potentially downscaled) version for ' + Url + ' because on iOS non-square compressed textures are not supported');
692 end else
693 {$endif}
694 for CompressionPair in CompressedFormatsGenerated do
695 begin
696 C := CompressionPair.Key;
697 if (C in SupportedTextureCompression) and (Platform in CompressionPair.Value) then
698 begin
699 Url := GeneratedTextureUrl(Url, true, C, Scale);
700 WritelnLog('MaterialProperties', 'Using GPU compressed (and potentially downscaled) alternative ' + Url);
701 Exit;
702 end;
703 end;
704 end;
705
706 { no GPU compression supported; still, maybe we should use a downscaled alternative }
707 if (Scale <> 1) or TrivialUncompressedConvert then
708 begin
709 Url := GeneratedTextureUrl(Url, false, Low(TTextureCompression), Scale);
710 WritelnLog('MaterialProperties', 'Using alternative ' + Url);
711 end;
712 end;
713
714 begin
715 if TextureUrlMatches(Url) then
716 ReplaceUrl;
717 end;
718
719 function TAutoGeneratedTextures.GeneratedTextureUrl(
720 const Url: String;
721 const UseCompression: Boolean; const TextureCompression: TTextureCompression;
722 const Scaling: Cardinal): String;
723 begin
724 Result := ExtractUriPath(Url) + TAutoGenerated.AutoGeneratedDirName + '/';
725 if UseCompression then
726 Result := Result + LowerCase(TextureCompressionToString(TextureCompression)) + '/'
727 else
728 Result := Result + 'uncompressed/';
729 if Scaling <> 1 then
730 Result := Result + 'downscaled_' + IntToStr(Scaling) + '/';
731 Result := Result + ExtractUriName(Url);
732 if UseCompression then
733 Result := Result + TextureCompressionInfo[TextureCompression].FileExtension
734 else
735 Result := Result + PreferredOutputFormat;
736 end;
737
738 function TAutoGeneratedTextures.OriginalPlatforms: TCastlePlatforms;
739 var
740 Scale: TScale;
741 begin
742 Result := [];
743 for Scale in Scales do
744 if Scale.Value = 1 then
745 Result := Result + Scale.Platforms;
746 end;
747
748 { TMaterialProperties ---------------------------------------------------------- }
749
750 constructor TMaterialProperties.Create(const AnAutoProcessImageUrls: Boolean);
751 begin
752 inherited Create;
753 FAutoProcessImageUrls := AnAutoProcessImageUrls;
754 FMaterialPropertyList := TMaterialPropertyList.Create({ owns objects } true);
755 FAutoGeneratedTexturesList := TAutoGeneratedTexturesList.Create({ owns objects } true);
756
757 FAutoGeneratedAtLoad := TAutoGenerated.Create;
758 FAutoGeneratedAtLoad.LoadFromFile('castle-data:/CastleAutoGenerated.xml');
759 end;
760
761 destructor TMaterialProperties.Destroy;
762 begin
763 FreeAndNil(FAutoGeneratedAtLoad);
764 FreeAndNil(FAutoGeneratedTexturesList);
765 FreeAndNil(FMaterialPropertyList);
766 inherited;
767 end;
768
769 procedure TMaterialProperties.SetUrl(const Value: String);
770 var
771 Config: TXMLDocument;
772 Elements: TXMLElementIterator;
773 MaterialProperty: TMaterialProperty;
774 Stream: TStream;
775 begin
776 FUrl := Value;
777
778 FMaterialPropertyList.Clear;
779 FAutoGeneratedTexturesList.Clear;
780
781 if Url = '' then Exit;
782
783 Stream := Download(Url);
784 try
785 ReadXMLFile(Config, Stream, Url);
786 finally FreeAndNil(Stream) end;
787
788 try
789 Check(Config.DocumentElement.TagName = 'properties',
790 'Root node of material properties file must be <properties>');
791
792 Elements := Config.DocumentElement.ChildrenIterator('property');
793 try
794 while Elements.GetNext do
795 begin
796 MaterialProperty := TMaterialProperty.Create;
797 FMaterialPropertyList.Add(MaterialProperty);
798 MaterialProperty.LoadFromDOMElement(Elements.Current, AbsoluteUri(Url));
799 end;
800 finally FreeAndNil(Elements); end;
801
802 Elements := Config.DocumentElement.ChildrenIterator('auto_generated_textures');
803 try
804 while Elements.GetNext do
805 begin
806 FAutoGeneratedTexturesList.Add(
807 TAutoGeneratedTextures.Create(Elements.Current, Url, FAutoProcessImageUrls,
808 FAutoGeneratedAtLoad));
809 end;
810 finally FreeAndNil(Elements); end;
811 finally
812 SysUtils.FreeAndNil(Config);
813 end;
814 end;
815
816 function TMaterialProperties.FindTextureBaseName(const TextureBaseName: String): TMaterialProperty;
817 var
818 I: Integer;
819 begin
820 {$warnings off} // using deprecated material props to keep them working
821 for I := 0 to FMaterialPropertyList.Count - 1 do
822 if SameText(FMaterialPropertyList[I].TextureBaseName, TextureBaseName) then
823 Exit(FMaterialPropertyList[I]);
824 {$warnings on}
825 Result := nil;
826 end;
827
828 function TMaterialProperties.AutoGeneratedTextures: TCastleStringList;
829 var
830 S: TCastleStringList;
831 I, J: Integer;
832 begin
833 Result := TCastleStringList.Create;
834 try
835 for I := 0 to FAutoGeneratedTexturesList.Count - 1 do
836 begin
837 S := FAutoGeneratedTexturesList[I].AutoGeneratedTextures;
838 try
839 for J := 0 to S.Count - 1 do
840 begin
841 if Result.IndexOf(S[J]) <> -1 then
842 WritelnWarning('MaterialProperties', Format('The texture URL "%s" is under the influence of more than one <auto_generated_textures> rule. Use <include> and <exclude> to avoid it',
843 [S[J]]))
844 else
845 Result.AddObject(S[J], FAutoGeneratedTexturesList[I]);
846 end;
847 finally FreeAndNil(S) end;
848 end;
849 except FreeAndNil(Result); raise end;
850 end;
851
852 { globals -------------------------------------------------------------------- }
853
854 var
855 FMaterialProperties: TMaterialProperties;
856
857 function MaterialProperties: TMaterialProperties;
858 begin
859 if FMaterialProperties = nil then
860 FMaterialProperties := TMaterialProperties.Create(true);
861 Result := FMaterialProperties;
862 end;
863
864 procedure LoadMaterialProperties;
865 begin
866 if UriFileExists('castle-data:/material_properties.xml') then
867 begin
868 WritelnLog('Found and loading castle-data:/material_properties.xml');
869 MaterialProperties.Url := 'castle-data:/material_properties.xml';
870 end;
871 end;
872
873 initialization
874 ApplicationProperties.OnGLContextEarlyOpen.Add({$ifdef FPC}@{$endif} LoadMaterialProperties);
875 finalization
876 FreeAndNil(FMaterialProperties);
877 end.