]> icculus.org git repositories - taylor/freespace2.git/blob - src/bmpman/bmpman.cpp
merge in updated graphics code
[taylor/freespace2.git] / src / bmpman / bmpman.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Bmpman/BmpMan.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Code to load and manage all bitmaps for the game
16  *
17  * $Log$
18  * Revision 1.11  2004/07/04 11:31:43  taylor
19  * amd64 support, compiler warning fixes, don't use software rendering
20  *
21  * Revision 1.10  2003/05/28 06:02:04  taylor
22  * fix transparency in green weapon blobs
23  *
24  * Revision 1.9  2002/06/09 04:41:15  relnev
25  * added copyright header
26  *
27  * Revision 1.8  2002/06/05 04:03:32  relnev
28  * finished cfilesystem.
29  *
30  * removed some old code.
31  *
32  * fixed mouse save off-by-one.
33  *
34  * sound cleanups.
35  *
36  * Revision 1.7  2002/06/03 09:25:37  relnev
37  * implement mouse cursor and screen save/restore
38  *
39  * Revision 1.6  2002/05/30 23:07:08  relnev
40  * shh
41  *
42  * Revision 1.5  2002/05/30 21:44:48  relnev
43  * implemented some missing texture stuff.
44  *
45  * enable bitmap polys for opengl.
46  *
47  * work around greenness in bitmaps.
48  *
49  * Revision 1.4  2002/05/28 17:03:29  theoddone33
50  * fs2 gets to the main game loop now
51  *
52  * Revision 1.3  2002/05/28 08:52:03  relnev
53  * implemented two assembly stubs.
54  *
55  * cleaned up a few warnings.
56  *
57  * added a little demo hackery to make it progress a little farther.
58  *
59  * Revision 1.2  2002/05/07 03:16:43  theoddone33
60  * The Great Newline Fix
61  *
62  * Revision 1.1.1.1  2002/05/03 03:28:08  root
63  * Initial import.
64  *
65  * 
66  * 37    9/13/99 11:26p Andsager
67  * Add debug code to check for poorly sized anis
68  * 
69  * 36    9/05/99 11:19p Dave
70  * Made d3d texture cache much more safe. Fixed training scoring bug where
71  * it would backout scores without ever having applied them in the first
72  * place.
73  * 
74  * 35    8/20/99 2:09p Dave
75  * PXO banner cycling.
76  * 
77  * 34    8/10/99 6:54p Dave
78  * Mad optimizations. Added paging to the nebula effect.
79  * 
80  * 33    8/06/99 1:52p Dave
81  * Bumped up MAX_BITMAPS for the demo.
82  * 
83  * 32    8/02/99 1:49p Dave
84  * Fixed low-mem animation problem. Whee!
85  * 
86  * 31    7/16/99 1:49p Dave
87  * 8 bit aabitmaps. yay.
88  * 
89  * 30    7/13/99 1:15p Dave
90  * 32 bit support. Whee!
91  * 
92  * 29    6/29/99 10:35a Dave
93  * Interface polygon bitmaps! Whee!
94  * 
95  * 28    6/16/99 4:06p Dave
96  * New pilot info popup. Added new draw-bitmap-as-poly function.
97  * 
98  * 27    5/05/99 9:02p Dave
99  * Fixed D3D aabitmap rendering. Spiffed up nebula effect a bit (added
100  * rotations, tweaked values, made bitmap selection more random). Fixed
101  * D3D beam weapon clipping problem. Added D3d frame dumping.
102  * 
103  * 26    4/27/99 12:16a Dave
104  * Fixed beam weapon muzzle glow problem. Fixed premature timeout on the
105  * pxo server list screen. Fixed secondary firing for hosts on a
106  * standalone. Fixed wacky multiplayer weapon "shuddering" problem.
107  * 
108  * 25    4/09/99 2:21p Dave
109  * Multiplayer beta stuff. CD checking.
110  * 
111  * 24    4/08/99 10:42a Johnson
112  * Don't try to swizzle a texture to transparent in Fred.
113  * 
114  * 23    3/31/99 8:24p Dave
115  * Beefed up all kinds of stuff, incluging beam weapons, nebula effects
116  * and background nebulae. Added per-ship non-dimming pixel colors.
117  * 
118  * 22    3/20/99 3:46p Dave
119  * Added support for model-based background nebulae. Added 3 new
120  * sexpressions.
121  * 
122  * 21    2/11/99 3:08p Dave
123  * PXO refresh button. Very preliminary squad war support.
124  * 
125  * 20    2/08/99 5:07p Dave
126  * FS2 chat server support. FS2 specific validated missions.
127  * 
128  * 19    2/05/99 12:52p Dave
129  * Fixed Glide nondarkening textures.
130  * 
131  * 18    2/04/99 6:29p Dave
132  * First full working rev of FS2 PXO support.  Fixed Glide lighting
133  * problems.
134  * 
135  * 17    2/03/99 11:44a Dave
136  * Fixed d3d transparent textures.
137  * 
138  * 16    1/15/99 11:29a Neilk
139  * Fixed D3D screen/texture pixel formatting problem. 
140  * 
141  * 15    1/14/99 12:48a Dave
142  * Todo list bug fixes. Made a pass at putting briefing icons back into
143  * FRED. Sort of works :(
144  * 
145  * 14    1/12/99 12:53a Dave
146  * More work on beam weapons - made collision detection very efficient -
147  * collide against all object types properly - made 3 movement types
148  * smooth. Put in test code to check for possible non-darkening pixels on
149  * object textures.
150  * 
151  * 13    1/08/99 2:08p Dave
152  * Fixed software rendering for pofview. Super early support for AWACS and
153  * beam weapons.
154  * 
155  * 12    1/06/99 2:24p Dave
156  * Stubs and release build fixes.
157  * 
158  * 11    12/14/98 4:01p Dave
159  * Got multi_data stuff working well with new xfer stuff. 
160  * 
161  * 10    12/06/98 2:36p Dave
162  * Drastically improved nebula fogging.
163  * 
164  * 9     12/01/98 5:53p Dave
165  * Simplified the way pixel data is swizzled. Fixed tga bitmaps to work
166  * properly in D3D and Glide.
167  * 
168  * 8     12/01/98 4:46p Dave
169  * Put in targa bitmap support (16 bit).
170  * 
171  * 7     12/01/98 10:32a Johnson
172  * Fixed direct3d font problems. Fixed sun bitmap problem. Fixed direct3d
173  * starfield problem.
174  * 
175  * 6     12/01/98 8:06a Dave
176  * Temporary checkin to fix some texture transparency problems in d3d.
177  * 
178  * 5     11/30/98 5:31p Dave
179  * Fixed up Fred support for software mode.
180  * 
181  * 4     11/30/98 1:07p Dave
182  * 16 bit conversion, first run.
183  * 
184  * 3     10/22/98 6:14p Dave
185  * Optimized some #includes in Anim folder. Put in the beginnings of
186  * parse/localization support for externalized strings and tstrings.tbl
187  * 
188  * 2     10/07/98 10:52a Dave
189  * Initial checkin.
190  * 
191  * 1     10/07/98 10:48a Dave
192  * 
193  * 106   5/23/98 4:43p John
194  * Took out debugging sleep
195  * 
196  * 105   5/23/98 4:14p John
197  * Added code to preload textures to video card for AGP.   Added in code
198  * to page in some bitmaps that weren't getting paged in at level start.
199  * 
200  * 104   5/20/98 12:59p John
201  * Turned optimizations on for debug builds.   Also turning on automatic
202  * function inlining.  Turned off the unreachable code warning.
203  * 
204  * 103   5/20/98 10:20a Hoffoss
205  * Fixed warning in the code.
206  * 
207  * 102   5/19/98 3:45p John
208  * fixed bug causing lowmem to drop half of the frames. Also halved fps
209  * during lowmem.
210  * 
211  * 101   5/14/98 3:38p John
212  * Added in more non-darkening colors for Adam.  Had to fix some bugs in
213  * BmpMan and Ani stuff to get this to work.
214  * 
215  * 100   4/22/98 9:13p John
216  * Added code to replace frames of animations in vram if so desired.
217  * 
218  * 99    4/17/98 6:56a John
219  * Fixed bug where RLE'd user bitmaps caused data to not get freed.
220  * (Turned off RLE for use bitmaps).   Made lossy animations reduce
221  * resolution by a factor of 2 in low memory conditions.
222  * 
223  * 98    4/16/98 6:31p Hoffoss
224  * Added function to get filename of a bitmap handle, which we don't have
225  * yet and I need.
226  * 
227  * 97    4/01/98 9:27p John
228  * Fixed debug info in bmpman.
229  * 
230  * 96    4/01/98 5:34p John
231  * Made only the used POFs page in for a level.   Reduced some interp
232  * arrays.    Made custom detail level work differently.
233  * 
234  * 95    3/31/98 9:55a Lawrance
235  * JOHN: get xparency working for user bitmaps
236  * 
237  * 94    3/30/98 4:02p John
238  * Made machines with < 32 MB of RAM use every other frame of certain
239  * bitmaps.   Put in code to keep track of how much RAM we've malloc'd.
240  * 
241  * 93    3/29/98 4:05p John
242  * New paging code that loads everything necessary at level startup.
243  * 
244  * 92    3/27/98 11:20a John
245  * commented back in some debug code.
246  * 
247  * 91    3/26/98 5:21p John
248  * Added new code to preload all bitmaps at the start of a level.
249  * Commented it out, though.
250  * 
251  * 90    3/26/98 4:56p Jasen
252  * AL: Allow find_block_of() to allocate a series of bitmaps from index 0
253  * 
254  * 89    3/26/98 10:21a John
255  * Made no palette-mapped bitmaps use 0,255,0 as transparent.
256  * 
257  * 88    3/24/98 5:39p John
258  * Added debug code to show bitmap fragmentation.  Made user bitmaps
259  * allocate from top of array.
260  * 
261  * 87    3/22/98 3:28p John
262  * Added in stippled alpha for lower details.  Made medium detail use
263  * engine glow.
264  * 
265  * 86    3/11/98 1:55p John
266  * Fixed warnings
267  * 
268  * 85    3/06/98 4:09p John
269  * Changed the way we do bitmap RLE'ing... this speds up HUD bitmaps by
270  * about 2x
271  * 
272  * 84    3/02/98 6:00p John
273  * Moved MAX_BITMAPS into BmpMan.h so the stuff in the graphics code that
274  * is dependent on it won't break if it changes.   Made ModelCache slots
275  * be equal to MAX_OBJECTS which is what it is.
276  * 
277  * 83    3/02/98 9:51a John
278  * Added code to print the number of bitmap slots in use between levels.
279  * 
280  * 82    2/16/98 3:54p John
281  * Changed a bunch of mprintfs to catagorize to BmpInfo
282  * 
283  * 81    2/13/98 5:00p John
284  * Made user bitmaps not get wrote to level cache file.
285  * 
286  * 80    2/06/98 8:25p John
287  * Added code for new bitmaps since last frame
288  * 
289  * 79    2/06/98 8:10p John
290  * Added code to show amout of texture usage each frame.
291  * 
292  * 78    2/05/98 9:21p John
293  * Some new Direct3D code.   Added code to monitor a ton of stuff in the
294  * game.
295  * 
296  * 77    1/29/98 11:48a John
297  * Added new counter measure rendering as model code.   Made weapons be
298  * able to have impact explosion.
299  * 
300  * 76    1/28/98 6:19p Dave
301  * Reduced standalone memory usage ~8 megs. Put in support for handling
302  * multiplayer submenu handling for endgame, etc.
303  * 
304  * 75    1/17/98 12:55p John
305  * Fixed bug that I just created that loaded all ani frames.
306  * 
307  * 74    1/17/98 12:33p John
308  * Made the game_busy function be called a constant amount of times per
309  * level load, making the bar prediction easier.
310  * 
311  * 73    1/17/98 12:14p John
312  * Added loading... bar to freespace.
313  * 
314  * 72    1/11/98 3:20p John
315  * Made so that if no .clt exists, it will load all the bitmaps
316  * 
317  * 71    1/11/98 3:06p John
318  * Made bitmap loading stop when cache gets full.
319  * 
320  * 70    1/11/98 2:45p John
321  * Changed .lst to .clt
322  * 
323  * 69    1/11/98 2:14p John
324  * Changed a lot of stuff that had to do with bitmap loading.   Made cfile
325  * not do callbacks, I put that in global code.   Made only bitmaps that
326  * need to load for a level load.
327  * 
328  * 67    1/09/98 4:07p John
329  * Made all bitmap functions return a bitmap "Handle" not number.  This
330  * helps to find bm_release errors.
331  * 
332  * 66    1/09/98 1:38p John
333  * Fixed some bugs from previous comment
334  * 
335  * 65    1/09/98 1:32p John
336  * Added some debugging code to track down a weird error.  Namely I fill
337  * in the be structure with bogus values when someone frees it.
338  * 
339  * 64    12/28/97 2:00p John
340  * put in another assert checking for invalid lock/unlock sequencing
341  * 
342  * 63    12/24/97 2:02p John
343  * Changed palette translation to be a little faster for unoptimized
344  * builds
345  * 
346  * 62    12/18/97 8:59p Dave
347  * Finished putting in basic support for weapon select and ship select in
348  * multiplayer.
349  * 
350  * 61    12/15/97 10:27p John
351  * fixed bug where 2 bm_loads of same file both open the header.
352  * 
353  * 60    12/08/97 2:17p John
354  * fixed bug with bmpman and cf_callback.
355  * made cf_callback in Freespace set small font back when done.
356  * 
357  * 59    12/03/97 5:01p Lawrance
358  * bump up MAX_BITMAPS to 1500.  People have reached 1000 bitmaps while
359  * playing multiple missions.
360  * 
361  * 58    12/02/97 3:59p John
362  * Added first rev of thruster glow, along with variable levels of
363  * translucency, which retquired some restructing of palman.
364  * 
365  * 57    11/30/97 3:57p John
366  * Made fixed 32-bpp translucency.  Made BmpMan always map translucent
367  * color into 255 even if you aren't supposed to remap and make it's
368  * palette black.
369  * 
370  * 56    10/05/97 10:39a John
371  * fixed bug with palette on unmapped bitmaps.  Made unmapped bitmaps get
372  * marked with xparent.
373  * 
374  * 55    9/23/97 11:46a Lawrance
375  * fixed bug with rle'ing with spans get big
376  * 
377  * 54    9/23/97 10:45a John
378  * made so you can tell bitblt code to rle a bitmap by passing flag to
379  * gr_set_bitmap
380  * 
381  * 53    9/19/97 10:18a John
382  * fixed bug with aa animations being re-rle'd every 
383  * frame.
384  * 
385  * 
386  * 52    9/09/97 10:08a Sandeep
387  * Fixed Compiler Level 4 warnings
388  * 
389  * 51    9/08/97 2:02p John
390  * fixed typo in nprintf
391  * 
392  * 50    9/08/97 1:56p John
393  * fixed some memory housekeeping bugs 
394  * 
395  * 49    9/03/97 4:19p John
396  * changed bmpman to only accept ani and pcx's.  made passing .pcx or .ani
397  * to bm_load functions not needed.   Made bmpman keep track of palettes
398  * for bitmaps not mapped into game palettes.
399  * 
400  * 48    8/29/97 7:35p Lawrance
401  * check if .ani animation is already loaded in bm_load_animation()
402  * 
403  * 47    8/25/97 11:14p Lawrance
404  * added support for .ani files in bm_load_animation()
405  * 
406  * 46    8/17/97 2:42p Lawrance
407  * only flag PCX files as xparent if they have xparent pixels in them
408  * 
409  * 45    8/15/97 9:57a Lawrance
410  * support multiple xparent entries for PCX files
411  * 
412  * 44    8/05/97 10:18a Lawrance
413  * my_rand() being used temporarily instead of rand()
414  * 
415  * 43    8/01/97 4:30p John
416  * 
417  * 42    7/29/97 8:34a John
418  * took out png stuff
419  * 
420  * 41    7/18/97 3:27p Lawrance
421  * have pcx files use (0,255,0) for transparency
422  * 
423  * 40    7/16/97 3:07p John
424  * 
425  * 39    7/10/97 8:34a John
426  * Added code to read TGA files.
427  * 
428  * 38    6/20/97 1:50p John
429  * added rle code to bmpman.  made gr8_aabitmap use it.
430  * 
431  * 37    6/18/97 12:07p John
432  * fixed some color bugs
433  * 
434  * 36    6/17/97 8:58p Lawrance
435  * fixed bug with not nulling bm.data with USER bitmaps
436  * 
437  * 35    6/12/97 2:44a Lawrance
438  * changed bm_unlock() to take an index into bm_bitmaps().  Added
439  * ref_count to bitmap_entry struct
440  * 
441  * 34    5/20/97 10:36a John
442  * Fixed problem with user bitmaps and direct3d caching.
443  * 
444  * 33    5/14/97 1:59p John
445  * fixed a palette bug with vclips.
446  * 
447  * 32    3/24/97 4:43p John
448  * speed up chunked collision detection by only checking cubes the vector
449  * goes through.
450  * 
451  * 31    3/24/97 3:25p John
452  * Cleaned up and restructured model_collide code and fvi code.  In fvi
453  * made code that finds uvs work..  Added bm_get_pixel to BmpMan.
454  * 
455  * 30    3/11/97 2:49p Allender
456  * 
457  * 29    2/18/97 9:43a Lawrance
458  * added SDL_assert() in bm_release
459  * 
460  * 28    1/22/97 4:29p John
461  * maybe fixed bug with code that counts total bytes of texture ram used.
462  * 
463  * 27    1/22/97 4:19p Lawrance
464  * added flags to bm_create to allow transparency
465  * 
466  * 26    1/21/97 5:24p John
467  * fixed another bug with bm_release.
468  * 
469  * 25    1/21/97 5:12p John
470  * fixed bug with case
471  * 
472  * 24    1/21/97 5:02p John
473  * Added code for 8bpp user bitmaps.
474  * 
475  * 23    1/09/97 11:35a John
476  * Added some 2d functions to get/put screen images.
477  * 
478  * 22    11/26/96 6:50p John
479  * Added some more hicolor primitives.  Made windowed mode run as current
480  * bpp, if bpp is 8,16,or 32.
481  * 
482  * 21    11/26/96 9:44a Allender
483  * Allow for use of different bitmap palettes
484  * 
485  * 20    11/25/96 10:36a Allender
486  * started working on 32 bpp support.  Added 15 bpp.
487  * 
488  * 19    11/18/96 1:51p Allender
489  * fix up manager code to reread bitmaps if needed in newer bit depth
490  * 
491  * 18    11/15/96 4:24p Allender
492  * more bmpman stuff -- only free bitmap slots when releasing copied
493  * texture -- otherwise, only release the data for the bitmap
494  * 
495  * 17    11/15/96 3:33p Allender
496  * added support for converting to 16 bit textures when requested with
497  * bm_load.  Added some other management functions
498  * 
499  * 16    11/13/96 4:51p Allender
500  * started overhaul of bitmap manager.  bm_load no longer actually load
501  * the data, only the info for the bitmap.  Locking the bitmap now forces
502  * load when no data present (or will if bpp changes)
503  *
504  * $NoKeywords: $
505  */
506
507 #include <ctype.h>
508 #include "pstypes.h"
509 #include "pcxutils.h"
510 #include "bmpman.h"
511 #include "palman.h"
512 #include "2d.h"
513 #include "animplay.h"
514 #include "timer.h"
515 #include "systemvars.h"
516 #include "key.h"
517 #include "packunpack.h"
518 #include "cfile.h"
519 #include "grinternal.h"
520 #include "tgautils.h"
521 #include "ship.h"
522
523 #ifndef NDEBUG
524 #define BMPMAN_NDEBUG
525 #endif
526
527 // keep this defined to use per-ship nondarkening pixels
528 #define BMPMAN_SPECIAL_NONDARK
529
530 int bm_inited = 0;
531
532 #define BM_TYPE_NONE            0
533 #define BM_TYPE_PCX                     1
534 #define BM_TYPE_USER            2
535 #define BM_TYPE_ANI                     3               // in-house ANI format
536 #define BM_TYPE_TGA                     4               // 16 bit targa
537
538 typedef union bm_extra_info     {
539         struct {
540                 // Stuff needed for animations
541                 int             first_frame;                                                            // used for animations -- points to index of first frame
542                 ubyte           num_frames;                                                                     // used for animation -- number of frames in the animation
543                 ubyte           fps;                                                                                    // used for animation -- frames per second
544         } ani;
545         struct {
546                 // Stuff needed for user bitmaps
547                 void            *data;                                                                  // For user bitmaps, this is where the data comes from
548                 ubyte           bpp;                                                                    // For user bitmaps, this is what format the data is
549                 ubyte           flags;                                                                  // Flags passed to bm_create
550         } user;
551 } bm_extra_info;
552
553 typedef struct bitmap_entry     {
554         // identification
555         char            filename[MAX_FILENAME_LEN];                     // filename for this bitmap
556
557         uint            signature;                                                                      // a unique signature identifying the data
558         uint            palette_checksum;                                                       // checksum used to be sure bitmap is in current palette
559         int             handle;                                                                         // Handle = id*MAX_BITMAPS + bitmapnum
560         int             last_used;                                                                      // When this bitmap was last used
561
562         ubyte           type;                                                                                   // PCX, USER, ANI, etc
563         signed char     ref_count;                                                              // Number of locks on bitmap.  Can't unload unless ref_count is 0.
564
565         // Stuff to keep track of usage
566         ubyte           preloaded;                                                                      // If set, then this was loaded from the lst file
567         ubyte           used_flags;                                                                     // What flags it was accessed thru
568
569         // Bitmap info
570         bitmap  bm;
571
572         // Data for animations and user bitmaps
573         bm_extra_info   info;           
574
575 #ifdef BMPMAN_NDEBUG
576         // bookeeping
577         ubyte           used_last_frame;                                                        // If set, then it was used last frame
578         ubyte           used_this_frame;                                                        // If set, then it was used this frame
579         int             data_size;                                                                      // How much data this bitmap uses
580         int             used_count;                                                                     // How many times it was accessed
581 #endif
582 } bitmap_entry;
583
584 uint Bm_next_signature = 0x1234;
585
586 bitmap_entry bm_bitmaps[MAX_BITMAPS];
587
588 int bm_texture_ram = 0;
589
590 // Bm_max_ram - How much RAM bmpman can use for textures.
591 // Set to <1 to make it use all it wants.
592 int Bm_max_ram = 0;             //16*1024*1024;                 // Only use 16 MB for textures
593
594 int bm_next_handle = 1;
595
596 int Bm_paging = 0;
597
598 static int Bm_low_mem = 0;                      
599
600
601 // ===========================================
602 // Mode: 0 = High memory
603 //       1 = Low memory ( every other frame of ani's)
604 //       2 = Debug low memory ( only use first frame of each ani )
605 void bm_set_low_mem( int mode )
606 {
607         SDL_assert( (mode >= 0)  && (mode<=2 ));
608         Bm_low_mem = mode;
609 }
610
611
612 static int bm_get_next_handle()
613 {
614         int n = bm_next_handle;
615         bm_next_handle++;
616         if ( bm_next_handle > 30000 )   {
617                 bm_next_handle = 1;
618         }
619         return n;
620 }
621
622 // Frees a bitmaps data if it should, and
623 // Returns true if bitmap n can free it's data.
624 static void bm_free_data(int n)
625 {
626         bitmap_entry    *be;
627         bitmap                  *bmp;
628
629         SDL_assert( n >= 0 && n < MAX_BITMAPS );
630
631         be = &bm_bitmaps[n];
632         bmp = &be->bm;
633
634         // If there isn't a bitmap in this structure, don't
635         // do anything but clear out the bitmap info
636         if ( be->type==BM_TYPE_NONE) 
637                 goto SkipFree;
638
639         // If this bitmap doesn't have any data to free, skip
640         // the freeing it part of this.
641         if ( bmp->data == 0 ) 
642                 goto SkipFree;
643
644         // Don't free up memory for user defined bitmaps, since
645         // BmpMan isn't the one in charge of allocating/deallocing them.
646         if ( ( be->type==BM_TYPE_USER ) )       
647                 goto SkipFree;
648
649         // Free up the data now!
650
651         //      mprintf(( "Bitmap %d freed %d bytes\n", n, bm_bitmaps[n].data_size ));
652         #ifdef BMPMAN_NDEBUG
653                 bm_texture_ram -= be->data_size;
654         #endif
655         free((void *)bmp->data);
656
657 SkipFree:
658
659         // Clear out & reset the bitmap data structure
660         bmp->flags = 0;
661         bmp->bpp = 0;
662         bmp->data = 0;
663         bmp->palette = NULL;
664         #ifdef BMPMAN_NDEBUG
665                 be->data_size = 0;
666         #endif
667         be->signature = Bm_next_signature++; 
668 }
669
670
671 #ifdef BMPMAN_NDEBUG
672
673 int Bm_ram_freed = 0;
674
675 static void bm_free_some_ram( int n, int size )
676 {
677 /*
678         if ( Bm_max_ram < 1 ) return;
679         if ( bm_texture_ram + size < Bm_max_ram ) return;
680
681         int current_time = timer_get_milliseconds();
682
683         while( bm_texture_ram + size > Bm_max_ram )     {
684                 Bm_ram_freed++;
685
686                 // Need to free some RAM up!
687                 int i, oldest=-1, best_val=0;
688                 for (i = 0; i < MAX_BITMAPS; i++)       {
689                         if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && (bm_bitmaps[i].first_frame!=bm_bitmaps[n].first_frame) && (bm_bitmaps[i].ref_count==0) && (bm_bitmaps[i].data_size>0) )    {
690                                 int page_func = ( current_time-bm_bitmaps[i].last_used)*bm_bitmaps[i].data_size;
691                                 if ( (oldest==-1) || (page_func>best_val) )     {
692                                         oldest=i;
693                                         best_val = page_func;
694                                 }
695                         }
696                 }
697
698                 if ( oldest > -1 )      {
699                         //mprintf(( "Freeing bitmap '%s'\n", bm_bitmaps[oldest].filename ));
700                         for (i=0; i<bm_bitmaps[oldest].num_frames; i++ )        {
701                                 bm_free_data(bm_bitmaps[oldest].first_frame+i);
702                         }
703                 } else {
704                         //mprintf(( "Couldn't free enough! %d\n", bm_texture_ram ));
705                         break;
706                 }
707         }       
708 */
709 }
710
711 #endif
712
713 static void *bm_malloc( int n, int size )
714 {
715         SDL_assert( n >= 0 && n < MAX_BITMAPS );
716 //      mprintf(( "Bitmap %d allocated %d bytes\n", n, size ));
717         #ifdef BMPMAN_NDEBUG
718         bm_free_some_ram( n, size );
719         SDL_assert( bm_bitmaps[n].data_size == 0 );
720         bm_bitmaps[n].data_size += size;
721         bm_texture_ram += size;
722         #endif
723         return malloc(size);
724 }
725
726 void bm_close()
727 {
728         int i;
729         if ( bm_inited )        {
730                 for (i=0; i<MAX_BITMAPS; i++ )  {
731                         bm_free_data(i);                        // clears flags, bbp, data, etc
732                 }
733                 bm_inited = 0;
734         }
735 }
736
737
738 void bm_init()
739 {
740         int i;
741
742         mprintf(( "Size of bitmap info = %d KB\n", sizeof( bm_bitmaps )/1024 ));
743         mprintf(( "Size of bitmap extra info = %d bytes\n", sizeof( bm_extra_info ) ));
744         
745         if (!bm_inited) {
746                 bm_inited = 1;
747                 atexit(bm_close);
748         }
749         
750         for (i=0; i<MAX_BITMAPS; i++ ) {
751                 bm_bitmaps[i].filename[0] = '\0';
752                 bm_bitmaps[i].type = BM_TYPE_NONE;
753                 bm_bitmaps[i].info.user.data = NULL;
754                 bm_bitmaps[i].bm.data = 0;
755                 bm_bitmaps[i].bm.palette = NULL;
756                 #ifdef BMPMAN_NDEBUG
757                         bm_bitmaps[i].data_size = 0;
758                         bm_bitmaps[i].used_count = 0;
759                         bm_bitmaps[i].used_last_frame = 0;
760                         bm_bitmaps[i].used_this_frame = 0;
761                 #endif
762                 bm_free_data(i);        // clears flags, bbp, data, etc
763         }
764
765
766 }
767
768 #ifdef BMPMAN_NDEBUG
769
770 // Returns number of bytes of bitmaps locked this frame
771 // ntotal = number of bytes of bitmaps locked this frame
772 // nnew = number of bytes of bitmaps locked this frame that weren't locked last frame
773 void bm_get_frame_usage(int *ntotal, int *nnew)
774 {
775         int i;
776         
777         *ntotal = 0;
778         *nnew = 0;
779
780         for (i=0; i<MAX_BITMAPS; i++ ) {
781                 if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && (bm_bitmaps[i].used_this_frame))   {
782                         if ( !bm_bitmaps[i].used_last_frame )   {
783                                 *nnew += bm_bitmaps[i].bm.w*bm_bitmaps[i].bm.h; 
784                         }
785                         *ntotal += bm_bitmaps[i].bm.w*bm_bitmaps[i].bm.h;
786                 }
787                 bm_bitmaps[i].used_last_frame = bm_bitmaps[i].used_this_frame;
788                 bm_bitmaps[i].used_this_frame = 0;
789         }
790
791 }
792 #else
793 void bm_get_frame_usage(int *ntotal, int *nnew)
794 {
795 }
796 #endif
797
798 // given a loaded bitmap with valid info, calculate sections
799 void bm_calc_sections(bitmap *be)
800 {
801         int idx;
802
803         if (gr_screen.use_sections) {
804                 // number of x and y sections
805                 be->sections.num_x = (ubyte)(be->w / MAX_BMAP_SECTION_SIZE);
806                 if((be->sections.num_x * MAX_BMAP_SECTION_SIZE) < be->w){
807                         be->sections.num_x++;
808                 }
809                 be->sections.num_y = (ubyte)(be->h / MAX_BMAP_SECTION_SIZE);
810                 if((be->sections.num_y * MAX_BMAP_SECTION_SIZE) < be->h){
811                         be->sections.num_y++;
812                 }
813
814                 // calculate the offsets for each section
815                 for(idx=0; idx<be->sections.num_x; idx++){
816                         be->sections.sx[idx] = (ushort)(MAX_BMAP_SECTION_SIZE * idx);
817                 }
818                 for(idx=0; idx<be->sections.num_y; idx++){
819                         be->sections.sy[idx] = (ushort)(MAX_BMAP_SECTION_SIZE * idx);
820                 }
821         } else {
822                 be->sections.num_x = 1;
823                 be->sections.num_y = 1;
824
825                 be->sections.sx[0] = 0;
826                 be->sections.sy[0] = 0;
827         }
828 }
829
830 // Creates a bitmap that exists in RAM somewhere, instead
831 // of coming from a disk file.  You pass in a pointer to a
832 // block of 32 (or 8)-bit-per-pixel data.  Right now, the only
833 // bpp you can pass in is 32 or 8.  On success, it returns the
834 // bitmap number.  You cannot free that RAM until bm_release
835 // is called on that bitmap.
836 int bm_create( int bpp, int w, int h, void *data, int flags )
837 {
838         int i, n, first_slot = MAX_BITMAPS;
839
840         if (data == NULL) {
841                 Int3();
842                 return -1;
843         }
844
845         // SDL_assert((bpp==32)||(bpp==8));
846         if(bpp != 16){
847                 SDL_assert(flags & BMP_AABITMAP);
848         } else {
849                 SDL_assert(bpp == 16);
850         }
851
852         if ( !bm_inited ) bm_init();
853
854         for (i = MAX_BITMAPS-1; i >= 0; i-- ) {
855                 if ( bm_bitmaps[i].type == BM_TYPE_NONE )       {
856                         first_slot = i;
857                         break;
858                 }
859         }
860
861         n = first_slot;
862         SDL_assert( n > -1 );
863
864         // Out of bitmap slots
865         if ( n == -1 ) return -1;
866
867         memset( &bm_bitmaps[n], 0, sizeof(bitmap_entry) );
868
869         sprintf( bm_bitmaps[n].filename, "TMP%dx%d", w, h );
870         bm_bitmaps[n].type = BM_TYPE_USER;
871         bm_bitmaps[n].palette_checksum = 0;
872
873         bm_bitmaps[n].bm.w = short(w);
874         bm_bitmaps[n].bm.h = short(h);
875         bm_bitmaps[n].bm.rowsize = short(w);
876         bm_bitmaps[n].bm.bpp = (unsigned char)(bpp);
877         bm_bitmaps[n].bm.flags = 0;
878         bm_bitmaps[n].bm.flags |= flags;
879         bm_bitmaps[n].bm.data = 0;
880         bm_bitmaps[n].bm.palette = NULL;
881
882         bm_bitmaps[n].info.user.bpp = ubyte(bpp);
883         bm_bitmaps[n].info.user.data = data;
884         bm_bitmaps[n].info.user.flags = ubyte(flags);
885
886         bm_bitmaps[n].signature = Bm_next_signature++;
887
888         bm_bitmaps[n].handle = bm_get_next_handle()*MAX_BITMAPS + n;
889         bm_bitmaps[n].last_used = -1;
890
891         // fill in section info
892         bm_calc_sections(&bm_bitmaps[n].bm);
893         
894         return bm_bitmaps[n].handle;
895 }
896
897 // sub helper function. Given a raw filename and an extension, try and find the bitmap
898 // returns -1 if it could not be found
899 //          0 if it was found as a file
900 //          1 if it already exists, fills in handle
901 int Bm_ignore_duplicates = 0;
902 int bm_load_sub(const char *real_filename, const char *ext, int *handle)
903 {       
904         int i;
905         char filename[MAX_FILENAME_LEN] = "";
906         
907         strcpy( filename, real_filename );
908         strcat( filename, ext );        
909         for (i=0; i<(int)strlen(filename); i++ ){
910                 filename[i] = char(tolower(filename[i]));
911         }               
912
913         // try to find given filename to see if it has been loaded before
914         if(!Bm_ignore_duplicates){
915                 for (i = 0; i < MAX_BITMAPS; i++) {
916                         if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && !SDL_strcasecmp(filename, bm_bitmaps[i].filename) ) {
917                                 nprintf (("BmpMan", "Found bitmap %s -- number %d\n", filename, i));
918                                 *handle = bm_bitmaps[i].handle;
919                                 return 1;
920                         }
921                 }       
922         }
923
924         // try and find the file
925         /*
926         CFILE *test = cfopen(filename, "rb");
927         if(test != NULL){
928                 cfclose(test);
929                 return 0;
930         }
931         */
932
933         // could not be found
934         return 0;
935 }
936
937 // This loads a bitmap so we can draw with it later.
938 // It returns a negative number if it couldn't load
939 // the bitmap.   On success, it returns the bitmap
940 // number.  Function doesn't acutally load the data, only
941 // width, height, and possibly flags.
942 int bm_load( const char * real_filename )
943 {
944         int i, n, first_slot = MAX_BITMAPS;
945         int w, h, bpp;
946         char filename[MAX_FILENAME_LEN];
947         int tga = 0;
948         int handle;
949         int found = 0;
950
951         if ( !bm_inited ) bm_init();
952
953         // nice little trick for keeping standalone memory usage way low - always return a bogus bitmap 
954         if(Game_mode & GM_STANDALONE_SERVER){
955                 strcpy(filename,"test128");
956         }
957
958         // make sure no one passed an extension
959         strcpy( filename, real_filename );
960         char *p = strchr( filename, '.' );
961         if ( p ) {
962                 mprintf(( "Someone passed an extension to bm_load for file '%s'\n", real_filename ));
963                 //Int3();
964                 *p = 0;
965         }
966          
967         // try and find the pcx file            
968         switch(bm_load_sub(filename, ".pcx", &handle)){
969         // error
970         case -1:
971                 break;
972
973         // found as a file
974         case 0:
975                 found = 1;
976                 strcat(filename, ".pcx");
977                 break;
978
979         // found as pre-existing
980         case 1:
981                 found = 1;
982                 return handle;          
983         }
984
985         if(!found){
986                 // try and find the tga file
987                 switch(bm_load_sub(filename, ".tga", &handle)){
988                 // error
989                 case -1:                        
990                         return -1;
991                         break;
992
993                 // found as a file
994                 case 0:                 
995                         strcat(filename, ".tga");
996                         tga = 1;
997                         break;
998
999                 // found as pre-existing
1000                 case 1:                                         
1001                         return handle;                                  
1002                 }
1003         }
1004
1005         // if its a tga file
1006         if(tga){
1007                 int tga_error=targa_read_header( filename, &w, &h, &bpp, NULL );
1008                 if ( tga_error != TARGA_ERROR_NONE )    {
1009                         mprintf(( "Couldn't open '%s'\n", filename ));
1010                         return -1;
1011                 }
1012         }
1013         // if its a pcx file
1014         else {
1015                 int pcx_error=pcx_read_header( filename, &w, &h, NULL );                
1016                 if ( pcx_error != PCX_ERROR_NONE )      {
1017                         mprintf(( "Couldn't open '%s'\n", filename ));
1018                         return -1;
1019                 }
1020         }
1021
1022         // Error( LOCATION, "Unknown bitmap type %s\n", filename );
1023                 
1024         // Find an open slot
1025         for (i = 0; i < MAX_BITMAPS; i++) {
1026                 if ( (bm_bitmaps[i].type == BM_TYPE_NONE) && (first_slot == MAX_BITMAPS) ){
1027                         first_slot = i;
1028                 }
1029         }
1030
1031         n = first_slot;
1032         SDL_assert( n < MAX_BITMAPS );  
1033
1034         if ( n == MAX_BITMAPS ) return -1;      
1035
1036         // ensure fields are cleared out from previous bitmap
1037 //      SDL_assert(bm_bitmaps[n].bm.data == 0);
1038 //      SDL_assert(bm_bitmaps[n].bm.palette == NULL);
1039 //      SDL_assert(bm_bitmaps[n].ref_count == 0 );
1040 //      SDL_assert(bm_bitmaps[n].user_data == NULL);
1041         memset( &bm_bitmaps[n], 0, sizeof(bitmap_entry) );
1042         
1043         // Mark the slot as filled, because cf_read might load a new bitmap
1044         // into this slot.
1045         bm_bitmaps[n].type = tga ? (ubyte)BM_TYPE_TGA : (ubyte)BM_TYPE_PCX;
1046         bm_bitmaps[n].signature = Bm_next_signature++;
1047         SDL_assert ( strlen(filename) < MAX_FILENAME_LEN );
1048         strncpy(bm_bitmaps[n].filename, filename, MAX_FILENAME_LEN-1 );
1049         bm_bitmaps[n].bm.w = short(w);
1050         bm_bitmaps[n].bm.rowsize = short(w);
1051         bm_bitmaps[n].bm.h = short(h);
1052         bm_bitmaps[n].bm.bpp = 0;
1053         bm_bitmaps[n].bm.flags = 0;
1054         bm_bitmaps[n].bm.data = 0;
1055         bm_bitmaps[n].bm.palette = NULL;
1056
1057         bm_bitmaps[n].palette_checksum = 0;
1058         bm_bitmaps[n].handle = bm_get_next_handle()*MAX_BITMAPS + n;
1059         bm_bitmaps[n].last_used = -1;
1060
1061         // fill in section info
1062         bm_calc_sections(&bm_bitmaps[n].bm);
1063
1064         return bm_bitmaps[n].handle;
1065 }
1066
1067 // special load function. basically allows you to load a bitmap which already exists (by filename). 
1068 // this is useful because in some cases we need to have a bitmap which is locked in screen format
1069 // _and_ texture format, such as pilot pics and squad logos
1070 int bm_load_duplicate(const char *filename)
1071 {
1072         int ret;
1073
1074         // ignore duplicates
1075         Bm_ignore_duplicates = 1;
1076         
1077         // load
1078         ret = bm_load(filename);
1079
1080         // back to normal
1081         Bm_ignore_duplicates = 0;
1082
1083         return ret;
1084 }
1085
1086 DCF(bm_frag,"Shows BmpMan fragmentation")
1087 {
1088         if ( Dc_command )       {
1089
1090                 gr_clear();
1091
1092                 int x=0, y=0;
1093                 int xs=2, ys=2;
1094                 int w=4, h=4;
1095
1096                 for (int i=0; i<MAX_BITMAPS; i++ )      {
1097                         switch( bm_bitmaps[i].type )    {
1098                         case BM_TYPE_NONE:
1099                                 gr_set_color(128,128,128);
1100                                 break;
1101                         case BM_TYPE_PCX:
1102                                 gr_set_color(255,0,0);
1103                                 break;
1104                         case BM_TYPE_USER:
1105                                 gr_set_color(0,255,0);
1106                                 break;
1107                         case BM_TYPE_ANI:
1108                                 gr_set_color(0,0,255);
1109                                 break;
1110                         }
1111
1112                         gr_rect( x+xs, y+ys, w, h );
1113                         x += w+xs+xs;
1114                         if ( x > 639 )  {
1115                                 x = 0;
1116                                 y += h + ys + ys;
1117                         }
1118
1119                 }
1120
1121                 gr_flip();
1122                 key_getch();
1123         }
1124 }
1125
1126 static int find_block_of(int n)
1127 {
1128         int i, cnt, nstart;
1129
1130         cnt=0;
1131         nstart = 0;
1132         for (i=0; i<MAX_BITMAPS; i++ )  {
1133                 if ( bm_bitmaps[i].type == BM_TYPE_NONE )       {
1134                         if (cnt==0) nstart = i;
1135                         cnt++;
1136                 } else
1137                         cnt=0;
1138                 if ( cnt == n ) return nstart;
1139         }
1140
1141         // Error( LOCATION, "Couldn't find block of %d frames\n", n );
1142         return -1;
1143 }
1144
1145 // ------------------------------------------------------------------
1146 // bm_load_animation()
1147 //
1148 //      input:          filename                =>              filename of animation
1149 //                                      nframes         =>              OUTPUT parameter:       number of frames in the animation
1150 //                                      fps                     =>              OUTPUT/OPTIONAL parameter: intended fps for the animation
1151 //
1152 // returns:             bitmap number of first frame in the animation
1153 //
1154 int bm_load_animation( const char *real_filename, int *nframes, int *fps, int can_drop_frames)
1155 {
1156         int     i, n;
1157         anim    the_anim;
1158         CFILE   *fp;
1159         char filename[MAX_FILENAME_LEN];
1160
1161         if ( !bm_inited ) bm_init();
1162
1163         strcpy( filename, real_filename );
1164         char *p = strchr( filename, '.' );
1165         if ( p ) {
1166                 mprintf(( "Someone passed an extension to bm_load_animation for file '%s'\n", real_filename ));
1167                 //Int3();
1168                 *p = 0;
1169         }
1170         strcat( filename, ".ani" );
1171
1172         if ( (fp = cfopen(filename, "rb")) == NULL ) {
1173 //              Error(LOCATION,"Could not open filename %s in bm_load_ani()\n", filename);
1174                 return -1;
1175         }
1176
1177         int reduced = 0;
1178 #ifndef NDEBUG
1179         // for debug of ANI sizes
1180         strcpy(the_anim.name, real_filename);
1181 #endif
1182         anim_read_header(&the_anim, fp);
1183         if ( can_drop_frames )  {
1184                 if ( Bm_low_mem == 1 )  {
1185                         reduced = 1;
1186                         the_anim.total_frames = ( the_anim.total_frames+1)/2;
1187                 } else if ( Bm_low_mem == 2 )   {
1188                         the_anim.total_frames = 1;      
1189                 }
1190         }
1191         cfclose(fp);
1192
1193         *nframes = the_anim.total_frames;
1194         if ( fps != NULL )      {
1195                 if ( reduced )  {
1196                         *fps = the_anim.fps / 2;
1197                 } else {
1198                         *fps = the_anim.fps;
1199                 }
1200         }
1201
1202         // first check to see if this ani already has it's frames loaded
1203         for (i = 0; i < MAX_BITMAPS; i++) {
1204                 if ( (bm_bitmaps[i].type == BM_TYPE_ANI) && !SDL_strcasecmp(filename, bm_bitmaps[i].filename) ) {
1205                         break;
1206                 }
1207         }
1208         
1209         if ( i < MAX_BITMAPS ) {
1210                 // in low memory modes this can happen
1211                 if(!Bm_low_mem){
1212                         SDL_assert(bm_bitmaps[i].info.ani.num_frames == *nframes);
1213                 }
1214                 return bm_bitmaps[i].handle;
1215         }
1216
1217         n = find_block_of(*nframes);
1218         if(n < 0){
1219                 return -1;
1220         }
1221         // SDL_assert( n >= 0 );
1222
1223         int first_handle = bm_get_next_handle();
1224
1225         SDL_assert ( strlen(filename) < MAX_FILENAME_LEN );
1226         for ( i = 0; i < *nframes; i++ ) {
1227                 memset( &bm_bitmaps[n+i], 0, sizeof(bitmap_entry) );
1228                 bm_bitmaps[n+i].info.ani.first_frame = n;
1229                 bm_bitmaps[n+i].info.ani.num_frames = ubyte(the_anim.total_frames);
1230                 bm_bitmaps[n+i].info.ani.fps = ubyte(the_anim.fps);
1231                 bm_bitmaps[n+i].bm.w = short(the_anim.width);
1232                 bm_bitmaps[n+i].bm.rowsize = short(the_anim.width);
1233                 bm_bitmaps[n+i].bm.h = short(the_anim.height);
1234                 if ( reduced )  {
1235                         bm_bitmaps[n+i].bm.w /= 2;
1236                         bm_bitmaps[n+i].bm.rowsize /= 2;
1237                         bm_bitmaps[n+i].bm.h /= 2;
1238                 }
1239                 bm_bitmaps[n+i].bm.flags = 0;
1240                 bm_bitmaps[n+i].bm.bpp = 0;
1241                 bm_bitmaps[n+i].bm.data = 0;
1242                 bm_bitmaps[n+i].bm.palette = NULL;
1243                 bm_bitmaps[n+i].type = BM_TYPE_ANI;
1244                 bm_bitmaps[n+i].palette_checksum = 0;
1245                 bm_bitmaps[n+i].signature = Bm_next_signature++;
1246                 bm_bitmaps[n+i].handle = first_handle*MAX_BITMAPS + n+i;
1247                 bm_bitmaps[n+i].last_used = -1;
1248
1249                 // fill in section info
1250                 bm_calc_sections(&bm_bitmaps[n+i].bm);
1251
1252                 if ( i == 0 )   {
1253                         sprintf( bm_bitmaps[n+i].filename, "%s", filename );
1254                 } else {
1255                         sprintf( bm_bitmaps[n+i].filename, "%s[%d]", filename, i );
1256                 }
1257         }
1258
1259         return bm_bitmaps[n].handle;
1260 }
1261
1262 // Gets info.   w,h,or flags,nframes or fps can be NULL if you don't care.
1263 void bm_get_info( int handle, int *w, int * h, ubyte * flags, int *nframes, int *fps, bitmap_section_info **sections )
1264 {
1265         bitmap * bmp;
1266
1267         if ( !bm_inited ) return;
1268
1269         int bitmapnum = handle % MAX_BITMAPS;
1270         SDL_assert( bm_bitmaps[bitmapnum].handle == handle );           // INVALID BITMAP HANDLE!       
1271         
1272         if ( (bm_bitmaps[bitmapnum].type == BM_TYPE_NONE) || (bm_bitmaps[bitmapnum].handle != handle) ) {
1273                 if (w) *w = 0;
1274                 if (h) *h = 0;
1275                 if (flags) *flags = 0;
1276                 if (nframes) *nframes=0;
1277                 if (fps) *fps=0;
1278                 if (sections != NULL) *sections = NULL;
1279                 return;
1280         }
1281
1282         bmp = &(bm_bitmaps[bitmapnum].bm);
1283
1284         if (w) *w = bmp->w;
1285         if (h) *h = bmp->h;
1286         if (flags) *flags = bmp->flags;
1287         if ( bm_bitmaps[bitmapnum].type == BM_TYPE_ANI )        {
1288                 if (nframes) {
1289                         *nframes = bm_bitmaps[bitmapnum].info.ani.num_frames;
1290                 } 
1291                 if (fps) {
1292                         *fps= bm_bitmaps[bitmapnum].info.ani.fps;
1293                 }
1294         } else {
1295                 if (nframes) {
1296                         *nframes = 1;
1297                 } 
1298                 if (fps) {
1299                         *fps= 0;
1300                 }
1301         }
1302         if(sections != NULL){
1303                 *sections = &bm_bitmaps[bitmapnum].bm.sections;
1304         }
1305 }
1306
1307 uint bm_get_signature( int handle )
1308 {
1309         if ( !bm_inited ) bm_init();
1310
1311         int bitmapnum = handle % MAX_BITMAPS;
1312         SDL_assert( bm_bitmaps[bitmapnum].handle == handle );           // INVALID BITMAP HANDLE
1313
1314         return bm_bitmaps[bitmapnum].signature;
1315 }
1316
1317 extern int palman_is_nondarkening(int r,int g, int b);
1318 static void bm_convert_format( int bitmapnum, bitmap *bmp, ubyte bpp, ubyte flags )
1319 {       
1320         int idx;        
1321         int r, g, b, a;
1322
1323         if(Fred_running || Pofview_running || Is_standalone){
1324                 SDL_assert(bmp->bpp == 8);
1325
1326                 return;
1327         } else {
1328                 if(flags & BMP_AABITMAP){
1329                         SDL_assert(bmp->bpp == 8);
1330                 } else {
1331                         SDL_assert(bmp->bpp == 16);
1332                 }
1333         }
1334
1335         // maybe swizzle to be an xparent texture
1336         if(!(bmp->flags & BMP_TEX_XPARENT) && (flags & BMP_TEX_XPARENT)){
1337                 for(idx=0; idx<bmp->w*bmp->h; idx++){                   
1338                         
1339                         // if the pixel is transparent
1340                         if ( ((ushort*)bmp->data)[idx] == Gr_t_green.mask)      {
1341                                 ((ushort*)bmp->data)[idx] = 0;
1342                         }
1343                 }
1344
1345                 bmp->flags |= BMP_TEX_XPARENT;
1346         }       
1347 }
1348
1349 // basically, map the bitmap into the current palette. used to be done for all pcx's, now just for
1350 // Fred, since its the only thing that uses the software tmapper
1351 void bm_swizzle_8bit_for_fred(bitmap_entry *be, bitmap *bmp, ubyte *data, ubyte *palette)
1352 {               
1353         int pcx_xparent_index = -1;
1354         int i;
1355         int r, g, b;
1356         ubyte palxlat[256];
1357
1358         for (i=0; i<256; i++ ) {
1359                 r = palette[i*3];
1360                 g = palette[i*3+1];
1361                 b = palette[i*3+2];
1362                 if ( g == 255 && r == 0 && b == 0 ) {
1363                         palxlat[i] = 255;
1364                         pcx_xparent_index = i;
1365                 } else {                        
1366                         palxlat[i] = (ubyte)(palette_find( r, g, b ));                  
1367                 }
1368         }               
1369         for (i=0; i<bmp->w * bmp->h; i++ ) {            
1370                 ubyte c = palxlat[data[i]];                     
1371                 data[i] = c;            
1372         }                       
1373         be->palette_checksum = gr_palette_checksum;     
1374 }
1375
1376 void bm_lock_pcx( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1377 {       
1378         ubyte *data, *palette;
1379         ubyte pal[768];
1380         palette = NULL;
1381
1382         // Unload any existing data
1383         bm_free_data( bitmapnum );      
1384
1385         // allocate bitmap data
1386         if(bpp == 8){
1387                 // SDL_assert(Fred_running || Pofview_running || Is_standalone);                
1388                         data = (ubyte *)bm_malloc(bitmapnum, bmp->w * bmp->h );
1389                 #ifdef BMPMAN_NDEBUG
1390                         SDL_assert( be->data_size == bmp->w * bmp->h );
1391                 #endif
1392                 palette = pal;
1393                 bmp->data = (ptr_u)data;
1394                 bmp->bpp = 8;
1395                 bmp->palette = gr_palette;
1396                 memset( data, 0, bmp->w * bmp->h);
1397         } else {
1398                 data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 2);       
1399                 bmp->bpp = 16;
1400                 bmp->data = (ptr_u)data;
1401                 bmp->palette = NULL;
1402                 memset( data, 0, bmp->w * bmp->h * 2);
1403         }       
1404
1405         SDL_assert( &be->bm == bmp );
1406         #ifdef BMPMAN_NDEBUG
1407                 SDL_assert( be->data_size > 0 );
1408         #endif
1409
1410         // some sanity checks on flags
1411         SDL_assert(!((flags & BMP_AABITMAP) && (flags & BMP_TEX_ANY)));                                         // no aabitmap textures
1412
1413         if(bpp == 8){
1414                 int pcx_error=pcx_read_bitmap_8bpp( be->filename, data, palette );
1415                 if ( pcx_error != PCX_ERROR_NONE )      {
1416                         // Error( LOCATION, "Couldn't open '%s'\n", be->filename );
1417                         //Error( LOCATION, "Couldn't open '%s'\n", filename );
1418                         //return -1;
1419                 }
1420
1421                 // now swizzle the thing into the proper format
1422                 if(Fred_running || Pofview_running){
1423                         bm_swizzle_8bit_for_fred(be, bmp, data, palette);
1424                 }
1425         } else {        
1426                 int pcx_error;
1427
1428                 // load types
1429                 if(flags & BMP_AABITMAP){
1430                         pcx_error = pcx_read_bitmap_16bpp_aabitmap( be->filename, data );
1431                 } else {
1432                         pcx_error = pcx_read_bitmap_16bpp( be->filename, data );
1433                 }
1434                 if ( pcx_error != PCX_ERROR_NONE )      {
1435                         // Error( LOCATION, "Couldn't open '%s'\n", be->filename );
1436                         //Error( LOCATION, "Couldn't open '%s'\n", filename );
1437                         //return -1;
1438                 }
1439         }
1440
1441         #ifdef BMPMAN_NDEBUG
1442         SDL_assert( be->data_size > 0 );
1443         #endif          
1444         
1445         bmp->flags = 0; 
1446         bm_convert_format( bitmapnum, bmp, bpp, flags );
1447 }
1448
1449 void bm_lock_ani( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1450 {       
1451         anim                            *the_anim;
1452         anim_instance   *the_anim_instance;
1453         bitmap                  *bm;
1454         ubyte                           *frame_data;
1455         int                             size, i;
1456         int                             first_frame, nframes;   
1457
1458         first_frame = be->info.ani.first_frame;
1459         nframes = bm_bitmaps[first_frame].info.ani.num_frames;
1460
1461         if ( (the_anim = anim_load(bm_bitmaps[first_frame].filename)) == NULL ) {
1462                 // Error(LOCATION, "Error opening %s in bm_lock\n", be->filename);
1463         }
1464
1465         if ( (the_anim_instance = init_anim_instance(the_anim, bpp)) == NULL ) {
1466                 // Error(LOCATION, "Error opening %s in bm_lock\n", be->filename);
1467                 anim_free(the_anim);
1468         }
1469
1470         int can_drop_frames = 0;
1471
1472         if ( the_anim->total_frames != bm_bitmaps[first_frame].info.ani.num_frames )    {
1473                 can_drop_frames = 1;
1474         }
1475         bm = &bm_bitmaps[first_frame].bm;
1476         if(bpp == 16){
1477                 size = bm->w * bm->h * 2;
1478         } else {
1479                 size = bm->w * bm->h;
1480         }
1481                 
1482         for ( i=0; i<nframes; i++ )     {
1483                 be = &bm_bitmaps[first_frame+i];
1484                 bm = &bm_bitmaps[first_frame+i].bm;
1485
1486                 // Unload any existing data
1487                 bm_free_data( first_frame+i );
1488
1489                 bm->flags = 0;
1490                 // briefing editor in Fred2 uses aabitmaps (ani's) - force to 8 bit
1491                 if(Fred_running || Is_standalone){
1492                         bm->bpp = 8;
1493                 } else {
1494                         bm->bpp = bpp;
1495                 }
1496                 bm->data = (ptr_u)bm_malloc(first_frame + i, size);
1497
1498                 frame_data = anim_get_next_raw_buffer(the_anim_instance, 0 ,flags & BMP_AABITMAP ? 1 : 0, bm->bpp);
1499
1500                 if ( frame_data == NULL ) {
1501                         // Error(LOCATION,"Fatal error locking .ani file: %s\n", be->filename);
1502                 }               
1503                 
1504                 ubyte *dptr, *sptr;
1505
1506                 sptr = frame_data;
1507                 dptr = (ubyte *)bm->data;
1508
1509                 if ( (bm->w!=the_anim->width) || (bm->h!=the_anim->height) )    {
1510                         // Scale it down
1511                         // Int3();                      // not ready yet - should only be ingame
1512         
1513                         // 8 bit
1514                         if(bpp == 8){
1515                                 int w,h;
1516                                 fix u, utmp, v, du, dv;
1517
1518                                 u = v = 0;
1519
1520                                 du = ( the_anim->width*F1_0 ) / bm->w;
1521                                 dv = ( the_anim->height*F1_0 ) / bm->h;
1522                                                                                                 
1523                                 for (h = 0; h < bm->h; h++) {
1524                                         ubyte *drow = &dptr[bm->w * h];
1525                                         ubyte *srow = &sptr[f2i(v)*the_anim->width];
1526
1527                                         utmp = u;
1528
1529                                         for (w = 0; w < bm->w; w++) {
1530                                                 *drow++ = srow[f2i(utmp)];
1531                                                 utmp += du;
1532                                         }
1533                                         v += dv;
1534                                 }                       
1535                         }
1536                         // 16 bpp
1537                         else {
1538                                 int w,h;
1539                                 fix u, utmp, v, du, dv;
1540
1541                                 u = v = 0;
1542
1543                                 du = ( the_anim->width*F1_0 ) / bm->w;
1544                                 dv = ( the_anim->height*F1_0 ) / bm->h;
1545                                                                                                 
1546                                 for (h = 0; h < bm->h; h++) {
1547                                         ushort *drow = &((ushort*)dptr)[bm->w * h];
1548                                         ushort *srow = &((ushort*)sptr)[f2i(v)*the_anim->width];
1549
1550                                         utmp = u;
1551
1552                                         for (w = 0; w < bm->w; w++) {
1553                                                 *drow++ = srow[f2i(utmp)];
1554                                                 utmp += du;
1555                                         }
1556                                         v += dv;
1557                                 }                       
1558                         }                       
1559                 } else {
1560                         // 1-to-1 mapping
1561                         memcpy(dptr, sptr, size);
1562                 }               
1563
1564                 bm_convert_format( first_frame+i, bm, bpp, flags );
1565
1566                 // Skip a frame
1567                 if ( (i < nframes-1)  && can_drop_frames )      {
1568                         frame_data = anim_get_next_raw_buffer(the_anim_instance, 0, flags & BMP_AABITMAP ? 1 : 0, bm->bpp);
1569                 }
1570
1571                 //mprintf(( "Checksum = %d\n", be->palette_checksum ));
1572         }
1573
1574         free_anim_instance(the_anim_instance);
1575         anim_free(the_anim);
1576 }
1577
1578
1579 void bm_lock_user( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1580 {
1581         // int idx;     
1582         // ushort bit_16;
1583
1584         // Unload any existing data
1585         bm_free_data( bitmapnum );      
1586
1587         switch( be->info.user.bpp )     {
1588         case 16:                        // user 16 bit bitmap
1589                 bmp->bpp = bpp;
1590                 bmp->flags = be->info.user.flags;               
1591                 bmp->data = (ptr_u)be->info.user.data;                                                          
1592                 break;  
1593         
1594         case 8:                 // Going from 8 bpp to something (probably only for aabitmaps)
1595                 /*
1596                 SDL_assert(flags & BMP_AABITMAP);
1597                 bmp->bpp = 16;
1598                 bmp->data = (uint)malloc(bmp->w * bmp->h * 2);
1599                 bmp->flags = be->info.user.flags;
1600                 bmp->palette = NULL;
1601
1602                 // go through and map the pixels
1603                 for(idx=0; idx<bmp->w * bmp->h; idx++){                 
1604                         bit_16 = (ushort)((ubyte*)be->info.user.data)[idx];                     
1605                         SDL_assert(bit_16 <= 255);
1606
1607                         // stuff the final result
1608                         memcpy((char*)bmp->data + (idx * 2), &bit_16, sizeof(ushort));
1609                 }
1610                 */              
1611                 SDL_assert(flags & BMP_AABITMAP);
1612                 bmp->bpp = bpp;
1613                 bmp->flags = be->info.user.flags;               
1614                 bmp->data = (ptr_u)be->info.user.data;                                                          
1615                 break;
1616                 
1617         // default:
1618                 // Error( LOCATION, "Unhandled user bitmap conversion from %d to %d bpp", be->info.user.bpp, bmp->bpp );
1619         }
1620
1621         bm_convert_format( bitmapnum, bmp, bpp, flags );
1622 }
1623
1624 void bm_lock_tga( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1625 {
1626         ubyte *data;    
1627
1628         // Unload any existing data
1629         bm_free_data( bitmapnum );      
1630
1631         if(Fred_running || Is_standalone){
1632                 SDL_assert(bpp == 8);
1633         } else {
1634                 SDL_assert(bpp == 16);
1635         }
1636
1637         // should never try to make an aabitmap out of a targa
1638         SDL_assert(!(flags & BMP_AABITMAP));
1639
1640         // allocate bitmap data 
1641         if(bpp == 16){
1642                 data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 2);       
1643         } else {
1644                 data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h);   
1645         }
1646         bmp->bpp = bpp;
1647         bmp->data = (ptr_u)data;
1648         bmp->palette = NULL;
1649         if(bpp == 16){
1650                 memset( data, 0, bmp->w * bmp->h * 2);  
1651         } else {
1652                 memset( data, 0, bmp->w * bmp->h );     
1653         }
1654
1655         SDL_assert( &be->bm == bmp );
1656         #ifdef BMPMAN_NDEBUG
1657         SDL_assert( be->data_size > 0 );
1658         #endif
1659         
1660         int tga_error=targa_read_bitmap( be->filename, data, NULL, (bpp == 16) ? 2 : 1);
1661         if ( tga_error != TARGA_ERROR_NONE )    {
1662                 // Error( LOCATION, "Couldn't open '%s'\n", be->filename );
1663                 //Error( LOCATION, "Couldn't open '%s'\n", filename );
1664                 //return -1;
1665         }
1666
1667         #ifdef BMPMAN_NDEBUG
1668         SDL_assert( be->data_size > 0 );
1669         #endif          
1670         
1671         bmp->flags = 0; 
1672         bm_convert_format( bitmapnum, bmp, bpp, flags );
1673 }
1674
1675 MONITOR( NumBitmapPage );
1676 MONITOR( SizeBitmapPage );
1677
1678 // This locks down a bitmap and returns a pointer to a bitmap
1679 // that can be accessed until you call bm_unlock.   Only lock
1680 // a bitmap when you need it!  This will convert it into the 
1681 // appropriate format also.
1682 bitmap * bm_lock( int handle, ubyte bpp, ubyte flags )
1683 {
1684         bitmap                  *bmp;
1685         bitmap_entry    *be;
1686
1687
1688         if ( !bm_inited ) bm_init();
1689
1690         int bitmapnum = handle % MAX_BITMAPS;
1691         SDL_assert( bm_bitmaps[bitmapnum].handle == handle );           // INVALID BITMAP HANDLE
1692
1693 //      flags &= (~BMP_RLE);
1694
1695         // if we're on a standalone server, aways for it to lock to 8 bits
1696         if(Is_standalone){
1697                 bpp = 8;
1698                 flags = 0;
1699         } 
1700         // otherwise do it as normal
1701         else {
1702                 if(Fred_running || Pofview_running){
1703                         SDL_assert( bpp == 8 );
1704                         SDL_assert( (bm_bitmaps[bitmapnum].type == BM_TYPE_PCX) || (bm_bitmaps[bitmapnum].type == BM_TYPE_ANI) || (bm_bitmaps[bitmapnum].type == BM_TYPE_TGA));
1705                 } else {
1706                         if(flags & BMP_AABITMAP){
1707                                 SDL_assert( bpp == 8 );
1708                         } else {
1709                                 SDL_assert( bpp == 16 );
1710                         }
1711                 }
1712         }
1713
1714         be = &bm_bitmaps[bitmapnum];
1715         bmp = &be->bm;
1716
1717         // If you hit this assert, chances are that someone freed the
1718         // wrong bitmap and now someone is trying to use that bitmap.
1719         // See John.
1720         SDL_assert( be->type != BM_TYPE_NONE );         
1721
1722         // Increment ref count for bitmap since lock was made on it.
1723         SDL_assert(be->ref_count >= 0);
1724         be->ref_count++;                                        // Lock it before we page in data; this prevents a callback from freeing this
1725                                                                                         // as it gets read in
1726
1727         // Mark this bitmap as used this frame
1728         #ifdef BMPMAN_NDEBUG
1729         if ( be->used_this_frame < 255 )        {
1730                 be->used_this_frame++;
1731         }
1732         #endif
1733
1734         // if bitmap hasn't been loaded yet, then load it from disk
1735         // reread the bitmap from disk under certain conditions
1736         int pal_changed = 0;
1737         int rle_changed = 0;
1738         int fake_xparent_changed = 0;   
1739         if ( (bmp->data == 0) || (bpp != bmp->bpp) || pal_changed || rle_changed || fake_xparent_changed ) {
1740                 SDL_assert(be->ref_count == 1);
1741
1742                 if ( be->type != BM_TYPE_USER ) {
1743                         if ( bmp->data == 0 ) {
1744                                 nprintf (("BmpMan","Loading %s for the first time.\n", be->filename));
1745                         } else if ( bpp != bmp->bpp ) {
1746                                 nprintf (("BmpMan","Reloading %s from bitdepth %d to bitdepth %d\n", be->filename, bmp->bpp, bpp));
1747                         } else if ( pal_changed ) {
1748                                 nprintf (("BmpMan","Reloading %s to remap palette\n", be->filename));
1749                         } else if ( rle_changed )       {
1750                                 nprintf (("BmpMan","Reloading %s to change RLE.\n", be->filename));
1751                         } else if ( fake_xparent_changed )      {
1752                                 nprintf (("BmpMan","Reloading %s to change fake xparency.\n", be->filename));
1753                         }
1754                 }
1755
1756                 MONITOR_INC( NumBitmapPage, 1 );
1757                 MONITOR_INC( SizeBitmapPage, bmp->w*bmp->h );
1758
1759                 if ( !Bm_paging )       {
1760                         if ( be->type != BM_TYPE_USER ) {
1761                                 char flag_text[64];
1762                                 strcpy( flag_text, "--" );                                                      
1763                                 nprintf(( "Paging", "Loading %s (%dx%dx%dx%s)\n", be->filename, bmp->w, bmp->h, bpp, flag_text ));
1764                         }
1765                 }
1766
1767                 // select proper format
1768                 if(flags & BMP_AABITMAP){
1769                         BM_SELECT_ALPHA_TEX_FORMAT();
1770                 } else if(flags & BMP_TEX_ANY){
1771                         BM_SELECT_TEX_FORMAT();                                 
1772                 } else {
1773                         BM_SELECT_SCREEN_FORMAT();
1774                 }
1775
1776                 switch ( be->type ) {
1777                 case BM_TYPE_PCX:
1778                         bm_lock_pcx( handle, bitmapnum, be, bmp, bpp, flags );
1779                         break;
1780
1781                 case BM_TYPE_ANI: 
1782                         bm_lock_ani( handle, bitmapnum, be, bmp, bpp, flags );
1783                         break;
1784
1785                 case BM_TYPE_USER:      
1786                         bm_lock_user( handle, bitmapnum, be, bmp, bpp, flags );
1787                         break;
1788
1789                 case BM_TYPE_TGA:
1790                         bm_lock_tga( handle, bitmapnum, be, bmp, bpp, flags );
1791                         break;
1792
1793                 default:
1794                         Warning(LOCATION, "Unsupported type in bm_lock -- %d\n", be->type );
1795                         return NULL;
1796                 }               
1797
1798                 // always go back to screen format
1799                 BM_SELECT_SCREEN_FORMAT();
1800         }
1801
1802         if ( be->type == BM_TYPE_ANI ) {
1803                 int i,first = bm_bitmaps[bitmapnum].info.ani.first_frame;
1804
1805                 for ( i=0; i< bm_bitmaps[first].info.ani.num_frames; i++ )      {
1806                         // Mark all the bitmaps in this bitmap or animation as recently used
1807                         bm_bitmaps[first+i].last_used = timer_get_milliseconds();
1808
1809                         // Mark all the bitmaps in this bitmap or animation as used for the usage tracker.
1810                         #ifdef BMPMAN_NDEBUG
1811                                 bm_bitmaps[first+i].used_count++;
1812                         #endif
1813                         bm_bitmaps[first+i].used_flags = flags;
1814                 }
1815         } else {
1816                 // Mark all the bitmaps in this bitmap or animation as recently used
1817                 be->last_used = timer_get_milliseconds();
1818
1819                 // Mark all the bitmaps in this bitmap or animation as used for the usage tracker.
1820                 #ifdef BMPMAN_NDEBUG
1821                         be->used_count++;
1822                 #endif
1823                 be->used_flags = flags;
1824         }
1825
1826         return bmp;
1827 }
1828
1829 // Unlocks a bitmap
1830 //
1831 // Decrements the ref_count member of the bitmap_entry struct.  A bitmap can only be unloaded
1832 // when the ref_count is 0.
1833 //
1834 void bm_unlock( int handle )
1835 {
1836         bitmap_entry    *be;
1837         bitmap                  *bmp;
1838
1839         int bitmapnum = handle % MAX_BITMAPS;
1840         SDL_assert( bm_bitmaps[bitmapnum].handle == handle );   // INVALID BITMAP HANDLE
1841
1842         SDL_assert(bitmapnum >= 0 && bitmapnum < MAX_BITMAPS);
1843         if ( !bm_inited ) bm_init();
1844
1845         be = &bm_bitmaps[bitmapnum];
1846         bmp = &be->bm;
1847
1848         be->ref_count--;
1849         SDL_assert(be->ref_count >= 0);         // Trying to unlock data more times than lock was called!!!
1850
1851 }
1852
1853
1854 void bm_update()
1855 {
1856 }
1857
1858 char *bm_get_filename(int handle)
1859 {
1860         int n;
1861
1862         n = handle % MAX_BITMAPS;
1863         SDL_assert(bm_bitmaps[n].handle == handle);             // INVALID BITMAP HANDLE
1864         return bm_bitmaps[n].filename;
1865 }
1866
1867 void bm_get_palette(int handle, ubyte *pal, char *name)
1868 {
1869         char *filename;
1870         int w,h;
1871
1872         int n= handle % MAX_BITMAPS;
1873         SDL_assert( bm_bitmaps[n].handle == handle );           // INVALID BITMAP HANDLE
1874
1875         filename = bm_bitmaps[n].filename;
1876
1877         if (name)       {
1878                 strcpy( name, filename );
1879         }
1880
1881         int pcx_error=pcx_read_header( filename, &w, &h, pal );
1882         if ( pcx_error != PCX_ERROR_NONE ){
1883                 // Error(LOCATION, "Couldn't open '%s'\n", filename );
1884         }
1885 }
1886
1887 // --------------------------------------------------------------------------------------
1888 // bm_release()  - unloads the bitmap's data and entire slot, so bitmap 'n' won't be valid anymore
1889 //
1890 // parameters:          n               =>              index into bm_bitmaps ( index returned from bm_load() or bm_create() )
1891 //
1892 // returns:                     nothing
1893
1894 // opengl hack
1895 void opengl1_free_texture_with_handle(int handle);
1896 void bm_release(int handle)
1897 {
1898         bitmap_entry    *be;
1899
1900         int n = handle % MAX_BITMAPS;
1901
1902         SDL_assert(n >= 0 && n < MAX_BITMAPS);
1903         be = &bm_bitmaps[n];
1904
1905         if ( bm_bitmaps[n].type == BM_TYPE_NONE ) {
1906                 return; // Already been released?
1907         }
1908
1909         if ( bm_bitmaps[n].type != BM_TYPE_USER )       {
1910                 return;
1911         }
1912
1913         SDL_assert( be->handle == handle );             // INVALID BITMAP HANDLE
1914
1915         // If it is locked, cannot free it.
1916         if (be->ref_count != 0) {
1917                 nprintf(("BmpMan", "tried to unload %s that has a lock count of %d.. not unloading\n", be->filename, be->ref_count));
1918                 return;
1919         }
1920
1921 // until opengl mode gets a proper texture manager, this will have to do
1922 #ifdef PLAT_UNIX
1923         opengl1_free_texture_with_handle(handle);
1924 #endif
1925
1926         bm_free_data(n);
1927
1928         if ( bm_bitmaps[n].type == BM_TYPE_USER )       {
1929                 bm_bitmaps[n].info.user.data = NULL;
1930                 bm_bitmaps[n].info.user.bpp = 0;
1931         }
1932
1933
1934         bm_bitmaps[n].type = BM_TYPE_NONE;
1935
1936         // Fill in bogus structures!
1937
1938         // For debugging:
1939         strcpy( bm_bitmaps[n].filename, "IVE_BEEN_RELEASED!" );
1940         bm_bitmaps[n].signature = 0xDEADBEEF;                                                                   // a unique signature identifying the data
1941         bm_bitmaps[n].palette_checksum = 0xDEADBEEF;                                                    // checksum used to be sure bitmap is in current palette
1942
1943         // bookeeping
1944         #ifdef BMPMAN_NDEBUG
1945         bm_bitmaps[n].data_size = -1;                                                                   // How much data this bitmap uses
1946         #endif
1947         bm_bitmaps[n].ref_count = -1;                                                                   // Number of locks on bitmap.  Can't unload unless ref_count is 0.
1948
1949         // Bitmap info
1950         bm_bitmaps[n].bm.w = bm_bitmaps[n].bm.h = -1;
1951         
1952         // Stuff needed for animations
1953         // Stuff needed for user bitmaps
1954         memset( &bm_bitmaps[n].info, 0, sizeof(bm_extra_info) );
1955
1956         bm_bitmaps[n].handle = -1;
1957 }
1958
1959
1960
1961
1962
1963
1964 // --------------------------------------------------------------------------------------
1965 // bm_unload()  - unloads the data, but not the bitmap info.
1966 //
1967 // parameters:          n               =>              index into bm_bitmaps ( index returned from bm_load() or bm_create() )
1968 //
1969 // returns:                     0               =>              unload failed
1970 //                                              1               =>              unload successful
1971 //
1972 int bm_unload( int handle )
1973 {
1974         bitmap_entry    *be;
1975         bitmap                  *bmp;
1976
1977         int n = handle % MAX_BITMAPS;
1978
1979         SDL_assert(n >= 0 && n < MAX_BITMAPS);
1980         be = &bm_bitmaps[n];
1981         bmp = &be->bm;
1982
1983         if ( be->type == BM_TYPE_NONE ) {
1984                 return 0;               // Already been released
1985         }
1986
1987         SDL_assert( be->handle == handle );             // INVALID BITMAP HANDLE!
1988
1989         // If it is locked, cannot free it.
1990         if (be->ref_count != 0) {
1991                 nprintf(("BmpMan", "tried to unload %s that has a lock count of %d.. not unloading\n", be->filename, be->ref_count));
1992                 return 0;
1993         }
1994
1995         nprintf(("BmpMan", "unloading %s.  %dx%dx%d\n", be->filename, bmp->w, bmp->h, bmp->bpp));
1996         bm_free_data(n);                // clears flags, bbp, data, etc
1997
1998         return 1;
1999 }
2000
2001
2002 // unload all used bitmaps
2003 void bm_unload_all()
2004 {
2005         int i;
2006
2007         for (i = 0; i < MAX_BITMAPS; i++)       {
2008                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2009                         bm_unload(bm_bitmaps[i].handle);
2010                 }
2011         }
2012 }
2013
2014
2015 DCF(bmpman,"Shows/changes bitmap caching parameters and usage")
2016 {
2017         if ( Dc_command )       {
2018                 dc_get_arg(ARG_STRING);
2019                 if ( !strcmp( Dc_arg, "flush" ))        {
2020                         dc_printf( "Total RAM usage before flush: %d bytes\n", bm_texture_ram );
2021                         int i;
2022                         for (i = 0; i < MAX_BITMAPS; i++)       {
2023                                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2024                                         bm_free_data(i);
2025                                 }
2026                         }
2027                         dc_printf( "Total RAM after flush: %d bytes\n", bm_texture_ram );
2028                 } else if ( !strcmp( Dc_arg, "ram" ))   {
2029                         dc_get_arg(ARG_INT);
2030                         Bm_max_ram = Dc_arg_int*1024*1024;
2031                 } else {
2032                         // print usage, not stats
2033                         Dc_help = 1;
2034                 }
2035         }
2036
2037         if ( Dc_help )  {
2038                 dc_printf( "Usage: BmpMan keyword\nWhere keyword can be in the following forms:\n" );
2039                 dc_printf( "BmpMan flush    Unloads all bitmaps.\n" );
2040                 dc_printf( "BmpMan ram x    Sets max mem usage to x MB. (Set to 0 to have no limit.)\n" );
2041                 dc_printf( "\nUse '? BmpMan' to see status of Bitmap manager.\n" );
2042                 Dc_status = 0;  // don't print status if help is printed.  Too messy.
2043         }
2044
2045         if ( Dc_status )        {
2046                 dc_printf( "Total RAM usage: %d bytes\n", bm_texture_ram );
2047
2048
2049                 if ( Bm_max_ram > 1024*1024 )
2050                         dc_printf( "Max RAM allowed: %.1f MB\n", i2fl(Bm_max_ram)/(1024.0f*1024.0f) );
2051                 else if ( Bm_max_ram > 1024 )
2052                         dc_printf( "Max RAM allowed: %.1f KB\n", i2fl(Bm_max_ram)/(1024.0f) );
2053                 else if ( Bm_max_ram > 0 )
2054                         dc_printf( "Max RAM allowed: %d bytes\n", Bm_max_ram );
2055                 else
2056                         dc_printf( "No RAM limit\n" );
2057
2058
2059         }
2060 }
2061
2062 // Marks a texture as being used for this level
2063 void bm_page_in_texture( int bitmapnum, int nframes )
2064 {
2065         int i;
2066         for (i=0; i<nframes;i++ )       {
2067                 int n = bitmapnum % MAX_BITMAPS;
2068
2069                 bm_bitmaps[n+i].preloaded = 1;
2070
2071                 bm_bitmaps[n+i].used_flags = BMP_TEX_OTHER;
2072         }
2073 }
2074
2075 // marks a texture as being a transparent textyre used for this level
2076 // Marks a texture as being used for this level
2077 // If num_frames is passed, assume this is an animation
2078 void bm_page_in_xparent_texture( int bitmapnum, int nframes)
2079 {
2080         int i;
2081         for (i=0; i<nframes;i++ )       {
2082                 int n = bitmapnum % MAX_BITMAPS;
2083
2084                 bm_bitmaps[n+i].preloaded = 3;
2085
2086                 // bm_bitmaps[n+i].used_flags = BMP_NO_PALETTE_MAP;
2087                 bm_bitmaps[n+i].used_flags = BMP_TEX_XPARENT;
2088         }
2089 }
2090
2091 // Marks an aabitmap as being used for this level
2092 void bm_page_in_aabitmap( int bitmapnum, int nframes )
2093 {
2094         int i;
2095
2096         for (i=0; i<nframes;i++ )       {
2097                 int n = bitmapnum % MAX_BITMAPS;
2098
2099                 bm_bitmaps[n+i].preloaded = 2;
2100
2101                 bm_bitmaps[n+i].used_flags = BMP_AABITMAP;
2102         }
2103 }
2104
2105
2106
2107 // Tell the bitmap manager to start keeping track of what bitmaps are used where.
2108 void bm_page_in_start()
2109 {
2110         int i;
2111
2112         Bm_paging = 1;
2113
2114         // Mark all as inited
2115         for (i = 0; i < MAX_BITMAPS; i++)       {
2116                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2117                         bm_unload(bm_bitmaps[i].handle);
2118                 }
2119                 bm_bitmaps[i].preloaded = 0;
2120                 #ifdef BMPMAN_NDEBUG
2121                         bm_bitmaps[i].used_count = 0;
2122                 #endif
2123                 bm_bitmaps[i].used_flags = 0;
2124         }
2125
2126 }
2127
2128 void bm_page_in_stop()
2129 {       
2130         int i;  
2131         int ship_info_index;
2132
2133         nprintf(( "BmpInfo","BMPMAN: Loading all used bitmaps.\n" ));
2134
2135         // Load all the ones that are supposed to be loaded for this level.
2136         int n = 0;
2137
2138         #ifdef BMPMAN_NDEBUG
2139         Bm_ram_freed = 0;
2140         #endif
2141
2142         int d3d_preloading = 1;
2143
2144         gr_preload_init();
2145
2146         for (i = 0; i < MAX_BITMAPS; i++)       {
2147                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2148                         if ( bm_bitmaps[i].preloaded )  {
2149 #ifdef BMPMAN_SPECIAL_NONDARK
2150                                 // if this is a texture, check to see if a ship uses it
2151                                 ship_info_index = ship_get_texture(bm_bitmaps[i].handle);
2152                                 // use the colors from this ship
2153                                 if((ship_info_index >= 0) && (Ship_info[ship_info_index].num_nondark_colors > 0)){
2154                                         // mprintf(("Using custom pixels for %s\n", Ship_info[ship_info_index].name));
2155                                         palman_set_nondarkening(Ship_info[ship_info_index].nondark_colors, Ship_info[ship_info_index].num_nondark_colors);
2156                                 }
2157                                 // use the colors from the default table
2158                                 else {
2159                                         // mprintf(("Using default pixels\n"));
2160                                         palman_set_nondarkening(Palman_non_darkening_default, Palman_num_nondarkening_default);
2161                                 }
2162 #endif
2163
2164                                 // if preloaded == 3, load it as an xparent texture                             
2165                                 if(bm_bitmaps[i].used_flags == BMP_AABITMAP){
2166                                         bm_lock( bm_bitmaps[i].handle, 8, bm_bitmaps[i].used_flags );
2167                                 } else {
2168                                         bm_lock( bm_bitmaps[i].handle, 16, bm_bitmaps[i].used_flags );
2169                                 }
2170                                 bm_unlock( bm_bitmaps[i].handle );
2171
2172                                 if ( d3d_preloading )   {
2173                                         if ( !gr_preload(bm_bitmaps[i].handle, (bm_bitmaps[i].preloaded==2) ) ) {
2174                                                 mprintf(( "Out of VRAM.  Done preloading.\n" ));
2175                                                 d3d_preloading = 0;
2176                                         }
2177                                 }
2178                                 
2179                                 n++;
2180                                 #ifdef BMPMAN_NDEBUG
2181                                 if ( Bm_ram_freed )     {
2182                                         nprintf(( "BmpInfo","BMPMAN: Not enough cache memory to load all level bitmaps\n" ));
2183                                         break;
2184                                 }
2185                                 #endif
2186                         } 
2187                 }
2188                 game_busy();
2189         }
2190         nprintf(( "BmpInfo","BMPMAN: Loaded %d bitmaps that are marked as used for this level.\n", n ));
2191
2192         int total_bitmaps = 0;
2193         for (i = 0; i < MAX_BITMAPS; i++)       {
2194                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2195                         total_bitmaps++;
2196                 }
2197                 if ( bm_bitmaps[i].type == BM_TYPE_USER )       {
2198                         mprintf(( "User bitmap '%s'\n", bm_bitmaps[i].filename ));
2199                 }
2200         }       
2201
2202         mprintf(( "Bmpman: %d/%d bitmap slots in use.\n", total_bitmaps, MAX_BITMAPS ));
2203         //mprintf(( "Bmpman: Usage went from %d KB to %d KB.\n", usage_before/1024, usage_after/1024 ));
2204
2205         Bm_paging = 0;
2206 }
2207
2208 int bm_get_cache_slot( int bitmap_id, int separate_ani_frames )
2209 {
2210         int n = bitmap_id % MAX_BITMAPS;
2211
2212         SDL_assert( bm_bitmaps[n].handle == bitmap_id );                // INVALID BITMAP HANDLE
2213
2214         bitmap_entry    *be = &bm_bitmaps[n];
2215
2216         if ( (!separate_ani_frames) && (be->type == BM_TYPE_ANI) )      {
2217                 return be->info.ani.first_frame;
2218         } 
2219
2220         return n;
2221
2222 }
2223
2224 // convert a 24 bit value to a 16 bit value
2225 void bm_24_to_16(int bit_24, ushort *bit_16)
2226 {
2227         ubyte *pixel = (ubyte*)&bit_24;
2228         ubyte alpha = 1;
2229
2230         bm_set_components((ubyte*)bit_16, (ubyte*)&pixel[0], (ubyte*)&pixel[1], (ubyte*)&pixel[2], &alpha);     
2231 }
2232
2233 void (*bm_set_components)(ubyte *pixel, ubyte *r, ubyte *g, ubyte *b, ubyte *a) = NULL;
2234
2235 void bm_set_components_argb_16_screen(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2236 {
2237         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2238         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2239         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2240         if(*av == 0){                           
2241                 *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2242         }                       
2243 }
2244
2245 void bm_set_components_argb_32_screen(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2246 {
2247         *((uint*)pixel) |= (uint)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2248         *((uint*)pixel) |= (uint)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2249         *((uint*)pixel) |= (uint)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2250         if(*av == 0){                           
2251                 *((uint*)pixel) = (uint)Gr_current_green->mask;         
2252         }
2253 }
2254
2255 void bm_set_components_argb_16_tex(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2256 {
2257         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2258         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2259         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2260         *((ushort*)pixel) &= ~(Gr_current_alpha->mask);
2261         if(*av){
2262                 *((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
2263         } else {
2264                 *((ushort*)pixel) = 0;
2265         }
2266 }
2267
2268 void bm_set_components_argb_32_tex(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2269 {
2270         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2271         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2272         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2273         *((ushort*)pixel) &= ~(Gr_current_alpha->mask);
2274         if(*av){
2275                 *((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
2276         } else {
2277                 *((ushort*)pixel) = 0;
2278         }
2279 }
2280
2281 // for selecting pixel formats
2282 void BM_SELECT_SCREEN_FORMAT()
2283 {
2284         Gr_current_red = &Gr_red;
2285         Gr_current_green = &Gr_green;
2286         Gr_current_blue = &Gr_blue;
2287         Gr_current_alpha = &Gr_alpha;
2288
2289         // setup pointers
2290         if ( gr_is_32bit() ) {
2291                 bm_set_components = bm_set_components_argb_32_screen;
2292         } else {
2293                 bm_set_components = bm_set_components_argb_16_screen;
2294         }
2295 }
2296
2297 void BM_SELECT_TEX_FORMAT()
2298 {
2299         Gr_current_red = &Gr_t_red; 
2300         Gr_current_green = &Gr_t_green; 
2301         Gr_current_blue = &Gr_t_blue; 
2302         Gr_current_alpha = &Gr_t_alpha;
2303
2304         // setup pointers
2305         if ( gr_is_32bit() ) {
2306                 bm_set_components = bm_set_components_argb_32_tex;
2307         } else {
2308                 bm_set_components = bm_set_components_argb_16_tex;
2309         }
2310 }
2311
2312 void BM_SELECT_ALPHA_TEX_FORMAT()
2313 {
2314         Gr_current_red = &Gr_ta_red; 
2315         Gr_current_green = &Gr_ta_green; 
2316         Gr_current_blue = &Gr_ta_blue; 
2317         Gr_current_alpha = &Gr_ta_alpha;
2318
2319         // setup pointers
2320         if ( gr_is_32bit() ) {
2321                 bm_set_components = bm_set_components_argb_32_tex;
2322         } else {
2323                 bm_set_components = bm_set_components_argb_16_tex;
2324         }
2325 }
2326
2327 // set the rgba components of a pixel, any of the parameters can be -1
2328 /*
2329 void bm_set_components(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2330 {
2331         int bit_32 = 0;
2332
2333         // pick a byte size - 32 bits only if 32 bit mode d3d and screen format
2334         if(D3D_32bit && (Gr_current_red == &Gr_red)){
2335                 bit_32 = 1;
2336         }       
2337         
2338         if(bit_32){
2339                 *((uint*)pixel) |= (uint)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2340         } else {
2341                 *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2342         }               
2343         if(bit_32){
2344                 *((uint*)pixel) |= (uint)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2345         } else {
2346                 *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2347         }               
2348         if(bit_32){
2349                 *((uint*)pixel) |= (uint)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2350         } else {
2351                 *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2352         }
2353         
2354         // NOTE - this is a semi-hack. For direct3d we don't use an alpha bit, so if *av == 0, we just set the whole pixel to be Gr_green.mask
2355         //        ergo, we need to do this _last_
2356         switch(Bm_pixel_format){
2357         // glide has an alpha channel so we have to unset ir or set it each time
2358         case BM_PIXEL_FORMAT_ARGB:
2359                 SDL_assert(!bit_32);
2360                 *((ushort*)pixel) &= ~(0x8000);
2361                 if(*av){
2362                         *((ushort*)pixel) |= 0x8000;
2363                 }
2364                 break;
2365         
2366         // this d3d format has no alpha channel, so only make it "transparent", never make it "non-transparent"
2367         case BM_PIXEL_FORMAT_D3D:                       
2368                 SDL_assert(!bit_32);
2369                 if(*av == 0){ 
2370                         *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2371                 }
2372                 break;
2373
2374         // nice 1555 texture format
2375         case BM_PIXEL_FORMAT_ARGB_D3D:                                          
2376                 // if we're writing to normal texture format
2377                 if(Gr_current_red == &Gr_t_red){                                        
2378                         SDL_assert(!bit_32);
2379                         *((ushort*)pixel) &= ~(Gr_current_alpha->mask);
2380                         if(*av){
2381                                 *((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
2382                         } else {
2383                                 *((ushort*)pixel) = 0;
2384                         }
2385                 }
2386                 // otherwise if we're writing to screen format, still do it the green mask way
2387                 else {                  
2388                         if(*av == 0){
2389                                 if(bit_32){
2390                                         *((uint*)pixel) = (uint)Gr_current_green->mask;
2391                                 } else {
2392                                         *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2393                                 }
2394                         }
2395                 }                       
2396                 break;
2397         }       
2398 }
2399 */
2400
2401 // get the rgba components of a pixel, any of the parameters can be NULL
2402 void bm_get_components(ubyte *pixel, ubyte *r, ubyte *g, ubyte *b, ubyte *a)
2403 {
2404         int bit_32 = 0;
2405
2406         // pick a byte size - 32 bits only if 32 bit mode d3d and screen format
2407         if ( gr_is_32bit() && (Gr_current_red == &Gr_red) ) {
2408                 bit_32 = 1;
2409         }
2410
2411         if(r != NULL){
2412                 if(bit_32){
2413                         *r = ubyte(( (*((uint*)pixel) & Gr_current_red->mask)>>Gr_current_red->shift)*Gr_current_red->scale);
2414                 } else {
2415                         *r = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_red->mask)>>Gr_current_red->shift)*Gr_current_red->scale);
2416                 }
2417         }
2418         if(g != NULL){
2419                 if(bit_32){
2420                         *g = ubyte(( (*((uint*)pixel) & Gr_current_green->mask) >>Gr_current_green->shift)*Gr_current_green->scale);
2421                 } else {
2422                         *g = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_green->mask) >>Gr_current_green->shift)*Gr_current_green->scale);
2423                 }
2424         }
2425         if(b != NULL){
2426                 if(bit_32){
2427                         *b = ubyte(( (*((uint*)pixel) & Gr_current_blue->mask)>>Gr_current_blue->shift)*Gr_current_blue->scale);
2428                 } else {
2429                         *b = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_blue->mask)>>Gr_current_blue->shift)*Gr_current_blue->scale);
2430                 }
2431         }
2432
2433         // get the alpha value
2434         if(a != NULL){          
2435                 *a = 1;
2436
2437                 // if we're writing to a normal texture, use nice alpha bits
2438                 if(Gr_current_red == &Gr_t_red){
2439                         SDL_assert(!bit_32);
2440
2441                         if(!(*((ushort*)pixel) & Gr_current_alpha->mask)){
2442                                 *a = 0;
2443                         }
2444                 }
2445                 // otherwise do it as normal
2446                 else {
2447                         if(bit_32){
2448                                 if(*((int*)pixel) == Gr_current_green->mask){
2449                                         *a = 0;
2450                                 }
2451                         } else {
2452                                 if(*((ushort*)pixel) == Gr_current_green->mask){
2453                                         *a = 0;
2454                                 }
2455                         }
2456                 }
2457         }
2458 }
2459
2460 // get filename
2461 void bm_get_filename(int bitmapnum, char *filename)
2462 {
2463         int n = bitmapnum % MAX_BITMAPS;
2464
2465         // return filename
2466         strcpy(filename, bm_bitmaps[n].filename);
2467 }
2468
2469 // given a bitmap and a section, return the size (w, h)
2470 void bm_get_section_size(int bitmapnum, int sx, int sy, int *w, int *h)
2471 {
2472         int bw, bh;
2473         bitmap_section_info *sections;
2474
2475         // bogus input?
2476         SDL_assert((w != NULL) && (h != NULL));
2477         if((w == NULL) || (h == NULL)){
2478                 return;
2479         }
2480
2481         // get bitmap info
2482         bm_get_info(bitmapnum, &bw, &bh, NULL, NULL, NULL, &sections);
2483
2484         // determine the width and height of this section
2485         if (gr_screen.use_sections) {
2486                 *w = sx < (sections->num_x - 1) ? MAX_BMAP_SECTION_SIZE : bw - sections->sx[sx];
2487                 *h = sy < (sections->num_y - 1) ? MAX_BMAP_SECTION_SIZE : bh - sections->sy[sy];
2488         } else {
2489                 *w = bw;
2490                 *h = bh;
2491         }
2492 }
2493