HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
RV_TextureCache.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: RV_TextureCache.h (RV Library, C++)
7  *
8  * COMMENTS:
9  */
10 #ifndef RV_TextureCache_h
11 #define RV_TextureCache_h
12 
13 #include "RV_API.h"
14 #include "RV_TextureRef.h"
15 #include "RV_Type.h"
16 #include "RV_TypePtrs.h"
17 
18 #include <PXL/PXL_Raster.h>
19 #include <UT/UT_Array.h>
20 #include <UT/UT_Cache.h>
21 #include <UT/UT_NonCopyable.h>
22 #include <UT/UT_Map.h>
23 #include <UT/UT_MemoryResource.h>
24 #include <UT/UT_Set.h>
25 #include <UT/UT_StringMap.h>
26 #include <UT/UT_StringHolder.h>
27 #include <UT/UT_UniquePtr.h>
28 #include <UT/UT_VectorTypes.h>
29 
30 #include <SYS/SYS_Types.h>
31 
32 #define RV_INVALID_OP_ID -1
33 
34 typedef void (*RV_TextureHDAResolverCB)(const char *optable_optype,
35  const char *pattern,
36  UT_StringArray &files);
37 
38 class RV_Render;
40 class RV_TextureResolver;
41 class RV_Instance;
42 class RV_VKImage;
43 
44 class PXL_Raster;
45 class IMG_Stat;
46 
47 /// Global cache of vulkan textures sourced from files.
49 {
50 public:
51  /// Initialize the cache (only used by the system during startup)
52  static void init(const UT_StringHolder &device_name);
53  /// Destroy the cache (only used by the system during exit)
54  static void cleanup();
55 
56  /// Clear all images out of the cache.
57  static void clear();
58  /// Mark any textures as dirty if their file source has been modified
59  static void updateTextures();
60 
61  /// The serial version of the cache. Incremented when a texture is added
62  static exint cacheVersion();
63  /// The serial refresh count of the cache. Incremented when the user
64  /// explicity updates the textures
65  static exint cacheRefresh();
66 
67  static exint currentSizeBytes();
68 
69  static exint totalTextureCount();
70 
71  static exint maxSizeBytes();
72 
73  static exint freeSomeMem(exint mem_in_bytes);
74 
75  /// If the texture is missing, one of these generic placeholders is used.
77  {
78  MISSING_BLACK_CLEAR, // 0,0,0,0
79  MISSING_BLACK_SOLID, // 0,0,0,1
80  MISSING_WHITE_SOLID, // 1,1,1,1
81  MISSING_RED_SOLID, // 1,0,0,1
82  MISSING_NORMAL_MAP, // 0.5, 0.5, 1, 0
83  MISSING_FALLBACK, // custom color
84 
85  MAX_PLACEHOLDER
86  };
87 
89  {
94  PRIORITY_CRITICAL
95  };
96 
97  /// Load the map (if needed) and bind the resulting texture to 'sampler_name'
98  /// in 'set'. If it cannot be loaded, bind a placeholder texture instead.
99  /// This method is equivalent to calling loadTextureRef() and then
100  /// bindTextureRef() or bindPlaceholder(). If the map is a reference to a
101  /// mofr with op:, op_id will contain its unique ID.
102  static bool bindTexture(RV_Render *r,
103  RV_TextureRef &map,
104  const RV_TextureParms &map_parms,
105  const UT_StringHolder &map_name,
106  const UT_StringHolder &relative_to_node,
107  RV_ImageDim tex_type,
109  const UT_StringHolder &sampler_name,
110  bool deferred_load,
111  bool &deferred_loaded,
112  int &op_id,
113  TexturePriority priority = PRIORITY_NORMAL,
114  PlaceholderType missing=MISSING_WHITE_SOLID,
115  UT_Vector4F *fallback_color = nullptr);
116 
117  /// Binds an existing texture ref to the set at 'sampler_name'. It should not
118  /// be a placeholder image (use bindPlaceholder instead).
119  static bool bindTextureRef(RV_Render *r,
122  const UT_StringHolder &sampler_name);
123 
124  /// Bind a small placeholder texture (1x1) to 'sampler_name' in 'set'.
125  /// The RGBA texture color is defined by the placeholder_type, or can be a
126  /// custom/ color if the type is FALLBACK. The texture is 8b unorm RGBA.
127  static bool bindPlaceholder(RV_Render *r,
128  RV_ImageDim tex_type,
130  const UT_StringHolder &sampler_name,
131  PlaceholderType placeholder_type,
132  const UT_Vector4F *fallbackcolor=nullptr);
133 
134  /// Load the map info a texture ref without binding it to a shader. If the
135  /// map could not be loaded, map.isPlaceholder() will be true.
136  /// If allow_deferred_load is true, background load the texture. Keep calling
137  /// this in subsequent redraws until defer_load_finished is true.
138  static bool loadTextureRef(RV_Render *r,
139  RV_TextureRef &map,
140  const RV_TextureParms &map_parms,
141  const UT_StringHolder &map_name,
142  const UT_StringHolder &relative_to_node,
143  RV_ImageDim tex_type,
144  bool allow_deferred_load,
145  bool &defer_load_finished,
146  int &op_id,
147  TexturePriority priority = PRIORITY_NORMAL,
148  UT_Vector3i *resolution = nullptr,
149  UT_Vector4F *fallback_color = nullptr);
150 
151  /// Cache an existing 2D Image. The name should be prefixed with exp:
152  /// (explicitly cached).
153  static bool cacheAsTexture(RV_Render *r,
154  RV_TextureRef &map,
155  const PXL_Raster *source_image,
156  const RV_TextureParms &map_parms,
157  const UT_StringHolder &map_name);
158  /// Remove a cached 2D Image
159  static bool removeCachedTexture(RV_TextureRef &map);
160 
161  /// Cache an existing image. The cache takes ownership (use std::move for
162  /// the image). If the image is a UDIM, you can optionally pass the bounds.
163  /// The map name should be prefixed with exp: (explicitly cached).
164  static bool cacheImage(UT_UniquePtr<RV_VKImage> image,
165  RV_TextureRef &map,
166  const UT_StringHolder &map_name,
167  UT_DimRect *udim_bounds = nullptr);
168  /// Remove a cached image from the cache, taking ownership of it.
169  /// If udim_bounds is not null, write the bounds to it.
171  uncacheImage(RV_TextureRef &map,
172  UT_DimRect *udim_bounds = nullptr);
173 
174 
175  /// Check if the texture is out of date. Flag the ref and set `dirty` if so.
176  /// doesn't touch either if it's current.
177  static void checkTextureDirty(RV_TextureRef &map, bool &dirty);
178 
179  /// Check if the texture has an alpha channel
180  static void checkTextureHasAlpha(const RV_TextureRef &ref, bool &has_alpha);
181 
182  /// For resolving a bunch of files to a 2D array, this is the separator
183  /// character between the filenames.
184  static const char * getFileSeparator() { return "\x1f"; }
185 
186  static void setSingleTexMemLimitMB(exint mem_in_mb);
187  static exint singleTexMemLimitMB();
188 
189  static void setCacheSize(exint mem_in_bytes);
190 
191  /// Reduce all textures in the cache by at least this amount.
192  static void setReductionFactor(fpreal reduce);
193 
194  /// For resolving
195  static void installHDACallback(RV_TextureHDAResolverCB resolver_func);
196 
197  /// @internal
199  {
200  public:
201  ImageInfo();
202  ~ImageInfo();
203 
211  int udim_x = 0;
212  int udim_y = 0;
213  int udim_w = 0;
214  int udim_h = 0;
215  int width = 1;
216  int height = 1;
217  int depth = 1;
218  fpreal aspect = 1.0;
219  bool check_alpha = false;
220  bool alpha = false;
221  int channels = 4;
222  int typeinfo = 0;
223  time_t modtime = 0;
224  fpreal optime = 0.0;
225  int op_id = RV_INVALID_OP_ID;
226  int version = 0;
227  bool valid = false;
228  bool loading = false;
229  fpreal downscale = 1.0;
230  };
231 
232 protected:
233  class Image
234  {
235  public:
236  RV_VKImage *image = nullptr;
237  int udim_x = 0;
238  int udim_y = 0;
239  int udim_w = 0;
240  int udim_h = 0;
241  fpreal aspect = 1.0;
242  int op_id = RV_INVALID_OP_ID;
243  };
244 
245  static RV_TextureCache::Image getTexture(exint id);
246 
247  exint resolveTexture(RV_Render *r,
248  const UT_StringHolder &map_name,
249  const UT_StringHolder &relative_to_node,
250  const RV_TextureParms &tex_parms,
251  RV_ImageDim tex_type,
252  bool force_update,
253  bool deferred_load,
254  bool &defer_loaded,
255  int &op_id,
256  bool &missing_texture,
258  TexturePriority priority,
259  const UT_Vector4F &fallback,
261 
262  static RV_VKImage *getPlaceholder(RV_Render *r, RV_ImageDim tex_type,
263  PlaceholderType type =MISSING_WHITE_SOLID,
264  const UT_Vector4F *fallbackcolor =nullptr);
265 
266  RV_TextureCache::Image privGetTexture(exint id);
267 
269  ~RV_TextureCache() override;
270 
272 
273  // UT_Cache interface
274  const char *utGetCacheName() const override
275  { return "Vulkan Texture Cache"; }
276  int64 utGetCurrentSize() const override
277  { return myCurrentSize; }
278  int64 utReduceCacheSizeBy(int64 amount) override
279  { return freeTextures(amount, true, false); }
280  bool utHasMaxSize() const override { return true; }
281  int64 utGetMaxSize() const override;
282  void utSetMaxSize(int64) override { }
283 
284 
285 private:
286 
287  exint freeTextures(exint needed_to_free, bool free_used, bool must_free);
288  exint cachedSizeBytes() const;
289 
290  class GraphicsMemoryClient : public UT_MemoryClient
291  {
292  public:
293  GraphicsMemoryClient(RV_TextureCache &cache) : myCache(cache) {}
294 
295  const char *name() const override
296  { return "Vulkan Texture Cache";}
297 
298  bool freeMemoryRequest(const UT_MemoryResource *resource,
299  RequestSeverity severity,
300  Niceness nice_level,
301  exint size_in_bytes,
302  exint &freed_amount_in_bytes) override;
303  bool memoryUse(const UT_MemoryResource *resource,
304  exint &in_use_bytes,
305  exint &cached_bytes) override;
306 
307  ~GraphicsMemoryClient() override {}
308  UT_NON_COPYABLE(GraphicsMemoryClient)
309 
310  private:
311  RV_TextureCache &myCache;
312  };
313 
314  GraphicsMemoryClient myResource;
315  UT_Array< UT_Map<exint, ImageInfo > > myImages;
316  UT_Map<exint, RV_ImageDim> myTypeMap;
317 
318  struct ResolveEntry
319  {
320  exint id = 0;
321  TexturePriority priority = RV_TextureCache::PRIORITY_NORMAL;
323 
324  ResolveEntry() {}
325  ResolveEntry(exint id,
326  TexturePriority priority,
328  : id{id}, priority{priority}, refs{refs}
329  {}
330 
331  /// Track if the texture is currently in use, these will
332  /// not be freed until the in use returns to zero.
333  /// set and clear MUST be paired.
334  bool isInUse() const
335  { return myInUseCount > 0; }
336  void setInUse()
337  { ++myInUseCount; }
338  void clearInUse()
339  { --myInUseCount; UT_ASSERT(myInUseCount >= 0); }
340  private:
341  int myInUseCount = 0;
342  };
343  UT_StringMap<ResolveEntry> myResolveMap;
344  UT_StringMap<fpreal> myReductionTable;
345 
347  UT_Array<UT_UniquePtr<RV_VKImage>> myPlaceholders;
348  UT_Array<UT_Map<int32, RV_VKImagePtr>> myFallbackTextures;
349  UT_Lock myLock;
350  UT_Set<exint> myDeferImages;
351 
352  exint myCurrentSize = 0;
353  fpreal myReductionFactor = 1.0;
354  UT_StringHolder myDeviceName;
355 };
356 
357 #endif
A collection of Vulkan UBO, SSBO, and Image shader bindings (descriptor set)
int64 utGetCurrentSize() const override
required - return the current cache size, in bytes
Unsorted map container.
Definition: UT_Map.h:114
void
Definition: png.h:1083
int64 exint
Definition: SYS_Types.h:125
Opaque reference to a texture stored in the RV_TextureCache.
Definition: RV_TextureRef.h:21
GLenum GLenum GLsizei void * image
Definition: glad.h:5132
UT_SharedPtr< RV_TextureRef::CacheData > refs
bool utHasMaxSize() const override
optional - override if the cache has a well defined maximum size
std::unique_ptr< T, Deleter > UT_UniquePtr
A smart pointer for unique ownership of dynamically allocated objects.
Definition: UT_UniquePtr.h:39
GLint GLsizei GLsizei height
Definition: glcorearb.h:103
GLint GLint GLsizei GLint GLenum GLenum type
Definition: glcorearb.h:108
GLint ref
Definition: glcorearb.h:124
std::shared_ptr< T > UT_SharedPtr
Wrapper around std::shared_ptr.
Definition: UT_SharedPtr.h:36
constexpr auto set(type rhs) -> int
Definition: core.h:610
T reduce(RangeT range, const T &identity, const FuncT &func, const JoinT &join)
Definition: Reduce.h:42
UT_Array< UT_UniquePtr< PXL_Raster > > rasters
#define RV_INVALID_OP_ID
#define UT_NON_COPYABLE(CLASS)
Define deleted copy constructor and assignment operator inside a class.
#define RV_API
Definition: RV_API.h:10
long long int64
Definition: SYS_Types.h:116
GLfloat GLfloat GLfloat alpha
Definition: glcorearb.h:112
GLenum GLenum severity
Definition: glcorearb.h:2539
void utSetMaxSize(int64) override
UT_UniquePtr< IMG_Stat > stat
HUSD_API const char * resolution()
GLuint const GLchar * name
Definition: glcorearb.h:786
GLushort pattern
Definition: glad.h:2583
PlaceholderType
If the texture is missing, one of these generic placeholders is used.
Handle to the main interface of Vulkan.
Definition: RV_Instance.h:48
Common base class for various caches.
Definition: UT_Cache.h:21
static const char * getFileSeparator()
FS_API bool cleanup(UT_StringArray &removed, UT_StringArray &error_files, exint &memory_freed, bool dry_run, const char *override_path=nullptr)
GLint GLint GLsizei GLsizei GLsizei depth
Definition: glcorearb.h:476
GT_API const UT_StringHolder version
Global cache of vulkan textures sourced from files.
fpreal64 fpreal
Definition: SYS_Types.h:283
Contains the details of a specific image file, used by IMG_File. This class contains all the high-lev...
Definition: IMG_Stat.h:38
GLint GLsizei width
Definition: glcorearb.h:103
#define UT_ASSERT(ZZ)
Definition: UT_Assert.h:165
Wrapper for a client of a limit memory resource.
GLboolean r
Definition: glcorearb.h:1222
void(* RV_TextureHDAResolverCB)(const char *optable_optype, const char *pattern, UT_StringArray &files)
RV_ImageDim
Definition: RV_Type.h:120
int64 utReduceCacheSizeBy(int64 amount) override
UT_UniquePtr< RV_VKImage > image
ImageBuf OIIO_API channels(const ImageBuf &src, int nchannels, cspan< int > channelorder, cspan< float > channelvalues={}, cspan< std::string > newchannelnames={}, bool shuffle_channel_names=false, int nthreads=0)