If there's not enough RAM, the value of the desired amount is halved until malloc suceeds. The algorithm then iterates down from the previously attempted higher amount value, until the highest possible available amount value is found.
The algorithm also ensures that a minimum amount of free memory is still available for the program to use elsewhere.
However, this doesn't seem to be working. It always calls Sys_Error, which means malloc is always failing, despite the initial D_SurfaceCacheForRes value being actually valid (it works if I malloc it directly).
[edit] I've fixed the code now.
Code: Select all
// initialize
maxofs = D_SurfaceCacheForRes (width, height);
vid_surfcachesize = 0;
// iterate up
do
{
minofs = maxofs - vid_surfcachesize;
// iterate down
do
{
maxofs = minofs; // before halving.
minofs >>= 1;
if (!(vid_surfcachesize + minofs))
{
Sys_Error ("Not enough RAM for surface caches\n");
return false;
}
}
while (!(vid_surfcache = (byte *)malloc (vid_surfcachesize + minofs))); // still null
// finally allocated it, so let's free and try to reallocate a higher value.
free (vid_surfcache);
vid_surfcachesize += minofs; // this value is guaranteed to work now.
}
while ( (maxofs - minofs) > 0x0FFFFFFF); // 256 * 1024 * 1024 // should let enough free RAM to compile textures.
// now allocate it for good.
vid_surfcache = (byte *)malloc (vid_surfcachesize);