\chapter{Cached Images}
\label{chap:imagecache}
\index{Image Cache|(}

\section{Image Cache Introduction and Theory of Operation}
\label{sec:imagecache:intro}

\ImageCache is a utility class that allows an application to read pixels
from a large number of image files while using a remarkably small amount
of memory and other resources.  Of course it is possible for an
application to do this directly using \ImageInput objects.  But
\ImageCache offers the following advantages:

\begin{itemize}
\item \ImageCache presents an even simpler user interface than
  \ImageInput --- the only supported operations are asking for an
  \ImageSpec describing a subimage in the file, retrieving for a block
  of pixels, and locking/reading/releasing individual tiles.  You refer
  to images by filename only; you don't need to keep track of individual
  file handles or \ImageInput objects.  You don't need to explicitly
  open or close files.

\item The \ImageCache is completely thread-safe; if multiple threads
  are accessing the same file, the \ImageCache internals will handle
  all the locking and resource sharing.

\item No matter how many image files you are accessing, the \ImageCache
  will maintain a reasonable number of simultaneously-open files,
  automatically closing files that have not been needed recently.

\item No matter how large the total pixels in all the image files you
  are dealing with are, the \ImageCache will use only a small amount of
  memory.  It does this by loading only the individual tiles requested,
  and as memory allotments are approached, automatically releasing the
  memory from tiles that have not been used recently.
\end{itemize}

In short, if you have an application that will need to read pixels from
many large image files, you can rely on \ImageCache to manage all the
resources for you.  It is reasonable to access thousands of image files
totalling hundreds of GB of pixels, efficiently and using a memory
footprint on the order of 50 MB.

\newpage
Below are some simple code fragments that shows \ImageCache in action:
\medskip

\begin{code}
    #include <OpenImageIO/imagecache.h>
    using namespace OIIO;

    // Create an image cache and set some options
    ImageCache *cache = ImageCache::create ();
    cache->attribute ("max_memory_MB", 500.0);
    cache->attribute ("autotile", 64);

    // Get a block of pixels from a file.
    // (for brevity of this example, let's assume that 'size' is the
    // number of channels times the number of pixels in the requested region)
    float pixels[size];
    cache->get_pixels ("file1.jpg", 0, 0, xbegin, xend, ybegin, yend,
                       zbegin, zend, TypeDesc::FLOAT, pixels);

    // Get information about a file
    ImageSpec spec;
    bool ok = cache->get_imagespec ("file2.exr", spec);
    if (ok)
        std::cout << "resolution is " << spec.width << "x" 
                  << "spec.height << "\n";

    // Request and hold a tile, do some work with its pixels, then release
    ImageCache::Tile *tile;
    tile = cache->get_tile ("file2.exr", 0, 0, x, y, z);
    // The tile won't be freed until we release it, so this is safe:
    TypeDesc format;
    void *p = cache->tile_pixels (tile, format);
    // Now p points to the raw pixels of the tile, whose data format
    // is given by 'format'.
    cache->release_tile (tile);  
    // Now cache is permitted to free the tile when needed

    // Note that all files were referenced by name, we never had to open
    // or close any files, and all the resource and memory management 
    // was automatic.

    ImageCache::destroy (cache);
\end{code}

\newpage
\section{ImageCache API}
\label{sec:imagecache:api}

\subsection{Creating and destroying an image cache}
\label{sec:imagecache:api:createdestroy}

\ImageCache is an abstract API described as a pure virtual class.  The
actual internal implementation is not exposed through the external API
of \product.  Because of this, you cannot construct or destroy the
concrete implementation, so two static methods of \ImageCache are
provided:

\apiitem{static ImageCache *ImageCache::{\ce create} (bool shared=true)}

Creates a new \ImageCache and returns a pointer to it.  If 
{\cf shared} is {\cf true}, {\cf create()} will return a pointer
to a shared \ImageCache (so that multiple parts of an application
that request an \ImageCache will all end up with the same one).
If {\cf shared} is {\cf false}, a completely unique \ImageCache
will be created and returned.

\apiend

\apiitem{static void ImageCache::{\ce destroy} (ImageCache *x, bool teardown=false)}
Destroys an allocated \ImageCache, including freeing all system
resources that it holds.

This is necessary to ensure that the memory is freed in a way that
matches the way it was allocated within the library.  Note that simply
using {\cf delete} on the pointer will not always work (at least,
not on some platforms in which a DSO/DLL can end up using a different
allocator than the main program).

It is safe to destroy even a shared \ImageCache, as the implementation
of {\cf destroy()} will recognize a shared one and only truly release
its resources if it has been requested to be destroyed as many times as
shared \ImageCache's were created.  For a shared \ImageCache, if the
{\cf teardown} parameter is {\cf true}, it will try to truly destroy the
shared cache if nobody else is still holding a reference (otherwise,
it will leave it intact).
\apiend

\subsection{Setting options and limits for the image cache}
\label{sec:imagecache:api:attribute}

The following member functions of \ImageCache allow you to set
(and in some cases retrieve) options that control the overall
behavior of the image cache:

\apiitem{bool {\ce attribute} (string_view name, TypeDesc type,
  const void *val)}
\indexapi{attribute}

Sets an attribute (i.e., a property or option) of the \ImageCache.
The {\cf name} designates the name of the attribute, {\cf type}
describes the type of data, and {\cf val} is a pointer to memory 
containing the new value for the attribute.

If the \ImageCache recognizes a valid attribute name that matches the
type specified, the attribute will be set to the new value and {\cf
  attribute()} will return {\cf true}.  If {\cf name} is not recognized
as a valid attribute name, or if the types do not match (e.g., {\cf
  type} is {\cf TypeDesc::FLOAT} but the named attribute is a string),
the attribute will not be modified, and {\cf attribute()} will return
{\cf false}.

Here are examples:

\begin{code}
      ImageCache *ts; 
      ...
      int maxfiles = 50;
      ts->attribute ("max_open_files", TypeDesc::INT, &maxfiles);

      const char *path = "/my/path";
      ts->attribute ("searchpath", TypeDesc::STRING, &path);
\end{code}

Note that when passing a string, you need to pass a pointer to the {\cf
  char*}, not a pointer to the first character.  (Rationale: for an {\cf
  int} attribute, you pass the address of the {\cf int}.  So for a
string, which is a {\cf char*}, you need to pass the address of the
string, i.e., a {\cf char**}).

The complete list of attributes can be found at the end of this section.

\apiend

\apiitem{bool {\ce attribute} (string_view name, int val) \\
bool {\ce attribute} (string_view name, float val) \\
bool {\ce attribute} (string_view name, double val) \\
bool {\ce attribute} (string_view name, string_view val)}
Specialized versions of {\cf attribute()} in which the data type is
implied by the type of the argument.

For example, the following are equivalent to the example above for the
general (pointer) form of {\cf attribute()}:

\begin{code}
      ts->attribute ("max_open_files", 50);
      ts->attribute ("searchpath", "/my/path");
\end{code}

\apiend


\apiitem{bool {\ce getattribute} (string_view name, TypeDesc type,
  void *val)}
\indexapi{getattribute}

Gets the current value of an attribute of the \ImageCache.
The {\cf name} designates the name of the attribute, {\cf type}
describes the type of data, and {\cf val} is a pointer to memory 
where the user would like the value placed.

If the \ImageCache recognizes a valid attribute name that matches the
type specified, the attribute value will be stored at address {\cf val}
and {\cf attribute()} will return {\cf true}.  If {\cf name} is not recognized
as a valid attribute name, or if the types do not match (e.g., {\cf
  type} is {\cf TypeDesc::FLOAT} but the named attribute is a string),
no data will be written to {\cf val}, and {\cf attribute()} will return
{\cf false}.

Here are examples:

\begin{code}
      ImageCache *ts; 
      ...
      int maxfiles;
      ts->getattribute ("max_open_files", TypeDesc::INT, &maxfiles);

      const char *path;
      ts->getattribute ("searchpath", TypeDesc::STRING, &path);
\end{code}

Note that when passing a string, you need to pass a pointer to the {\cf
  char*}, not a pointer to the first character.  Also, the {\cf char*}
will end up pointing to characters owned by the \ImageCache; the
caller does not need to ever free the memory that contains the
characters.

The complete list of attributes can be found at the end of this section.


\apiend

\apiitem{bool {\ce getattribute} (string_view name, int \&val) \\
bool {\ce getattribute} (string_view name, float \&val) \\
bool {\ce getattribute} (string_view name, double \&val) \\
bool {\ce getattribute} (string_view name, char **val) \\
bool {\ce getattribute} (string_view name, std::string \& val)}
Specialized versions of {\cf getattribute()} in which the data type is
implied by the type of the argument.

For example, the following are equivalent to the example above for the
general (pointer) form of {\cf getattribute()}:

\begin{code}
      int maxfiles;
      ts->getattribute ("max_open_files", &maxfiles);
      const char *path;
      ts->getattribute ("searchpath", &path);
\end{code}

\apiend


\subsubsection*{Image cache attributes}

Recognized attributes include the following:

\apiitem{int max_open_files}
The maximum number of file handles that the image cache will
hold open simultaneously.  (Default = 100)
\apiend

\apiitem{float max_memory_MB}
The maximum amount of memory (measured in MB) that the image cache
will use for its ``tile cache.'' (Default: 256.0 MB)
\apiend

\apiitem{string searchpath}
The search path for images: a colon-separated list of
directories that will be searched in order for any image name
that is not specified as an absolute path. (Default: no search path.)
\apiend

\apiitem{string plugin_searchpath}
The search path for plugins: a colon-separated list of
directories that will be searched in order for any OIIO plugins, if
not found in OIIO's ``lib'' directory.)
(Default: no additional search path.)
\apiend

\apiitem{int autotile \\
int autoscanline}
\label{imagecacheattr:autotile}
These attributes control how the image cache deals with images that
are not ``tiled'' (i.e., are stored as scanlines). 

If {\cf autotile} is set to 0 (the default), an untiled image will be
treated as if it were a single tile of the resolution of the whole
image.  This is simple and fast, but can lead to poor cache behavior if
you are simultaneously accessing many large untiled images.

If {\cf autotile} is nonzero (e.g., 64 is a good recommended value), any
untiled images will be read and cached as if they were constructed in
tiles of size:

\begin{tabular}{p{2in} p{3in}}
 {\cf autotile} $\times$ {\cf autotile} & if {\cf autoscanline} is 0 \\
 {\cf width} $\times$ {\cf autotile} & if {\cf autoscanline} is nonzero. \\
\end{tabular}

In both cases, this should lead more efficient caching.  The 
{\cf autoscanline} determines whether the ``virtual tiles'' in the cache
are square (if {\cf autoscanline} is 0, the default) or if they will be
as wide as the image (but only {\cf autotile} scanlines high).  You
should try in your application to see which leads to higher performance.
\apiend

\apiitem{int automip}
If {\cf automip} is set to 0 (the default), an untiled single-subimage
file will only be able to utilize that single subimage.

If {\cf automip} is nonzero, any untiled, single-subimage
(un-MIP-mapped) images will have lower-resolution MIP-map levels
generated on-demand if pixels are requested from the lower-res subimages
(that don't really exist).  Essentially this makes the \ImageCache
pretend that the file is MIP-mapped even if it isn't.
\apiend

\apiitem{int forcefloat}
If set to nonzero, all image tiles will be converted to {\cf float} 
type when stored in the image cache.  This can be helpful especially
for users of \ImageBuf who want to simplify their image manipulations
to only need to consider {\cf float} data.

The default is zero, meaning that image pixels are not forced to
be {\cf float} when in cache.
\apiend

\apiitem{int accept_untiled}
When nonzero (the default), \ImageCache accepts untiled images as
usual.  When set to zero, \ImageCache will reject untiled images with
an error condition, as if the file could not be properly read.
This is sometimes helpful for applications that want to enforce use of
tiled images only.
\apiend

\apiitem{int accept_unmipped}
When nonzero (the default), \ImageCache accepts un-MIPmapped images as
usual.  When set to zero, \ImageCache will reject un-MIPmapped images with
an error condition, as if the file could not be properly read.
This is sometimes helpful for applications that want to enforce use of
MIP-mapped images only.
\apiend

\apiitem{int failure_retries}
When an {\cf open()} or {\cf read_tile()} calls fails, pause and try
again, up to {\cf failure_retries} times before truly returning a
failure.  This is meant to address spooky disk or network failures.  The
default is zero, meaning that failures of open or tile reading will
immediately return as a failure.
\apiend

\apiitem{int deduplicate}
When nonzero, the \ImageCache will notice duplicate images under
different names if their headers contain a SHA-1 fingerprint (as is done
with \maketx-produced textures) and handle them more efficiently by
avoiding redundant reads.  The default is 1 (de-duplication turned on).
The only reason to set it to 0 is if you specifically want to disable the
de-duplication optimization.
\apiend

\apiitem{string substitute_image}
When set to anything other than the empty string, the \ImageCache will
use the named image in place of \emph{all} other images.  This allows
you to run an app using OIIO and (if you can manage to get this option
set) automagically substitute a grid, zone plate, or other special
debugging image for all image/texture use.
\apiend

\apiitem{int unassociatedalpha}
When nonzero, will request that image format readers try to leave input
images with unassociated alpha as they are, rather than automatically
converting to associated alpha upon reading the pixels.  The default is
0, meaning that the automatic conversion will take place.
\apiend

\apiitem{int max_errors_per_file}
The maximum number of errors that will be printed for each file. The default
is 100. If your output is cluttered with error messages and after the first
few for each file you aren't getting any helpful additional information,
this can cut down on the clutter and the runtime.
\apiend

\apiitem{int max_open_files}
The maximum number of file handles that the image cache will
hold open simultaneously.  (Default = 100)
\apiend

\apiitem{string options}
This catch-all is simply a comma-separated list of {\cf name=value}
settings of named options, which will be parsed and individually set.
\begin{code}
        ic->attribute ("options", "max_memory_MB=512.0,autotile=1");
\end{code}
Note that if an option takes a string value that must itself contain a
comma, it is permissible to enclose the value in either single ({\cf ' '})
or double ({\cf " "}) quotes.
\apiend

\apiitem{int total_files {\rm ~(read only)}}
The total number of unique file names referenced by calls to the \ImageCache.
\apiend

\apiitem{string[] all_filenames {\rm ~(read only)}}
An array that will be filled with the list of the names of all files
referenced by calls to the \ImageCache. (The array is of {\cf ustring}s or
{\cf char*}'s.)
\apiend

\apiitem{int64 stat:cache_memory_used {\rm ~(read only)}}
Total bytes used by tile cache.
\apiend

\apiitem{int stat:tiles_created {\rm ~(read only)} \\
int stat:tiles_current {\rm ~(read only)} \\
int stat:tiles_peak {\rm ~(read only)}}
Total times created, still allocated (at the time of the query), and the
peak number of tiles in memory at any time.
\apiend

\apiitem{int stat:open_files_created {\rm ~(read only)} \\
int stat:open_files_current {\rm ~(read only)} \\
int stat:open_files_peak {\rm ~(read only)}}
Total number of times a file was opened, number still opened (at the time of
the query), and the peak number of files opened at any time.
\apiend

\apiitem{int stat:find_tile_calls {\rm ~(read only)}}
Number of times a filename was looked up in the file cache.
\apiend

\apiitem{int64 stat:image_size {\rm ~(read only)}}
Total size (uncompressed bytes of pixel data) of all images referenced
by the \ImageCache. (Note: Prior to 1.7, this was called \qkw{stat:files_totalsize}.)
\apiend

\apiitem{int64 stat:file_size {\rm ~(read only)}}
Total size of all files (as on disk, possibly compressed) of all images
referenced by the \ImageCache.
\apiend

\apiitem{int64 stat:bytes_read {\rm ~(read only)}}
Total size (uncompressed bytes of pixel data) read.
\apiend

\apiitem{int stat:unique_files {\rm ~(read only)}}
Number of unique files opened.
\apiend

\apiitem{float stat:fileio_time {\rm ~(read only)}}
Total I/O-related time (seconds).
\apiend

\apiitem{float stat:fileopen_time {\rm ~(read only)}}
I/O time related to opening and reading headers (but not pixel I/O).
\apiend

\apiitem{float stat:file_locking_time {\rm ~(read only)}}
Total time (across all threads) that threads blocked waiting for access to
the file data structures.
\apiend

\apiitem{float stat:tile_locking_time {\rm ~(read only)}}
Total time (across all threads) that threads blocked waiting for access to
the tile cache data structures.
\apiend

\apiitem{float stat:find_file_time {\rm ~(read only)}}
Total time (across all threads) that threads spent looking up files by name.
\apiend

\apiitem{float stat:find_tile_time {\rm ~(read only)}}
Total time (across all threads) that threads spent looking up individual tiles.
\apiend



\bigskip

\subsection{Opaque data for performance lookups}
\label{sec:imagecache:api:opaque}

\apiitem{Perthread * {\ce get_perthread_info} (Perthread *thread_info=NULL) \\
Perthread * {\ce create_perthread_info} () \\
void {\ce destroy_perthread_info} (Perthread *thread_info)}
\indexapi{get_perthread_info}
\indexapi{create_perthread_info} \indexapi{destroy_perthread_info}

The \ImageCache implementation needs to maintain certain per-thread
state, and some \ImageCache methods take an opaque {\cf Perthread} pointer
to this record. There are three options for how to deal with it:

1. Don't worry about it at all: don't use the methods that want {\cf
Perthread} pointers, or always pass {\cf NULL} for any {\cf Perthread*}
arguments, and \ImageCache will do thread-specific-pointer retrieval as
necessary (though at some small cost).

2. If your app already stores per-thread information of its own, you may
call {\cf get_perthread_info(NULL)} to retrieve it for that thread, and then
pass it into the functions that allow it (thus sparing them the need and
expense of retrieving the thread-specific pointer). However, it is crucial
that this pointer not be shared between multiple threads. In this case,
the \ImageCache manages the storage, which will automatically be released
when the thread terminates.

3. If your app also wants to manage the storage of the {\cf Perthread},
it can explicitly create one with {\cf create_perthread_info}, pass it around,
and eventually be responsible for destroying it with {\cf destroy_perthread_info}.
When managing the storage, the app may reuse the {\cf Perthread} for another
thread after the first is terminated, but still may not use the same
{\cf Perthread} for two threads running concurrently.
\apiend


\apiitem{ImageHandle * {\ce get_image_handle} (ustring filename,\\
\bigspc\bigspc\spc\spc  Perthread *thread_info=NULL)}
\indexapi{get_image_handle}
Retrieve an opaque handle for fast \ImageCache lookups.  The optional opaque
pointer {\cf thread_info} is thread-specific information returned by
{\cf get_perthread_info()}.  Return {\cf NULL} if something has gone
horribly wrong.
\apiend

\apiitem{bool {\ce good} (ImageHandle *file)}
\indexapi{good}
Return true if the image handle (previously returned by
{\cf get_image_handle()}) is a valid image that can be subsequently read.
\apiend


\subsection{Getting information about images}
\label{sec:imagecache:api:getimageinfo}
\label{sec:imagecache:api:getimagespec}


\apiitem{bool {\ce get_image_info} (ustring filename, int subimage, int
  miplevel, \\
  \bigspc\bigspc ustring dataname, TypeDesc datatype, void *data) \\
bool {\ce get_image_info} (ImageHandle *file, Perthread *thread_info,\\
  \bigspc\bigspc int subimage, int miplevel, \\
  \bigspc\bigspc ustring dataname, TypeDesc datatype, void *data)}
Retrieves information about the image named by {\cf filename} (or specified
by the opaque image handle).
The {\cf dataname} is a keyword indcating what information should
be retrieved, {\cf datatype} is the type of data expected, and
{\cf data} points to caller-owned memory where the results should be
placed.  It is up to the caller to ensure that {\cf data} contains
enough space to hold an item of the requested {\cf datatype}.

The return value is {\cf true} if {\cf get_image_info()} is able to answer
the query -- that is, find the requested {\cf dataname} for the texture and
it matched the requested {\cf datatype}.  If the requested data was not
found, or was not of the right data type, {\cf get_texture_info()} will
return {\cf false}. Except for the \qkw{exists} query, file that does not
exist or could not be read properly as an image also constitutes a query
failure that will return {\cf false}.

Supported {\cf dataname} values include:

\begin{description}
\item[\spc] \spc
\vspace{-12pt} 

\item[\rm \kw{exists}] Stores the value 1 (as an {\cf int}) if the file
exists and is an image format that \product can read, or 0 if the file
does not exist, or could not be properly read as an image. Note that
unlike all other queries, this query will ``succeed'' (return {\cf true})
even if the file does not exist.

\item[\rm \kw{udim}] Stores the value 1 (as an {\cf int}) if the file
is a ``virtual UDIM'' or texture atlas file (as described in
Section~\ref{sec:texturesys:udim}) or 0 otherwise.

\item[\rm \kw{subimages}] The number of subimages in the file, as an integer.

\item[\rm \kw{resolution}] The resolution of the image file, which
is an array of 2 integers (described as {\cf TypeDesc(INT,2)}).

\item[\rm \kw{miplevels}] The number of MIPmap levels for the specified
subimage (an integer).

\item[\rm \kw{texturetype}] A string describing the type of texture
of the given file, which describes how the texture may be used (also
which texture API call is probably the right one for it).
This currently may return one of: \qkw{unknown}, \qkw{Plain Texture},
\qkw{Volume Texture}, \qkw{Shadow}, 
or \qkw{Environment}.

\item[\rm \kw{textureformat}] A string describing the format of the
given file, which describes the kind of texture stored in the file.
This currently may return one of: \qkw{unknown}, \qkw{Plain Texture},
\qkw{Volume Texture}, \qkw{Shadow}, \qkw{CubeFace Shadow}, \qkw{Volume
  Shadow}, \qkw{LatLong Environment}, or \qkw{CubeFace Environment}.
Note that there are several kinds of shadows and environment maps,
all accessible through the same API calls.

\item[\rm \kw{channels}] The number of color channels in the file 
(an integer).

\item[\rm \kw{format}] The native data format of the pixels in the
  file (an integer, giving the {\cf TypeDesc::BASETYPE} of the data).
  Note that this is not necessarily the same as the data format stored
  in the image cache.

\item[\rm \kw{cachedformat}] The native data format of the pixels as
  stored in the image cache (an integer, giving the {\cf
    TypeDesc::BASETYPE} of the data).  Note that this is not necessarily
  the same as the native data format of the file.

\item[\rm \kw{datawindow}] 
Returns the pixel data window of the image, which is either an array of 4
integers (returning xmin, ymin, xmax, ymax) or an array of 6 integers
(returning xmin, ymin, zmin, xmax, ymax, zmax). The $z$ values may be useful
for 3D/volumetric images; for 2D images they will be 0).

\item[\rm \kw{displaywindow}] 
Returns the display (a.k.a.\ full) window of the image, which is either an
array of 4 integers (returning xmin, ymin, xmax, ymax) or an array of 6
integers (returning xmin, ymin, zmin, xmax, ymax, zmax). The $z$ values may
be useful for 3D/volumetric images; for 2D images they will be 0).

\item[\rm \kw{worldtocamera}] The viewing matrix, which is a $4 \times 4$
matrix (an {\cf Imath::M44f}, described as {\cf TypeDesc(FLOAT,MATRIX)}),
giving the world-to-camera 3D transformation matrix that was used when  the
image was created. Generally, only rendered images will have this.

\item[\rm \kw{worldtoscreen}] The projection matrix, which is a $4 \times 4$
matrix (an {\cf Imath::M44f}, described as {\cf TypeDesc(FLOAT,MATRIX)}),
giving the matrix that projected points from world space into a 2D screen
coordinate system where $x$ and $y$ range from $-1$ to $+1$.  Generally,
only rendered images will have this.

\item[\rm \kw{averagecolor}] If available in the metadata (generally only
for files that have been processed by {\cf maketx}), this will return the
average color of the texture (into an array of floats).

\item[\rm \kw{averagealpha}] If available in the metadata (generally only
for files that have been processed by {\cf maketx}), this will return the
average alpha value of the texture (into a float).

\item[\rm \kw{constantcolor}] If the metadata (generally only for files that
have been processed by {\cf maketx}) indicates that the texture has the same
values for all pixels in the texture, this will retrieve the constant color
of the texture (into an array of floats). A non-constant image (or one that
does not have the special metadata tag identifying it as a constant texture)
will fail this query (return false).

\item[\rm \kw{constantalpha}] If the metadata indicates that the texture has
the same values for all pixels in the texture, this will retrieve the
constant alpha value of the texture (into a float). A non-constant image (or
one that does not have the special metadata tag identifying it as a constant
texture) will fail this query (return false).

\item[\rm \kw{stat:tilesread}] Number of tiles read from this file ({\cf int64}).

\item[\rm \kw{stat:bytesread}] Number of bytes of uncompressed pixel data read
from this file ({\cf int64}).

\item[\rm \kw{stat:redundant_tiles}] Number of times a tile was read, where
the same tile had been rad before. ({\cf int64}).

\item[\rm \kw{stat:redundant_bytesread}] Number of bytes (of uncompressed pixel
data) in tiles that were read redundantly. ({\cf int64}).

\item[\rm \kw{stat:redundant_bytesread}] Number of tiles read from this file ({\cf int}).

\item[\rm \kw{stat:image_size}] Size of the uncompressed image pixel data
of this image, in bytes ({\cf int64}).

\item[\rm \kw{stat:file_size}] Size of the disk file (possibly compressed)
for this image, in bytes ({\cf int64}).

\item[\rm \kw{stat:timesopened}] Number of times this file was opened ({\cf int}).

\item[\rm \kw{stat:iotime}] Time (in seconds) spent on all I/O for this file ({\cf float}).

\item[\rm \kw{stat:mipsused}] Stores 1 if any MIP levels beyond the highest
resolution were accesed, otherwise 0. ({\cf int})

\item[\rm \kw{stat:is_duplicate}] Stores 1 if this file was a duplicate of
another image, otherwise 0. ({\cf int})

\item[Anything else] -- For all other data names, the
the metadata of the image file will be searched for an item that
matches both the name and data type.

\end{description}
\apiend

\apiitem{bool {\ce get_imagespec} (ustring filename, ImageSpec \&spec,\\
\bigspc\spc\spc  int subimage=0, int miplevel=0, bool native=false)\\
bool {\ce get_imagespec} (ImageHandle *file,  Perthread *thread_info,\\
  \bigspc\bigspc ImageSpec \&spec, int subimage=0, \\
  \bigspc\bigspc int miplevel=0, bool native=false)}

If the image (and the specific subimage and MIP level) is found and able to
be opened by an available
image format plugin, and the designated subimage exists, this function copies
its image specification for that subimage into {\cf spec} and returns
{\cf true}.  Otherwise, if the file is not found, could not be opened,
is not of a format readable by any plugin that could be found, or
the designated subimage did not exist in the file, the return value is
{\cf false} and {\cf spec} will not be modified.
The image may be specified either by name, or by the opaque handle returned
by {\cf get_image_handle()}.

If {\cf native} is {\cf false} (the default), then the spec retrieved
will accurately describe the image stored internally in the cache,
whereas if {\cf native} is {\cf true}, the spec retrieved will reflect
the original file.  These may differ due to use of certain \ImageCache
settings such as \qkw{forcefloat} or \qkw{autotile}.

\apiend

\apiitem{const ImageSpec * {\ce imagespec} (ustring filename, int
  subimage=0, \\
      \bigspc\bigspc\spc int miplevel=0, bool native=false) \\
const ImageSpec * {\ce imagespec} (ImageHandle *file, Perthread *thread_info,\\
  \bigspc\bigspc int subimage=0, int miplevel=0, bool native=false)}

If the image is found and able to be opened by an available
image format plugin, and the designated subimage exists, this function
returns a pointer to an \ImageSpec that describes it.  Otherwise, if the
file is not found, could not be opened, is not of a format readable by
any plugin that could be find, or the designated subimage did
not exist in the file, the return value is NULL.
The image may be specified either by name, or by the opaque handle returned
by {\cf get_image_handle()}.

If {\cf native} is {\cf false} (the default), then the spec retrieved
will accurately describe the image stored internally in the cache,
whereas if {\cf native} is {\cf true}, the spec retrieved will reflect
the original file.  These may differ due to use of certain \ImageCache
settings such as \qkw{forcefloat} or \qkw{autotile}.

This method is much more efficient than {\cf get_imagespec()}, since it
just returns a pointer to the spec held internally by the \ImageCache
(rather than copying the spec to the user's memory).  However, the
caller must beware that the pointer is only valid as long as nobody
(even other threads) calls {\cf invalidate()} on the file, or {\cf
  invalidate_all()}, or destroys the \ImageCache.
\apiend

\apiitem{std::string {\ce resolve_filename} (const std::string \&filename)}
Returns the true path to the given file name, with searchpath logic
applied.
\apiend

\subsection{Getting pixels}
\label{sec:imagecache:api:getpixels}

\apiitem{bool {\ce get\_pixels} (ustring filename, int subimage, int miplevel, \\
         \bigspc\spc int xbegin, int xend, int ybegin, int yend, \\
         \bigspc\spc int zbegin, int zend, \\
         \bigspc\spc TypeDesc format, void *result) \\
bool {\ce get\_pixels} (ImageHandle *file, Perthread *thread_info, \\
         \bigspc\spc int subimage, int miplevel, \\
         \bigspc\spc int xbegin, int xend, int ybegin, int yend, \\
         \bigspc\spc int zbegin, int zend, \\
         \bigspc\spc TypeDesc format, void *result)}
For an image specified by either name or handle,
retrieve the rectangle of pixels
of the designated {\cf subimage} and {\cf miplevel}, storing the pixel values
beginning at the address specified by result.  The pixel values will be
converted to the type specified by {\cf format}.  It is up to the caller
to ensure that result points to an area of memory big enough to
accommodate the requested rectangle (taking into consideration its
dimensions, number of channels, and data format).
The rectangular region to be retrieved includes {\cf begin} but does not
include {\cf end} (much like STL begin/end usage).
Requested pixels that are not part of the valid pixel data region of the
image file will be filled with zero values.
\apiend

\apiitem{bool {\ce get\_pixels} (ustring filename, int subimage, int miplevel, \\
         \bigspc\spc int xbegin, int xend, int ybegin, int yend, \\
         \bigspc\spc int zbegin, int zend, int chbegin, int chend,\\
         \bigspc\spc TypeDesc format, void *result, \\
         \bigspc\spc stride_t xstride, stride_t ystride, stride_t zstride,\\
         \bigspc\spc int cache_chbegin=0, int cache_chend=-1) \\
bool {\ce get\_pixels} (ImageHandle *file, Perthread *thread_info, \\
         \bigspc\spc int subimage, int miplevel, \\
         \bigspc\spc int xbegin, int xend, int ybegin, int yend, \\
         \bigspc\spc int zbegin, int zend, int chbegin, int chend,\\
         \bigspc\spc TypeDesc format, void *result, \\
         \bigspc\spc stride_t xstride, stride_t ystride, stride_t zstride,\\
         \bigspc\spc int cache_chbegin=0, int cache_chend=-1)}
For an image specified by either name or handle,
retrieve the rectangle of pixels and subset of channels
of the designated {\cf subimage} and {\cf miplevel}, storing the pixel values
beginning at the address specified by result and with the given strides.
The pixel values will be
converted to the type specified by {\cf format}.  It is up to the caller
to ensure that result points to an area of memory big enough to
accommodate the requested rectangle (taking into consideration its
dimensions, number of channels, data format, and strides).
Any stride values set to {\cf AutoStride} will be assumed to indicate
a contiguous data layout.
The rectangular region and channel set to be retrieved includes 
{\cf begin} but does not
include {\cf end} (much like STL begin/end usage).
Requested pixels that are not part of the valid pixel data region of the
image file will be filled with zero values. The optional parameters
{\cf cache_chbegin} and {\cf cache_chend} can be used to tell the
\ImageCache to read and cache a subset of channels (if not specified,
all the channels of the file will be stored in the cached tile).
\apiend


\subsection{Dealing with tiles}
\label{sec:imagecache:api:tiles}

\apiitem{ImageCache::Tile * {\ce get_tile} (ustring filename, int subimage, int miplevel, \\
  \bigspc \bigspc int x, int y, int z, int chbegin=0, int chend=-1) \\
ImageCache::Tile * {\ce get_tile} (ImageHandle *file, Perthread *thread_info, \\
\bigspc\bigspc int subimage, int miplevel, \\
  \bigspc \bigspc int x, int y, int z, int chbegin=0, int chend=-1)}
Find a tile of an image (identified by either name or handle)
for the requested {\cf subimage}, pixel
coordinates, and channel range (if {\cf chend < chbegin}, the full
range of channels in the file will be used).
An opaque pointer to the tile will be returned,
or {\cf NULL} if no such file (or tile within the file) exists or can
be read.  The tile will not be purged from the cache until 
after {\cf release_tile()} is called on the tile pointer.  This is
thread-safe.
\apiend

\apiitem{void {\ce release_tile} (ImageCache::Tile *tile)}
After finishing with a tile, {\cf release_tile()} will allow it to 
once again be purged from the tile cache if required.
\apiend

\apiitem{const void * {\ce tile_pixels} (ImageCache::Tile *tile,
  TypeDesc \&format)}
For a tile retrived by {\cf get_tile()}, return a pointer to the
pixel data itself, and also store in {\cf format} the data type that
the pixels are internally stored in (which may be different than
the data type of the pixels in the disk file).  This method should
only be called on a tile that has been requested by 
{\cf get_tile()} but has not yet been released with {\cf release_tile()}.
\apiend

\apiitem{void {\ce invalidate} (ustring filename, bool force=true)}
Invalidate any loaded tiles or open file handles associated with
the filename, so that any subsequent queries will be forced to
re-open the file or re-load any tiles (even those that were
previously loaded and would ordinarily be reused).  A client
might do this if, for example, they are aware that an image
being held in the cache has been updated on disk.  This is safe
to do even if other procedures are currently holding 
reference-counted tile pointers from the named image, but those 
procedures will not get updated pixels until they release the 
tiles they are holding.

If {\cf force} is true, this invalidation will happen unconditionally; if
false, the file will only be invalidated if it has been changed since it was
first opened by the ImageCache.
\apiend

\apiitem{void {\ce invalidate_all} (bool force=false)}
Invalidate all loaded tiles and open file handles, so that any
subsequent queries will be forced to re-open the file or re-load any
tiles (even those that were previously loaded and would ordinarily be
reused).  A client might do this if, for example, they are aware that an
image being held in the cache has been updated on disk.  This is safe to
do even if other procedures are currently holding reference-counted tile
pointers from the named image, but those procedures will not get updated
pixels until they release the tiles they are holding.  If force is true,
everything will be invalidated, no matter how wasteful it is, but if
force is false, in actuality files will only be invalidated if their
modification times have been changed since they were first opened.
\apiend

\apiitem{void {\ce close} (ustring filename) \\
void {\ce close_all} ()}
Close any open file handles associated with a named file, or for all
files, but do not invalidate any image spec information or pixels
associated with the files.  A client might do this in order to
release OS file handle resources, or to make it safe for other
processes to modify cached files.
\apiend

\subsection{Seeding the cache}
\label{sec:imagecache:api:seeding}
\apiitem{bool {\ce add_file} (ustring filename, \\
    \bigspc ImageInput::Creator creator = NULL,\\
    \bigspc const ImageSpec *config = NULL)}
This method causes a file to be opened or added to the
cache. There is no reason to use this method unless you are supplying
a custom creator, or configuration, or both.

If {\cf creator} is not NULL, it points to an {\cf ImageInput::Creator} that
will be used rather than the default {\cf ImageInput::create()}, thus
instead of reading from disk, creates and uses a custom ImageInput
to generate the image. The {\cf creator} is a factory that creates the
custom ImageInput and will be called like this:
\begin{code}
    ImageInput *in = creator();
\end{code}
Once created, the \ImageCache owns the \ImageInput and is responsible
for destroying it when done. Custom \ImageInput's allow ``procedural''
images, among other things.  Also, this is the method you use to set
up a ``writeable'' \ImageCache images (perhaps with a type of
\ImageInput that's just a stub that does as little as possible).

If {\cf config} is not NULL, it points to an \ImageSpec with configuration
options/hints that will be passed to the underlying
{\cf ImageInput::open()} call. Thus, this can be used to ensure that the
\ImageCache opens a call with special configuration options.

This call (including any custom creator or configuration hints) will
have no effect if there's already an image by the same name in the
cache. Custom creators or configurations only ``work'' the \emph{first} time
a particular filename is referenced in the lifetime of the
\ImageCache.
\apiend

\apiitem{bool {\ce add_tile} (ustring filename, int subimage, int miplevel,\\
\bigspc        int x, int y, int z, int chbegin, int chend, \\
\bigspc        TypeDesc format, const void *buffer,\\
\bigspc        stride_t xstride=AutoStride, stride_t ystride=AutoStride, \\
\bigspc        stride_t zstride=AutoStride}
Preemptively add a tile corresponding to the named image, at the
given subimage and MIP level.  The tile added is the one whose
corner is (x,y,z), with the given channel range,
and buffer points to the pixels (in the given
format, with supplied strides) which will be copied and inserted
into the cache and made available for future lookups.
\apiend

\subsection{Errors and statistics}
\label{sec:imagecache:api:geterror}
\label{sec:imagecache:api:getstats}
\label{sec:imagecache:api:resetstats}

\apiitem{std::string {\ce geterror} ()}
\index{error checking}
If any other API routines return {\cf false}, indicating that an error
has occurred, this routine will retrieve the error and clear the error
status.  If no error has occurred since the last time {\cf geterror()}
was called, it will return an empty string.
\apiend

\apiitem{std::string {\ce getstats} (int level=1)}
Returns a big string containing useful statistics about the \ImageCache
operations, suitable for saving to a file or outputting to the terminal.
The {\cf level} indicates the amount of detail in the statistics,
with higher numbers (up to a maximum of 5) yielding more and more
esoteric information.
\apiend

\apiitem{void {\ce reset_stats} ()}
Reset most statistics to be as they were with a fresh
\ImageCache.  Caveat emptor: this does not flush the cache
itelf, so the resulting statistics from the next set of texture
requests will not match the number of tile reads, etc., that
would have resulted from a new \ImageCache.
\apiend


\index{Image Cache|)}

\chapwidthend
