Debian Codegraph @

src/scene/castleinternalrenderer_cache.inc

raw
1 {%MainUnit castleinternalrenderer.pas}
2 {
3 Copyright 2002-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Types used by TRendererCache. }
18
19 {$ifdef read_interface}
20 //type
21 { Cache to share prepared renderer (OpenGL) resources,
22 like textures and shaders. This allows to share OpenGL resources
23 between multiple X3D nodes, in turn between multiple TCastleScenes.
24 This may save a lot of OpenGL memory (and time to upload textures to GPU)
25 when the same texture is referenced from various models,
26 or the same shader is used by various models.
27
28 This cache is used by TRenderer, but the cache has no connections to
29 any particular TRenderer.
30 So the cache can have a longer lifetime than TRenderer.
31 In practice, we use now a single global instance of this cache
32 in @link(RendererCache).
33 In constrast, there can be many TRenderer instances (one per viewport),
34 and each TCastleScene and TGLShape during it's life may switch
35 between viewports (so also between renderers).
36
37 The cache can only be used in OpenGL contexts sharing resources.
38 In CGE, all OpenGL contexts (created by TCastleWindow and TCastleControl)
39 share resources. }
40 TRendererCache = class
41 private
42 FFreeWhenEmpty: Boolean;
43 FFreeWhenEmptyInstanceToNil: PObject;
44 TextureImageCaches: TTextureImageCacheList;
45 TextureVideoCaches: TTextureVideoCacheList;
46 TextureCubeMapCaches: TTextureCubeMapCacheList;
47 Texture3DCaches: TTexture3DCacheList;
48 TextureDepthOrFloatCaches: TTextureDepthOrFloatCacheList;
49 ShapeCaches: array [{ DisableSharedCache } Boolean] of TShapeCacheList;
50 ProgramCaches: TShaderProgramCacheList;
51
52 function Empty: Boolean;
53
54 { If we are empty, and FFreeWhenEmpty, then free self.
55 Beware: calling this procedure may free the current instance.
56 Do not access anything from this instance after calling this method. }
57 procedure CheckFreeWhenEmpty;
58
59 { Load given texture to OpenGL, using our cache.
60
61 @raises(ETextureLoadError If texture cannot be loaded for whatever
62 reason.) }
63 function TextureImage_IncReference(
64 const TextureImage: TEncodedImage;
65 const TextureFullUrl: String;
66 const Filter: TTextureFilter;
67 const TextureAnisotropy: TGLfloat;
68 const TextureWrap: TTextureWrap2D;
69 const CompositeForMipmaps: TCompositeImage;
70 const GUITexture: boolean;
71 const FlipVertically: Boolean): TGLuint;
72
73 procedure TextureImage_DecReference(
74 const TextureGLName: TGLuint);
75
76 function TextureVideo_IncReference(
77 const TextureVideo: TVideo;
78 const TextureFullUrl: String;
79 const FlipVertically: Boolean;
80 const Filter: TTextureFilter;
81 const TextureAnisotropy: TGLfloat;
82 const TextureWrap: TTextureWrap2D;
83 const GUITexture: boolean): TGLVideo3D;
84
85 procedure TextureVideo_DecReference(
86 const TextureVideo: TGLVideo3D);
87
88 { Load given cube texture to OpenGL, using our cache.
89
90 @raises(ETextureLoadError If texture cannot be loaded for whatever
91 reason.) }
92 function TextureCubeMap_IncReference(
93 const TextureFullUrl: String;
94 const Filter: TTextureFilter;
95 const Anisotropy: TGLfloat;
96 const PositiveX, NegativeX,
97 PositiveY, NegativeY,
98 PositiveZ, NegativeZ: TEncodedImage;
99 const CompositeForMipmaps: TCompositeImage): TGLuint;
100
101 procedure TextureCubeMap_DecReference(
102 const TextureGLName: TGLuint);
103
104 { Requires GLFeatures.TextureDepthCompare (not just TextureDepth!) before calling this. }
105 function TextureDepth_IncReference(
106 const TextureFullUrl: String;
107 const TextureWrap: TTextureWrap2D;
108 const Width, Height: Cardinal): TGLuint;
109
110 procedure TextureDepth_DecReference(
111 const TextureGLName: TGLuint);
112
113 { Increase / decrease reference to a float texture.
114 Required GLFeatures.TextureFloat before calling this.
115 Precision32 = @true requires 32-bit full Single floats,
116 Precision32 = @false requires 16-bit (half) floats. }
117 function TextureFloat_IncReference(
118 const TextureFullUrl: String;
119 const Filter: TTextureFilter;
120 const TextureWrap: TTextureWrap2D;
121 const Width, Height: Cardinal;
122 const Precision32: boolean): TGLuint;
123 procedure TextureFloat_DecReference(
124 const TextureGLName: TGLuint);
125
126 { Load given 3D texture to OpenGL, using our cache.
127
128 @raises(ETextureLoadError If texture cannot be loaded for whatever
129 reason.) }
130 function Texture3D_IncReference(
131 const TextureFullUrl: String;
132 const Filter: TTextureFilter;
133 const Anisotropy: TGLfloat;
134 const TextureWrap: TTextureWrap3D;
135 const Image: TEncodedImage;
136 const Composite: TCompositeImage): TGLuint;
137
138 procedure Texture3D_DecReference(
139 const TextureGLName: TGLuint);
140 public
141 constructor Create;
142 destructor Destroy; override;
143
144 { Shape cache. We return TShapeCache, either taking an existing
145 instance from cache or creating and adding a new one.
146 Caller is responsible for checking are Arrays / Vbo zero and
147 eventually initializing and setting. }
148 function Shape_IncReference(const Shape: TX3DRendererShape;
149 const RenderOptions: TCastleRenderOptions): TShapeCache;
150
151 procedure Shape_DecReference(const Shape: TX3DRendererShape;
152 var ShapeCache: TShapeCache);
153
154 { Shader program cache. We return TShaderProgramCache,
155 either taking an existing instance from cache or creating and adding
156 a new one. If we create a new one, we will use Shader to initialize
157 program hash and to create and link actual TX3DGLSLProgram instance. }
158 function Program_IncReference(
159 Shader: TShader; const ShapeNiceName: string): TShaderProgramCache;
160
161 procedure Program_DecReference(var ProgramCache: TShaderProgramCache);
162
163 { Free (and Self <> nil) when the cache will be empty (maybe immediately,
164 maybe later).
165
166 Beware: calling this procedure may free the current instance.
167 Do not access anything from this instance after calling this method.
168
169 After this procedure, any Xxx_DecReference call also may free
170 the cache instance. }
171 procedure FreeWhenEmpty(const InstanceToNil: PObject);
172 end;
173 {$endif read_interface}
174
175 {$ifdef read_implementation}
176
177 { TRendererCache -------------------------------------------- }
178
179 constructor TRendererCache.Create;
180 var
181 B: Boolean;
182 begin
183 inherited;
184 TextureImageCaches := TTextureImageCacheList.Create;
185 TextureVideoCaches := TTextureVideoCacheList.Create;
186 TextureCubeMapCaches := TTextureCubeMapCacheList.Create;
187 Texture3DCaches := TTexture3DCacheList.Create;
188 TextureDepthOrFloatCaches := TTextureDepthOrFloatCacheList.Create;
189 for B := Low(Boolean) to High(Boolean) do
190 ShapeCaches[B] := TShapeCacheList.Create;
191 ProgramCaches := TShaderProgramCacheList.Create;
192 end;
193
194 destructor TRendererCache.Destroy;
195
196 {.$define ONLY_WARN_ON_CACHE_LEAK}
197
198 {$ifdef ONLY_WARN_ON_CACHE_LEAK}
199 procedure Assert(const B: boolean; const S: string = '');
200 begin
201 if not B then
202 WritelnWarning('VRML/X3D', 'GLRendererContextCache warning: ' + S);
203 end;
204 {$endif}
205
206 var
207 B: Boolean;
208 begin
209 if TextureImageCaches <> nil then
210 begin
211 Assert(TextureImageCaches.Count = 0, 'Some references to texture images still exist' +
212 ' when freeing TRendererCache');
213 FreeAndNil(TextureImageCaches);
214 end;
215
216 if TextureVideoCaches <> nil then
217 begin
218 Assert(TextureVideoCaches.Count = 0, 'Some references to texture videos still exist' +
219 ' when freeing TRendererCache');
220 FreeAndNil(TextureVideoCaches);
221 end;
222
223 if TextureCubeMapCaches <> nil then
224 begin
225 Assert(TextureCubeMapCaches.Count = 0, 'Some references to texture cubemaps still exist' +
226 ' when freeing TRendererCache');
227 FreeAndNil(TextureCubeMapCaches);
228 end;
229
230 if Texture3DCaches <> nil then
231 begin
232 Assert(Texture3DCaches.Count = 0, 'Some references to texture 3D still exist' +
233 ' when freeing TRendererCache');
234 FreeAndNil(Texture3DCaches);
235 end;
236
237 if TextureDepthOrFloatCaches <> nil then
238 begin
239 Assert(TextureDepthOrFloatCaches.Count = 0, 'Some references to depth or float texture still exist' +
240 ' when freeing TRendererCache');
241 FreeAndNil(TextureDepthOrFloatCaches);
242 end;
243
244 for B := Low(Boolean) to High(Boolean) do
245 if ShapeCaches[B] <> nil then
246 begin
247 Assert(ShapeCaches[B].Count = 0, Format('%d references to shapes still exist on ShapeCaches[%s] when freeing TRendererCache', [
248 ShapeCaches[B].Count,
249 BoolToStr(B, true)
250 // ShapeCaches[B][0].ToString // not printed, risks further SEGFAULT during log output in case invalid reference remained on the list
251 ]));
252 FreeAndNil(ShapeCaches[B]);
253 end;
254
255 if ProgramCaches <> nil then
256 begin
257 Assert(ProgramCaches.Count = 0, 'Some references to GLSL programs still exist' +
258 ' when freeing TRendererCache');
259 FreeAndNil(ProgramCaches);
260 end;
261
262 inherited;
263 end;
264
265 function TRendererCache.TextureImage_IncReference(
266 const TextureImage: TEncodedImage;
267 const TextureFullUrl: String;
268 const Filter: TTextureFilter;
269 const TextureAnisotropy: TGLfloat;
270 const TextureWrap: TTextureWrap2D;
271 const CompositeForMipmaps: TCompositeImage;
272 const GUITexture: boolean;
273 const FlipVertically: Boolean): TGLuint;
274 var
275 I: Integer;
276 TextureCached: TTextureImageCache;
277 begin
278 for I := 0 to TextureImageCaches.Count - 1 do
279 begin
280 TextureCached := TextureImageCaches[I];
281
282 { Once I had an idea to make here comparison with
283 TextureImage = TextureCached^.Image. Since we have TTexturesVideosCache,
284 so images from the same URL would have the same reference, so this
285 would work perfectly, and make comparison with TextureURL obsolete, right ?
286
287 But there's a problem with this: Image reference may be freed while
288 the corresponding texture is still cached. In fact, it's normal in
289 "The Castle", if you use FreeResources([frTexturesInNodes]) feature.
290 Which means that Image reference may become invalid, and, worse,
291 another Image may be potentially assigned the same reference.
292
293 What would be needed is to automatically set cached Image reference
294 to nil (and implement to not use Image reference if it's nil) if
295 Image instance is freed. Something like FreeNotification.
296
297 But still, the same FreeResources([frTexturesInNodes]) would prevent
298 the texture from sharing, if we would free the texture prematurely
299 and later load the same texture, with to different TCastleImage instance.
300
301 For now, I don't use this idea, and rely on TextureFullUrl. }
302
303 if (TextureFullUrl <> '') and
304 (TextureCached.FullUrl = TextureFullUrl) and
305 (TextureCached.FlipVertically = FlipVertically) and
306 (TextureCached.Filter = Filter) and
307 (TextureCached.Anisotropy = TextureAnisotropy) and
308 (TextureCached.Wrap = TextureWrap) and
309 (TextureCached.GUITexture = GUITexture) then
310 begin
311 Inc(TextureCached.References);
312 if LogRendererCache then
313 WritelnLog('++', 'TextureImage %s: %d', [TextureFullUrl, TextureCached.References]);
314 Exit(TextureCached.GLName);
315 end;
316 end;
317
318 { Initialize Result first, before calling TextureImageCaches.Add.
319 That's because in case LoadGLTexture raises exception,
320 we don't want to add texture to cache (because caller would have
321 no way to call TextureImage_DecReference later). }
322 Result := LoadGLTexture(TextureImage, Filter, TextureWrap, CompositeForMipmaps, GUITexture);
323
324 TexParameterMaxAnisotropy(GL_TEXTURE_2D, TextureAnisotropy);
325
326 TextureCached := TTextureImageCache.Create;
327 TextureImageCaches.Add(TextureCached);
328 TextureCached.FullUrl := TextureFullUrl;
329 TextureCached.FlipVertically := FlipVertically;
330 TextureCached.Filter := Filter;
331 TextureCached.Anisotropy := TextureAnisotropy;
332 TextureCached.Wrap := TextureWrap;
333 TextureCached.GUITexture := GUITexture;
334 TextureCached.References := 1;
335 TextureCached.GLName := Result;
336
337 if LogRendererCache then
338 WritelnLog('++', 'TextureImage %s: %d', [TextureFullUrl, 1]);
339 end;
340
341 procedure TRendererCache.TextureImage_DecReference(
342 const TextureGLName: TGLuint);
343 var
344 I: Integer;
345 begin
346 for I := 0 to TextureImageCaches.Count - 1 do
347 if TextureImageCaches[I].GLName = TextureGLName then
348 begin
349 Dec(TextureImageCaches[I].References);
350 if LogRendererCache then
351 WritelnLog('--', 'TextureImage %s: %d', [TextureImageCaches[I].FullUrl,
352 TextureImageCaches[I].References]);
353 if TextureImageCaches[I].References = 0 then
354 begin
355 glFreeTexture(TextureImageCaches[I].GLName);
356 TextureImageCaches.Delete(I);
357 end;
358 CheckFreeWhenEmpty;
359 Exit;
360 end;
361
362 raise EInternalError.CreateFmt(
363 'TRendererCache.TextureImage_DecReference: no reference ' +
364 'found to texture %d', [TextureGLName]);
365 end;
366
367 function TRendererCache.TextureVideo_IncReference(
368 const TextureVideo: TVideo;
369 const TextureFullUrl: String;
370 const FlipVertically: Boolean;
371 const Filter: TTextureFilter;
372 const TextureAnisotropy: TGLfloat;
373 const TextureWrap: TTextureWrap2D;
374 const GUITexture: boolean): TGLVideo3D;
375 var
376 I: Integer;
377 TextureCached: TTextureVideoCache;
378 begin
379 for I := 0 to TextureVideoCaches.Count - 1 do
380 begin
381 TextureCached := TextureVideoCaches[I];
382
383 if (TextureFullUrl <> '') and
384 (TextureCached.FullUrl = TextureFullUrl) and
385 (TextureCached.FlipVertically = FlipVertically) and
386 (TextureCached.Filter = Filter) and
387 (TextureCached.Anisotropy = TextureAnisotropy) and
388 (TextureCached.Wrap = TextureWrap) and
389 (TextureCached.GUITexture = GUITexture) then
390 begin
391 Inc(TextureCached.References);
392 if LogRendererCache then
393 WritelnLog('++', 'TextureVideo %s: %d', [TextureFullUrl, TextureCached.References]);
394 Exit(TextureCached.GLVideo);
395 end;
396 end;
397
398 { Initialize Result first, before calling TextureVideoCaches.Add.
399 That's because in case TGLVideo3D.Create raises exception,
400 we don't want to add texture to cache (because caller would have
401 no way to call TextureVideo_DecReference later). }
402 Result := TGLVideo3D.Create(TextureVideo, Filter, TextureAnisotropy, TextureWrap, GUITexture);
403
404 TextureCached := TTextureVideoCache.Create;
405 TextureVideoCaches.Add(TextureCached);
406 TextureCached.FullUrl := TextureFullUrl;
407 TextureCached.FlipVertically := FlipVertically;
408 TextureCached.Filter := Filter;
409 TextureCached.Anisotropy := TextureAnisotropy;
410 TextureCached.Wrap := TextureWrap;
411 TextureCached.GUITexture := GUITexture;
412 TextureCached.References := 1;
413 TextureCached.GLVideo := Result;
414
415 if LogRendererCache then
416 WritelnLog('++', 'TextureVideo %s: %d', [TextureFullUrl, 1]);
417 end;
418
419 procedure TRendererCache.TextureVideo_DecReference(
420 const TextureVideo: TGLVideo3D);
421 var
422 I: Integer;
423 begin
424 for I := 0 to TextureVideoCaches.Count - 1 do
425 if TextureVideoCaches[I].GLVideo = TextureVideo then
426 begin
427 Dec(TextureVideoCaches[I].References);
428 if LogRendererCache then
429 WritelnLog('--', 'TextureVideo %s: %d', [
430 TextureVideoCaches[I].FullUrl,
431 TextureVideoCaches[I].References
432 ]);
433 if TextureVideoCaches[I].References = 0 then
434 begin
435 FreeAndNil(TextureVideoCaches[I].GLVideo);
436 TextureVideoCaches.Delete(I);
437 end;
438 CheckFreeWhenEmpty;
439 Exit;
440 end;
441
442 raise EInternalError.CreateFmt(
443 'TRendererCache.TextureVideo_DecReference: no reference ' +
444 'found to texture %s', [PointerToStr(TextureVideo)]);
445 end;
446
447 function TRendererCache.TextureCubeMap_IncReference(
448 const TextureFullUrl: String;
449 const Filter: TTextureFilter;
450 const Anisotropy: TGLfloat;
451 const PositiveX, NegativeX,
452 PositiveY, NegativeY,
453 PositiveZ, NegativeZ: TEncodedImage;
454 const CompositeForMipmaps: TCompositeImage): TGLuint;
455 var
456 I: Integer;
457 TextureCached: TTextureCubeMapCache;
458 DisableMipmaps: Boolean;
459 begin
460 if TextureFullUrl <> '' then // never share texture with FullUrl = '', e.g. from GeneratedCubeMapTexture
461 for I := 0 to TextureCubeMapCaches.Count - 1 do
462 begin
463 TextureCached := TextureCubeMapCaches[I];
464
465 if (TextureCached.FullUrl = TextureFullUrl) and
466 (TextureCached.Filter = Filter) and
467 (TextureCached.Anisotropy = Anisotropy) then
468 begin
469 Inc(TextureCached.References);
470 if LogRendererCache then
471 WritelnLog('++', 'Cube map %s: %d', [
472 TextureFullUrl,
473 TextureCached.References
474 ]);
475 Exit(TextureCached.GLName);
476 end;
477 end;
478
479 glGenTextures(1, @Result);
480 glBindTexture(GL_TEXTURE_CUBE_MAP, Result);
481
482 SetTextureFilter(GL_TEXTURE_CUBE_MAP, Filter);
483 glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GLFeatures.CLAMP_TO_EDGE);
484 glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GLFeatures.CLAMP_TO_EDGE);
485
486 glTextureCubeMap(Result,
487 PositiveX, NegativeX,
488 PositiveY, NegativeY,
489 PositiveZ, NegativeZ,
490 CompositeForMipmaps,
491 Filter.NeedsMipmaps,
492 DisableMipmaps);
493
494 if DisableMipmaps then
495 begin
496 Filter.DisableMipmaps;
497 SetTextureFilter(GL_TEXTURE_CUBE_MAP, Filter);
498 end;
499
500 TexParameterMaxAnisotropy(GL_TEXTURE_CUBE_MAP, Anisotropy);
501
502 TextureCached := TTextureCubeMapCache.Create;
503 TextureCubeMapCaches.Add(TextureCached);
504 TextureCached.FullUrl := TextureFullUrl;
505 TextureCached.Filter := Filter;
506 TextureCached.Anisotropy := Anisotropy;
507 TextureCached.References := 1;
508 TextureCached.GLName := Result;
509
510 if LogRendererCache then
511 WritelnLog('++', 'Cube map %s: %d', [TextureFullUrl, 1]);
512 end;
513
514 procedure TRendererCache.TextureCubeMap_DecReference(
515 const TextureGLName: TGLuint);
516 var
517 I: Integer;
518 begin
519 for I := 0 to TextureCubeMapCaches.Count - 1 do
520 if TextureCubeMapCaches[I].GLName = TextureGLName then
521 begin
522 Dec(TextureCubeMapCaches[I].References);
523 if LogRendererCache then
524 WritelnLog('--', 'Cube map %s: %d', [
525 TextureCubeMapCaches[I].FullUrl,
526 TextureCubeMapCaches[I].References
527 ]);
528 if TextureCubeMapCaches[I].References = 0 then
529 begin
530 glFreeTexture(TextureCubeMapCaches[I].GLName);
531 TextureCubeMapCaches.Delete(I);
532 end;
533 CheckFreeWhenEmpty;
534 Exit;
535 end;
536
537 raise EInternalError.CreateFmt(
538 'TRendererCache.TextureCubeMap_DecReference: no reference ' +
539 'found to texture %d', [TextureGLName]);
540 end;
541
542 function TRendererCache.Texture3D_IncReference(
543 const TextureFullUrl: String;
544 const Filter: TTextureFilter;
545 const Anisotropy: TGLfloat;
546 const TextureWrap: TTextureWrap3D;
547 const Image: TEncodedImage;
548 const Composite: TCompositeImage): TGLuint;
549 var
550 I: Integer;
551 TextureCached: TTexture3DCache;
552 begin
553 for I := 0 to Texture3DCaches.Count - 1 do
554 begin
555 TextureCached := Texture3DCaches[I];
556
557 if (TextureFullUrl <> '') and
558 (TextureCached.FullUrl = TextureFullUrl) and
559 (TextureCached.Filter = Filter) and
560 (TextureCached.Anisotropy = Anisotropy) and
561 (TextureCached.Wrap = TextureWrap) then
562 begin
563 Inc(TextureCached.References);
564 if LogRendererCache then
565 WritelnLog('++', 'Texture3D %s: %d', [TextureFullUrl, TextureCached.References]);
566 Exit(TextureCached.GLName);
567 end;
568 end;
569
570 if not GLFeatures.Texture3D then
571 raise Exception.Create('3D textures not supported by OpenGL(ES)');
572
573 glGenTextures(1, @Result);
574 glBindTexture(GL_TEXTURE_3D, Result);
575
576 glTextureImage3d(Result, Image, Filter, Composite);
577
578 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, TextureWrap.Data[0]);
579 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, TextureWrap.Data[1]);
580 glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, TextureWrap.Data[2]);
581
582 TexParameterMaxAnisotropy(GL_TEXTURE_3D, Anisotropy);
583
584 TextureCached := TTexture3DCache.Create;
585 Texture3DCaches.Add(TextureCached);
586 TextureCached.FullUrl := TextureFullUrl;
587 TextureCached.Filter := Filter;
588 TextureCached.Anisotropy := Anisotropy;
589 TextureCached.Wrap := TextureWrap;
590 TextureCached.References := 1;
591 TextureCached.GLName := Result;
592
593 if LogRendererCache then
594 WritelnLog('++', 'Texture3D %s: %d', [TextureFullUrl, 1]);
595 end;
596
597 procedure TRendererCache.Texture3D_DecReference(
598 const TextureGLName: TGLuint);
599 var
600 I: Integer;
601 begin
602 for I := 0 to Texture3DCaches.Count - 1 do
603 if Texture3DCaches[I].GLName = TextureGLName then
604 begin
605 Dec(Texture3DCaches[I].References);
606 if LogRendererCache then
607 WritelnLog('--', 'Texture3D %s: %d', [
608 Texture3DCaches[I].FullUrl,
609 Texture3DCaches[I].References
610 ]);
611 if Texture3DCaches[I].References = 0 then
612 begin
613 glFreeTexture(Texture3DCaches[I].GLName);
614 Texture3DCaches.Delete(I);
615 end;
616 CheckFreeWhenEmpty;
617 Exit;
618 end;
619
620 raise EInternalError.CreateFmt(
621 'TRendererCache.Texture3D_DecReference: no reference ' +
622 'found to texture %d', [TextureGLName]);
623 end;
624
625 function TRendererCache.TextureDepth_IncReference(
626 const TextureFullUrl: String;
627 const TextureWrap: TTextureWrap2D;
628 const Width, Height: Cardinal): TGLuint;
629 var
630 I: Integer;
631 TextureCached: TTextureDepthOrFloatCache;
632 Filter: TTextureFilter;
633 ImageType: TGLenum;
634 ImageFormat: string;
635 ImageSize: Int64;
636 begin
637 for I := 0 to TextureDepthOrFloatCaches.Count - 1 do
638 begin
639 TextureCached := TextureDepthOrFloatCaches[I];
640
641 if (TextureFullUrl <> '') and
642 (TextureCached.FullUrl = TextureFullUrl) and
643 (TextureCached.Wrap = TextureWrap) then
644 begin
645 Inc(TextureCached.References);
646 if LogRendererCache then
647 WritelnLog('++', 'Depth texture %s: %d', [
648 TextureFullUrl,
649 TextureCached.References
650 ]);
651 Exit(TextureCached.GLName);
652 end;
653 end;
654
655 Assert(GLFeatures.TextureDepth);
656 Assert(GLFeatures.TextureDepthCompare);
657
658 glGenTextures(1, @Result);
659 glBindTexture(GL_TEXTURE_2D, Result);
660
661 Filter.Minification := minLinear;
662 Filter.Magnification := magLinear;
663 SetTextureFilter(GL_TEXTURE_2D, Filter);
664 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, TextureWrap.Data[0]);
665 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, TextureWrap.Data[1]);
666
667 { OpenGLES allows only GL_UNSIGNED_SHORT or GL_UNSIGNED_INT for depth textures.
668 This was true for OES_depth_texture, looks like it is true for OpenGLES 3.0 core too,
669 based on "OpenGL ES 3.2 NVIDIA 515.86.01". }
670 ImageType := {$ifdef OpenGLES} GL_UNSIGNED_SHORT {$else} GL_UNSIGNED_BYTE {$endif};
671 ImageFormat := {$ifdef OpenGLES} 'depth-short' {$else} 'depth-byte' {$endif};
672 ImageSize := {$ifdef OpenGLES} SizeOf(TGLushort) {$else} SizeOf(TGLbyte) {$endif}
673 * Width * Height;
674
675 { Do not init any texture image. Just initialize texture sizes
676 and both internal and external formats to GL_DEPTH_COMPONENT_ARB
677 (will match depth buffer precision). }
678 glTexImage2d(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
679 Width, Height, 0, GL_DEPTH_COMPONENT, ImageType, nil);
680 TextureMemoryProfiler.Allocate(Result, '', ImageFormat, ImageSize, false,
681 Width, Height, 1);
682
683 if GLFeatures.TextureDepthCompare then
684 begin
685 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
686 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
687 end else
688 WritelnWarning('VRML/X3D', 'OpenGL doesn''t support GL_ARB_shadow, we cannot set depth comparison for depth texture');
689
690 TextureCached := TTextureDepthOrFloatCache.Create;
691 TextureDepthOrFloatCaches.Add(TextureCached);
692 TextureCached.FullUrl := TextureFullUrl;
693 TextureCached.References := 1;
694 TextureCached.Wrap := TextureWrap;
695 TextureCached.GLName := Result;
696
697 if LogRendererCache then
698 WritelnLog('++', 'Depth texture %s: %d', [TextureFullUrl, 1]);
699 end;
700
701 procedure TRendererCache.TextureDepth_DecReference(
702 const TextureGLName: TGLuint);
703 var
704 I: Integer;
705 begin
706 for I := 0 to TextureDepthOrFloatCaches.Count - 1 do
707 if TextureDepthOrFloatCaches[I].GLName = TextureGLName then
708 begin
709 Dec(TextureDepthOrFloatCaches[I].References);
710 if LogRendererCache then
711 WritelnLog('--', 'Depth texture %s: %d', [
712 TextureDepthOrFloatCaches[I].FullUrl,
713 TextureDepthOrFloatCaches[I].References
714 ]);
715 if TextureDepthOrFloatCaches[I].References = 0 then
716 begin
717 glFreeTexture(TextureDepthOrFloatCaches[I].GLName);
718 TextureDepthOrFloatCaches.Delete(I);
719 end;
720 CheckFreeWhenEmpty;
721 Exit;
722 end;
723
724 raise EInternalError.CreateFmt(
725 'TRendererCache.TextureDepth_DecReference: no reference ' +
726 'found to texture %d', [TextureGLName]);
727 end;
728
729 function TRendererCache.TextureFloat_IncReference(
730 const TextureFullUrl: String;
731 const Filter: TTextureFilter;
732 const TextureWrap: TTextureWrap2D;
733 const Width, Height: Cardinal;
734 const Precision32: boolean): TGLuint;
735 {$ifndef OpenGLES}
736 var
737 I: Integer;
738 TextureCached: TTextureDepthOrFloatCache;
739 InternalFormat: TGLenum;
740 begin
741 for I := 0 to TextureDepthOrFloatCaches.Count - 1 do
742 begin
743 TextureCached := TextureDepthOrFloatCaches[I];
744
745 if (TextureFullUrl <> '') and
746 (TextureCached.FullUrl = TextureFullUrl) and
747 (TextureCached.Wrap = TextureWrap) then
748 begin
749 Inc(TextureCached.References);
750 if LogRendererCache then
751 WritelnLog('++', 'Float texture %s: %d', [TextureFullUrl, TextureCached.References]);
752 Exit(TextureCached.GLName);
753 end;
754 end;
755
756 glGenTextures(1, @Result);
757 glBindTexture(GL_TEXTURE_2D, Result);
758 SetTextureFilter(GL_TEXTURE_2D, Filter);
759 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, TextureWrap.Data[0]);
760 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, TextureWrap.Data[1]);
761
762 if Precision32 then
763 InternalFormat := GL_RGB32F_ARB { same thing as GL_RGB_FLOAT32_ATI } else
764 InternalFormat := GL_RGB16F_ARB { same thing as GL_RGB_FLOAT16_ATI };
765
766 { Do not init any texture image. Just initialize texture sizes and formats. }
767 glTexImage2d(GL_TEXTURE_2D, 0, InternalFormat,
768 Width, Height, 0, GL_RGB, GL_FLOAT, nil);
769 TextureMemoryProfiler.Allocate(Result, '', 'rgb-float',
770 3 * SizeOf(TGLfloat) * Width * Height, false, Width, Height, 1);
771
772 TextureCached := TTextureDepthOrFloatCache.Create;
773 TextureDepthOrFloatCaches.Add(TextureCached);
774 TextureCached.FullUrl := TextureFullUrl;
775 TextureCached.References := 1;
776 TextureCached.Wrap := TextureWrap;
777 TextureCached.GLName := Result;
778 { Hm, we probably should store Filter, Precision32
779 inside TextureCached as well... Ignore this, useless for now ---
780 one Node will require only one float texture anyway. }
781
782 if LogRendererCache then
783 WritelnLog('++', 'Float texture %s: %d', [TextureFullUrl, 1]);
784 {$else}
785 begin
786 raise Exception.Create('Float textures not available on OpenGL ES 2.0');
787 Result := 0; // silence warning
788 {$endif}
789 end;
790
791 procedure TRendererCache.TextureFloat_DecReference(
792 const TextureGLName: TGLuint);
793 var
794 I: Integer;
795 begin
796 for I := 0 to TextureDepthOrFloatCaches.Count - 1 do
797 if TextureDepthOrFloatCaches[I].GLName = TextureGLName then
798 begin
799 Dec(TextureDepthOrFloatCaches[I].References);
800 if LogRendererCache then
801 WritelnLog('--', 'Float texture %s: %d', [
802 TextureDepthOrFloatCaches[I].FullUrl,
803 TextureDepthOrFloatCaches[I].References
804 ]);
805 if TextureDepthOrFloatCaches[I].References = 0 then
806 begin
807 glFreeTexture(TextureDepthOrFloatCaches[I].GLName);
808 TextureDepthOrFloatCaches.Delete(I);
809 end;
810 CheckFreeWhenEmpty;
811 Exit;
812 end;
813
814 raise EInternalError.CreateFmt(
815 'TRendererCache.TextureFloat_DecReference: no reference ' +
816 'found to texture %d', [TextureGLName]);
817 end;
818
819 function TRendererCache.Shape_IncReference(
820 const Shape: TX3DRendererShape;
821 const RenderOptions: TCastleRenderOptions): TShapeCache;
822 var
823 FogEnabled, FogVolumetric: boolean;
824 FogVolumetricDirection: TVector3;
825 FogVolumetricVisibilityStart: Single;
826
827 function IgnoreStateTransform: boolean;
828 begin
829 if { Force CacheIgnoresTransform to be false if our shape uses shaders.
830 Shaders may depend on coordinates in eye space, which obviously
831 may be different for shapes that differ even only on transform. }
832 (Shape.Node <> nil) and
833 (Shape.Node.Appearance <> nil) and
834 (Shape.Node.Appearance.FdShaders.Count <> 0) then
835 Exit(false);
836
837 { If we use any features that (may) render shape differently
838 if shape's transform (or other stuff handled outside arrays
839 and castlerenderer) changes, then Result must be false. }
840 Result := not FogVolumetric;
841 end;
842
843 function FogVolumetricEqual(
844 const Volumetric1: boolean;
845 const VolumetricDirection1: TVector3;
846 const VolumetricVisibilityStart1: Single;
847 const Volumetric2: boolean;
848 const VolumetricDirection2: TVector3;
849 const VolumetricVisibilityStart2: Single): boolean;
850 begin
851 Result := (Volumetric1 = Volumetric2) and
852 ( (not Volumetric1) or
853 ( TVector3.PerfectlyEquals(VolumetricDirection1, VolumetricDirection2) and
854 (VolumetricVisibilityStart1 = VolumetricVisibilityStart2) ) );
855 end;
856
857 var
858 I: Integer;
859 DisableSharedCache: Boolean;
860 Caches: TShapeCacheList;
861 begin
862 TRenderer.GetFog(Shape.Fog, RenderOptions, FogEnabled, FogVolumetric,
863 FogVolumetricDirection, FogVolumetricVisibilityStart);
864
865 DisableSharedCache := TGLShape(Shape).DisableSharedCache;
866 Caches := ShapeCaches[DisableSharedCache];
867
868 if not DisableSharedCache then
869 for I := 0 to Caches.Count - 1 do
870 begin
871 Result := Caches[I];
872 if (Result.Geometry = Shape.Geometry) and
873 Result.RenderOptions.EqualForShapeCache(RenderOptions) and
874 Result.State.Equals(Shape.State, IgnoreStateTransform) and
875 FogVolumetricEqual(
876 Result.FogVolumetric,
877 Result.FogVolumetricDirection,
878 Result.FogVolumetricVisibilityStart,
879 FogVolumetric,
880 FogVolumetricDirection,
881 FogVolumetricVisibilityStart) then
882 begin
883 Inc(Result.References);
884 if LogRendererCache then
885 WritelnLog('++', Result.ToString);
886 Exit(Result);
887 end;
888 end;
889
890 { not found, so create new }
891
892 Result := TShapeCache.Create;
893 Caches.Add(Result);
894 Result.RenderOptions := RenderOptions;
895 Result.Geometry := Shape.Geometry;
896 Result.State := Shape.State;
897 Result.FogVolumetric := FogVolumetric;
898 Result.FogVolumetricDirection := FogVolumetricDirection;
899 Result.FogVolumetricVisibilityStart := FogVolumetricVisibilityStart;
900 Result.References := 1;
901
902 if LogRendererCache then
903 WritelnLog('++', Result.ToString);
904 end;
905
906 procedure TRendererCache.Shape_DecReference(const Shape: TX3DRendererShape;
907 var ShapeCache: TShapeCache);
908 var
909 I: Integer;
910 DisableSharedCache: Boolean;
911 Caches: TShapeCacheList;
912 begin
913 DisableSharedCache := TGLShape(Shape).DisableSharedCache;
914 Caches := ShapeCaches[DisableSharedCache];
915 I := Caches.IndexOf(ShapeCache);
916
917 if I <> -1 then
918 begin
919 Dec(ShapeCache.References);
920 if LogRendererCache then
921 WritelnLog('--', ShapeCache.ToString);
922 if ShapeCache.References = 0 then
923 Caches.Delete(I);
924 ShapeCache := nil;
925 CheckFreeWhenEmpty;
926 end else
927 raise EInternalError.Create(
928 'TRendererCache.Shape_DecReference: no reference found');
929 end;
930
931 function TRendererCache.Program_IncReference(
932 Shader: TShader; const ShapeNiceName: string): TShaderProgramCache;
933 var
934 I: Integer;
935 begin
936 for I := 0 to ProgramCaches.Count - 1 do
937 begin
938 Result := ProgramCaches[I];
939 if Result.Hash = Shader.CodeHash then
940 begin
941 Inc(Result.References);
942 if LogRendererCache then
943 WritelnLog('++', 'Shader program (hash %s): %d', [Result.Hash.ToString, Result.References]);
944 Exit(Result);
945 end;
946 end;
947
948 Result := TShaderProgramCache.Create;
949 ProgramCaches.Add(Result);
950 Result.References := 1;
951 Result.Hash := Shader.CodeHash;
952
953 try
954 Result.ShaderProgram := TX3DGLSLProgram.Create;
955 Shader.LinkProgram(Result.ShaderProgram, ShapeNiceName);
956 except on E: EGLSLError do
957 begin
958 FreeAndNil(Result.ShaderProgram);
959 { Note: leave Result assigned and Result.Hash set,
960 to avoid reinitializing this shader next time. }
961 WritelnWarning('VRML/X3D', Format('Cannot use GLSL shader for shape "%s": %s',
962 [ShapeNiceName, E.Message]));
963 end;
964 end;
965
966 { We *must* have some GLSL shader when GLFeatures.EnableFixedFunction = false }
967 if (not GLFeatures.EnableFixedFunction) and (Result.ShaderProgram = nil) then
968 begin
969 try
970 Result.ShaderProgram := TX3DGLSLProgram.Create;
971 Shader.LinkFallbackProgram(Result.ShaderProgram);
972 except on E: EGLSLError do
973 begin
974 { We try to behave nicely when LinkFallbackProgram fails, although in practice
975 Android's OpenGLES implementation may just crash... }
976 FreeAndNil(Result.ShaderProgram);
977 WritelnWarning('VRML/X3D', Format('Cannot use even fallback GLSL shader for shape "%s": %s',
978 [ShapeNiceName, E.Message]));
979 end;
980 end;
981 end;
982
983 if LogRendererCache then
984 WritelnLog('++', 'Shader program (hash %s): %d', [Result.Hash.ToString, Result.References]);
985 end;
986
987 procedure TRendererCache.Program_DecReference(var ProgramCache: TShaderProgramCache);
988 var
989 I: Integer;
990 begin
991 for I := 0 to ProgramCaches.Count - 1 do
992 begin
993 if ProgramCaches[I] = ProgramCache then
994 begin
995 Dec(ProgramCache.References);
996 if LogRendererCache then
997 WritelnLog('--', 'Shader program (hash %s): %d', [ProgramCache.Hash.ToString, ProgramCache.References]);
998 if ProgramCache.References = 0 then
999 ProgramCaches.Delete(I);
1000 ProgramCache := nil;
1001 CheckFreeWhenEmpty;
1002 Exit;
1003 end;
1004 end;
1005
1006 raise EInternalError.Create(
1007 'TRendererCache.Program_DecReference: no reference found');
1008 end;
1009
1010 function TRendererCache.Empty: Boolean;
1011 begin
1012 Result :=
1013 (TextureImageCaches.Count = 0) and
1014 (TextureVideoCaches.Count = 0) and
1015 (TextureCubeMapCaches.Count = 0) and
1016 (Texture3DCaches.Count = 0) and
1017 (TextureDepthOrFloatCaches.Count = 0) and
1018 (ShapeCaches[false].Count = 0) and
1019 (ShapeCaches[true].Count = 0) and
1020 (ProgramCaches.Count = 0);
1021 end;
1022
1023 procedure TRendererCache.CheckFreeWhenEmpty;
1024 begin
1025 if FFreeWhenEmpty and Empty then
1026 begin
1027 FFreeWhenEmptyInstanceToNil^ := nil; // sets global RendererCache to nil
1028 Self.Destroy;
1029 end;
1030 end;
1031
1032 procedure TRendererCache.FreeWhenEmpty(const InstanceToNil: PObject);
1033 begin
1034 if Self <> nil then // hack to allow calling on nil instance, like standard Free
1035 begin
1036 FFreeWhenEmptyInstanceToNil := InstanceToNil;
1037 FFreeWhenEmpty := true;
1038 CheckFreeWhenEmpty;
1039 end;
1040 end;
1041
1042 {$endif}