289
z Some resources like background music, ambient sound eff ects, or full-
screen movies are streamed “live” as they play. The lifetime of this kind
of resource is diffi cult to defi ne, because each byte only persists in mem-
ory for a tiny fraction of a second, but the entire piece of music sounds
like it lasts for a long period of time. Such assets are typically loaded in
chunks of a size that matches the underlying hardware’s requirements.
For example, a music track might be read in 4 kB chunks, because that
might be the buff er size used by the low-level sound system. Only two
chunks are ever present in memory at any given moment—the chunk
that is currently playing and the chunk immediately following it that is
being loaded into memory.
The question of when to load a resource is usually answered quite easily,
based on knowledge of when the asset is fi rst seen by the player. However, the
question of when to unload a resource and reclaim its memory is not so eas-
ily answered. The problem is that many resources are shared across multiple
levels. We don’t want to unload a resource when level A is done, only to im-
mediately reload it because level B needs the same resource.
One solution to this problem is to reference-count the resources. When-
ever a new game level needs to be loaded, the list of all resources used by that
level is traversed, and the reference count for each resource is incremented
by one (but they are not loaded yet). Next, we traverse the resources of any
unneeded levels and decrement their reference counts by one; any resource
whose reference count drops to zero is unloaded. Finally, we run through the
list of all resources whose reference count just went from zero to one and load
those assets into memory.
For example, imagine that level 1 uses resources A, B, and C, and that
level 2 uses resources B, C, D, and E. (B and C are shared between both levels.)
Table 6.2 shows the reference counts of these fi ve resources as the player plays
through levels 1 and 2. In this table, reference counts are shown in boldface
type to indicate that the corresponding resource actually exists in memory,
while a grey background indicates that the resource is not in memory. A refer-
ence count in parentheses indicates that the corresponding resource data is
being loaded or unloaded.
6.2.2.7. Memory Management for Resources
Resource management is closely related to memory management , because we
must inevitably decide where the resources should end up in memory once
they have been loaded. The destination of every resource is not always the
same. For one thing, certain types of resources must reside in video RAM.
Typical examples include textures, vertex buff ers, index buff ers, and shader
6.2. The Resource Manager