PreCaching Textures

I know - use dummy x3dv for models… Problem is I wanna do this with downloaded textures I’m not going to store - basically use on-demand then discard at some point so I had a play with a local model trying to cache its textures using the code below…

Basicaly I create a texturenode, load an image, apply everything that’s in the model (Flipped in this case) and set IsTextureLoaded which is supposed to stick it in the cache.

It appears that the texture isn’t being cached though as Scene.PrepareResources appears to load it again.

Tracing through debug I can see it getting to DoLoadTexture (then debugger goes wonky)

Later, when doing PrepareResources it hits TextureImage_IncReference and caches the image

var 
  imgCache: Array[0..4] of TPixelTextureNode;

const
  hallImages: Array[0..4] of String = (...);

procedure TCastleApp.preCacheImages;
var
  i: Integer;
  Texture: TCastleImage;
begin
  SetLength(imgCache, Length(hallImages));
  for i:= 0 to Length(hallImages) - 1 do
    begin
      Texture := LoadImage(hallImages[i], [TRGBImage]) as TCastleImage;
      Texture.FlipVertical;
      imgCache[i] := TPixelTextureNode.Create;
      imgCache[i].FdImage.Value := Texture;
      imgCache[i].IsTextureLoaded := True;
      if imgCache[i].IsTextureImage then
        WriteLnLog('Cached Image ' + hallImages[i])
      else
        WriteLnLog('Failed to cache Image ' + hallImages[i])
    end;
end;

You load texture to TPixelTextureNode instance. This is not a way to cache textures. Each scene will need a different TPixelTextureNode instance, and they do not share texture data (they are different TPixelTextureNode instances, and they do not know to share images – every one could have a different contents in TCastleImage).

Also, LoadImage doesn’t cache textures.

As mentioned on Discord, the way to cache textures is

  • TCastleImagePersistent (for images used in UI)

  • make a dummy scene referencing them (for textures used in scenes).

In the latter case, you need to use TImageTextureNode which will allow the cache to recognize it’s the same image because it has the same URL. TImageTextureNode relies on the fact that it just loads images from URLs, and all loading parameters (that may affect caching, like whether to flip and what is OpenGL filtering) are known by TImageTextureNode .