]> icculus.org git repositories - taylor/freespace2.git/blob - src/bmpman/bmpman.cpp
amd64 support, compiler warning fixes, don't use software rendering
[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 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 // 16 bit pixel formats
601 int Bm_pixel_format = BM_PIXEL_FORMAT_ARGB;
602
603 // get and put functions for 16 bit pixels - neat bit slinging, huh?
604 #define BM_SET_R_ARGB(p, r)     { p[1] &= ~(0x7c); p[1] |= ((r & 0x1f) << 2); }
605 #define BM_SET_G_ARGB(p, g)     { p[0] &= ~(0xe0); p[1] &= ~(0x03); p[0] |= ((g & 0x07) << 5); p[1] |= ((g & 0x18) >> 3); }
606 #define BM_SET_B_ARGB(p, b)     { p[0] &= ~(0x1f); p[0] |= b & 0x1f; }
607 #define BM_SET_A_ARGB(p, a)     { p[1] &= ~(0x80); p[1] |= ((a & 0x01) << 7); }
608
609 #define BM_SET_R_D3D(p, r)              { *p |= (ushort)(( (int)r / Gr_current_red->scale ) << Gr_current_red->shift); }
610 #define BM_SET_G_D3D(p, g)              { *p |= (ushort)(( (int)g / Gr_current_green->scale ) << Gr_current_green->shift); }
611 #define BM_SET_B_D3D(p, b)              { *p |= (ushort)(( (int)b / Gr_current_blue->scale ) << Gr_current_blue->shift); }
612 #define BM_SET_A_D3D(p, a)              { if(a == 0){ *p = (ushort)Gr_current_green->mask; } }
613
614 #define BM_SET_R(p, r)  { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_R_ARGB(((char*)p), r); break; case BM_PIXEL_FORMAT_D3D: BM_SET_R_D3D(p, r); break; default: Int3(); } }
615 #define BM_SET_G(p, g)  { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_G_ARGB(((char*)p), g); break; case BM_PIXEL_FORMAT_D3D: BM_SET_G_D3D(p, g); break; default: Int3(); } }
616 #define BM_SET_B(p, b)  { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_B_ARGB(((char*)p), b); break; case BM_PIXEL_FORMAT_D3D: BM_SET_B_D3D(p, b); break;  default: Int3(); } }
617 #define BM_SET_A(p, a)  { switch(Bm_pixel_format){ case BM_PIXEL_FORMAT_ARGB: BM_SET_A_ARGB(((char*)p), a); break; case BM_PIXEL_FORMAT_D3D: BM_SET_A_D3D(p, a); break;  default: Int3(); } }
618
619 // ===========================================
620 // Mode: 0 = High memory
621 //       1 = Low memory ( every other frame of ani's)
622 //       2 = Debug low memory ( only use first frame of each ani )
623 void bm_set_low_mem( int mode )
624 {
625         Assert( (mode >= 0)  && (mode<=2 ));
626         Bm_low_mem = mode;
627 }
628
629
630 static int bm_get_next_handle()
631 {
632         int n = bm_next_handle;
633         bm_next_handle++;
634         if ( bm_next_handle > 30000 )   {
635                 bm_next_handle = 1;
636         }
637         return n;
638 }
639
640 // Frees a bitmaps data if it should, and
641 // Returns true if bitmap n can free it's data.
642 static void bm_free_data(int n)
643 {
644         bitmap_entry    *be;
645         bitmap                  *bmp;
646
647         Assert( n >= 0 && n < MAX_BITMAPS );
648
649         be = &bm_bitmaps[n];
650         bmp = &be->bm;
651
652         // If there isn't a bitmap in this structure, don't
653         // do anything but clear out the bitmap info
654         if ( be->type==BM_TYPE_NONE) 
655                 goto SkipFree;
656
657         // If this bitmap doesn't have any data to free, skip
658         // the freeing it part of this.
659         if ( bmp->data == 0 ) 
660                 goto SkipFree;
661
662         // Don't free up memory for user defined bitmaps, since
663         // BmpMan isn't the one in charge of allocating/deallocing them.
664         if ( ( be->type==BM_TYPE_USER ) )       
665                 goto SkipFree;
666
667         // Free up the data now!
668
669         //      mprintf(( "Bitmap %d freed %d bytes\n", n, bm_bitmaps[n].data_size ));
670         #ifdef BMPMAN_NDEBUG
671                 bm_texture_ram -= be->data_size;
672         #endif
673         free((void *)bmp->data);
674
675 SkipFree:
676
677         // Clear out & reset the bitmap data structure
678         bmp->flags = 0;
679         bmp->bpp = 0;
680         bmp->data = 0;
681         bmp->palette = NULL;
682         #ifdef BMPMAN_NDEBUG
683                 be->data_size = 0;
684         #endif
685         be->signature = Bm_next_signature++; 
686 }
687
688
689 #ifdef BMPMAN_NDEBUG
690
691 int Bm_ram_freed = 0;
692
693 static void bm_free_some_ram( int n, int size )
694 {
695 /*
696         if ( Bm_max_ram < 1 ) return;
697         if ( bm_texture_ram + size < Bm_max_ram ) return;
698
699         int current_time = timer_get_milliseconds();
700
701         while( bm_texture_ram + size > Bm_max_ram )     {
702                 Bm_ram_freed++;
703
704                 // Need to free some RAM up!
705                 int i, oldest=-1, best_val=0;
706                 for (i = 0; i < MAX_BITMAPS; i++)       {
707                         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) )    {
708                                 int page_func = ( current_time-bm_bitmaps[i].last_used)*bm_bitmaps[i].data_size;
709                                 if ( (oldest==-1) || (page_func>best_val) )     {
710                                         oldest=i;
711                                         best_val = page_func;
712                                 }
713                         }
714                 }
715
716                 if ( oldest > -1 )      {
717                         //mprintf(( "Freeing bitmap '%s'\n", bm_bitmaps[oldest].filename ));
718                         for (i=0; i<bm_bitmaps[oldest].num_frames; i++ )        {
719                                 bm_free_data(bm_bitmaps[oldest].first_frame+i);
720                         }
721                 } else {
722                         //mprintf(( "Couldn't free enough! %d\n", bm_texture_ram ));
723                         break;
724                 }
725         }       
726 */
727 }
728
729 #endif
730
731 static void *bm_malloc( int n, int size )
732 {
733         Assert( n >= 0 && n < MAX_BITMAPS );
734 //      mprintf(( "Bitmap %d allocated %d bytes\n", n, size ));
735         #ifdef BMPMAN_NDEBUG
736         bm_free_some_ram( n, size );
737         Assert( bm_bitmaps[n].data_size == 0 );
738         bm_bitmaps[n].data_size += size;
739         bm_texture_ram += size;
740         #endif
741         return malloc(size);
742 }
743
744 void bm_close()
745 {
746         int i;
747         if ( bm_inited )        {
748                 for (i=0; i<MAX_BITMAPS; i++ )  {
749                         bm_free_data(i);                        // clears flags, bbp, data, etc
750                 }
751                 bm_inited = 0;
752         }
753 }
754
755
756 void bm_init()
757 {
758         int i;
759
760         mprintf(( "Size of bitmap info = %d KB\n", sizeof( bm_bitmaps )/1024 ));
761         mprintf(( "Size of bitmap extra info = %d bytes\n", sizeof( bm_extra_info ) ));
762         
763         if (!bm_inited) {
764                 bm_inited = 1;
765                 atexit(bm_close);
766         }
767         
768         for (i=0; i<MAX_BITMAPS; i++ ) {
769                 bm_bitmaps[i].filename[0] = '\0';
770                 bm_bitmaps[i].type = BM_TYPE_NONE;
771                 bm_bitmaps[i].info.user.data = NULL;
772                 bm_bitmaps[i].bm.data = 0;
773                 bm_bitmaps[i].bm.palette = NULL;
774                 #ifdef BMPMAN_NDEBUG
775                         bm_bitmaps[i].data_size = 0;
776                         bm_bitmaps[i].used_count = 0;
777                         bm_bitmaps[i].used_last_frame = 0;
778                         bm_bitmaps[i].used_this_frame = 0;
779                 #endif
780                 bm_free_data(i);        // clears flags, bbp, data, etc
781         }
782
783
784 }
785
786 #ifdef BMPMAN_NDEBUG
787
788 // Returns number of bytes of bitmaps locked this frame
789 // ntotal = number of bytes of bitmaps locked this frame
790 // nnew = number of bytes of bitmaps locked this frame that weren't locked last frame
791 void bm_get_frame_usage(int *ntotal, int *nnew)
792 {
793         int i;
794         
795         *ntotal = 0;
796         *nnew = 0;
797
798         for (i=0; i<MAX_BITMAPS; i++ ) {
799                 if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && (bm_bitmaps[i].used_this_frame))   {
800                         if ( !bm_bitmaps[i].used_last_frame )   {
801                                 *nnew += bm_bitmaps[i].bm.w*bm_bitmaps[i].bm.h; 
802                         }
803                         *ntotal += bm_bitmaps[i].bm.w*bm_bitmaps[i].bm.h;
804                 }
805                 bm_bitmaps[i].used_last_frame = bm_bitmaps[i].used_this_frame;
806                 bm_bitmaps[i].used_this_frame = 0;
807         }
808
809 }
810 #else
811 void bm_get_frame_usage(int *ntotal, int *nnew)
812 {
813 }
814 #endif
815
816 // given a loaded bitmap with valid info, calculate sections
817 void bm_calc_sections(bitmap *be)
818 {
819         int idx;
820
821         // number of x and y sections
822         be->sections.num_x = (ubyte)(be->w / MAX_BMAP_SECTION_SIZE);
823         if((be->sections.num_x * MAX_BMAP_SECTION_SIZE) < be->w){
824                 be->sections.num_x++;
825         }
826         be->sections.num_y = (ubyte)(be->h / MAX_BMAP_SECTION_SIZE);
827         if((be->sections.num_y * MAX_BMAP_SECTION_SIZE) < be->h){
828                 be->sections.num_y++;
829         }
830
831         // calculate the offsets for each section
832         for(idx=0; idx<be->sections.num_x; idx++){
833                 be->sections.sx[idx] = (ushort)(MAX_BMAP_SECTION_SIZE * idx);
834         }
835         for(idx=0; idx<be->sections.num_y; idx++){
836                 be->sections.sy[idx] = (ushort)(MAX_BMAP_SECTION_SIZE * idx);
837         }
838 }
839
840 // Creates a bitmap that exists in RAM somewhere, instead
841 // of coming from a disk file.  You pass in a pointer to a
842 // block of 32 (or 8)-bit-per-pixel data.  Right now, the only
843 // bpp you can pass in is 32 or 8.  On success, it returns the
844 // bitmap number.  You cannot free that RAM until bm_release
845 // is called on that bitmap.
846 int bm_create( int bpp, int w, int h, void * data, int flags )
847 {
848         int i, n, first_slot = MAX_BITMAPS;
849
850         // Assert((bpp==32)||(bpp==8));
851         if(bpp != 16){
852                 Assert(flags & BMP_AABITMAP);
853         } else {
854                 Assert(bpp == 16);
855         }
856
857         if ( !bm_inited ) bm_init();
858
859         for (i = MAX_BITMAPS-1; i >= 0; i-- ) {
860                 if ( bm_bitmaps[i].type == BM_TYPE_NONE )       {
861                         first_slot = i;
862                         break;
863                 }
864         }
865
866         n = first_slot;
867         Assert( n > -1 );
868
869         // Out of bitmap slots
870         if ( n == -1 ) return -1;
871
872         memset( &bm_bitmaps[n], 0, sizeof(bitmap_entry) );
873
874         sprintf( bm_bitmaps[n].filename, "TMP%dx%d", w, h );
875         bm_bitmaps[n].type = BM_TYPE_USER;
876         bm_bitmaps[n].palette_checksum = 0;
877
878         bm_bitmaps[n].bm.w = short(w);
879         bm_bitmaps[n].bm.h = short(h);
880         bm_bitmaps[n].bm.rowsize = short(w);
881         bm_bitmaps[n].bm.bpp = (unsigned char)(bpp);
882         bm_bitmaps[n].bm.flags = 0;
883         bm_bitmaps[n].bm.flags |= flags;
884         bm_bitmaps[n].bm.data = 0;
885         bm_bitmaps[n].bm.palette = NULL;
886
887         bm_bitmaps[n].info.user.bpp = ubyte(bpp);
888         bm_bitmaps[n].info.user.data = data;
889         bm_bitmaps[n].info.user.flags = ubyte(flags);
890
891         bm_bitmaps[n].signature = Bm_next_signature++;
892
893         bm_bitmaps[n].handle = bm_get_next_handle()*MAX_BITMAPS + n;
894         bm_bitmaps[n].last_used = -1;
895
896         // fill in section info
897         bm_calc_sections(&bm_bitmaps[n].bm);
898         
899         return bm_bitmaps[n].handle;
900 }
901
902 // sub helper function. Given a raw filename and an extension, try and find the bitmap
903 // returns -1 if it could not be found
904 //          0 if it was found as a file
905 //          1 if it already exists, fills in handle
906 int Bm_ignore_duplicates = 0;
907 int bm_load_sub(char *real_filename, char *ext, int *handle)
908 {       
909         int i;
910         char filename[MAX_FILENAME_LEN] = "";
911         
912         strcpy( filename, real_filename );
913         strcat( filename, ext );        
914         for (i=0; i<(int)strlen(filename); i++ ){
915                 filename[i] = char(tolower(filename[i]));
916         }               
917
918         // try to find given filename to see if it has been loaded before
919         if(!Bm_ignore_duplicates){
920                 for (i = 0; i < MAX_BITMAPS; i++) {
921                         if ( (bm_bitmaps[i].type != BM_TYPE_NONE) && !stricmp(filename, bm_bitmaps[i].filename) ) {
922                                 nprintf (("BmpMan", "Found bitmap %s -- number %d\n", filename, i));
923                                 *handle = bm_bitmaps[i].handle;
924                                 return 1;
925                         }
926                 }       
927         }
928
929         // try and find the file
930         /*
931         CFILE *test = cfopen(filename, "rb");
932         if(test != NULL){
933                 cfclose(test);
934                 return 0;
935         }
936         */
937
938         // could not be found
939         return 0;
940 }
941
942 // This loads a bitmap so we can draw with it later.
943 // It returns a negative number if it couldn't load
944 // the bitmap.   On success, it returns the bitmap
945 // number.  Function doesn't acutally load the data, only
946 // width, height, and possibly flags.
947 int bm_load( char * real_filename )
948 {
949         int i, n, first_slot = MAX_BITMAPS;
950         int w, h, bpp;
951         char filename[MAX_FILENAME_LEN];
952         int tga = 0;
953         int handle;
954         int found = 0;
955
956         if ( !bm_inited ) bm_init();
957
958         // nice little trick for keeping standalone memory usage way low - always return a bogus bitmap 
959         if(Game_mode & GM_STANDALONE_SERVER){
960                 strcpy(filename,"test128");
961         }
962
963         // make sure no one passed an extension
964         strcpy( filename, real_filename );
965         char *p = strchr( filename, '.' );
966         if ( p ) {
967                 mprintf(( "Someone passed an extension to bm_load for file '%s'\n", real_filename ));
968                 //Int3();
969                 *p = 0;
970         }
971          
972         // try and find the pcx file            
973         switch(bm_load_sub(filename, ".pcx", &handle)){
974         // error
975         case -1:
976                 break;
977
978         // found as a file
979         case 0:
980                 found = 1;
981                 strcat(filename, ".pcx");
982                 break;
983
984         // found as pre-existing
985         case 1:
986                 found = 1;
987                 return handle;          
988         }
989
990         if(!found){
991                 // try and find the tga file
992                 switch(bm_load_sub(filename, ".tga", &handle)){
993                 // error
994                 case -1:                        
995                         return -1;
996                         break;
997
998                 // found as a file
999                 case 0:                 
1000                         strcat(filename, ".tga");
1001                         tga = 1;
1002                         break;
1003
1004                 // found as pre-existing
1005                 case 1:                                         
1006                         return handle;                                  
1007                 }
1008         }
1009
1010         // if its a tga file
1011         if(tga){
1012                 int tga_error=targa_read_header( filename, &w, &h, &bpp, NULL );
1013                 if ( tga_error != TARGA_ERROR_NONE )    {
1014                         mprintf(( "Couldn't open '%s'\n", filename ));
1015                         return -1;
1016                 }
1017         }
1018         // if its a pcx file
1019         else {
1020                 int pcx_error=pcx_read_header( filename, &w, &h, NULL );                
1021                 if ( pcx_error != PCX_ERROR_NONE )      {
1022                         mprintf(( "Couldn't open '%s'\n", filename ));
1023                         return -1;
1024                 }
1025         }
1026
1027         // Error( LOCATION, "Unknown bitmap type %s\n", filename );
1028                 
1029         // Find an open slot
1030         for (i = 0; i < MAX_BITMAPS; i++) {
1031                 if ( (bm_bitmaps[i].type == BM_TYPE_NONE) && (first_slot == MAX_BITMAPS) ){
1032                         first_slot = i;
1033                 }
1034         }
1035
1036         n = first_slot;
1037         Assert( n < MAX_BITMAPS );      
1038
1039         if ( n == MAX_BITMAPS ) return -1;      
1040
1041         // ensure fields are cleared out from previous bitmap
1042 //      Assert(bm_bitmaps[n].bm.data == 0);
1043 //      Assert(bm_bitmaps[n].bm.palette == NULL);
1044 //      Assert(bm_bitmaps[n].ref_count == 0 );
1045 //      Assert(bm_bitmaps[n].user_data == NULL);
1046         memset( &bm_bitmaps[n], 0, sizeof(bitmap_entry) );
1047         
1048         // Mark the slot as filled, because cf_read might load a new bitmap
1049         // into this slot.
1050         bm_bitmaps[n].type = tga ? (ubyte)BM_TYPE_TGA : (ubyte)BM_TYPE_PCX;
1051         bm_bitmaps[n].signature = Bm_next_signature++;
1052         Assert ( strlen(filename) < MAX_FILENAME_LEN );
1053         strncpy(bm_bitmaps[n].filename, filename, MAX_FILENAME_LEN-1 );
1054         bm_bitmaps[n].bm.w = short(w);
1055         bm_bitmaps[n].bm.rowsize = short(w);
1056         bm_bitmaps[n].bm.h = short(h);
1057         bm_bitmaps[n].bm.bpp = 0;
1058         bm_bitmaps[n].bm.flags = 0;
1059         bm_bitmaps[n].bm.data = 0;
1060         bm_bitmaps[n].bm.palette = NULL;
1061
1062         bm_bitmaps[n].palette_checksum = 0;
1063         bm_bitmaps[n].handle = bm_get_next_handle()*MAX_BITMAPS + n;
1064         bm_bitmaps[n].last_used = -1;
1065
1066         // fill in section info
1067         bm_calc_sections(&bm_bitmaps[n].bm);
1068
1069         return bm_bitmaps[n].handle;
1070 }
1071
1072 // special load function. basically allows you to load a bitmap which already exists (by filename). 
1073 // this is useful because in some cases we need to have a bitmap which is locked in screen format
1074 // _and_ texture format, such as pilot pics and squad logos
1075 int bm_load_duplicate(char *filename)
1076 {
1077         int ret;
1078
1079         // ignore duplicates
1080         Bm_ignore_duplicates = 1;
1081         
1082         // load
1083         ret = bm_load(filename);
1084
1085         // back to normal
1086         Bm_ignore_duplicates = 0;
1087
1088         return ret;
1089 }
1090
1091 DCF(bm_frag,"Shows BmpMan fragmentation")
1092 {
1093         if ( Dc_command )       {
1094
1095                 gr_clear();
1096
1097                 int x=0, y=0;
1098                 int xs=2, ys=2;
1099                 int w=4, h=4;
1100
1101                 for (int i=0; i<MAX_BITMAPS; i++ )      {
1102                         switch( bm_bitmaps[i].type )    {
1103                         case BM_TYPE_NONE:
1104                                 gr_set_color(128,128,128);
1105                                 break;
1106                         case BM_TYPE_PCX:
1107                                 gr_set_color(255,0,0);
1108                                 break;
1109                         case BM_TYPE_USER:
1110                                 gr_set_color(0,255,0);
1111                                 break;
1112                         case BM_TYPE_ANI:
1113                                 gr_set_color(0,0,255);
1114                                 break;
1115                         }
1116
1117                         gr_rect( x+xs, y+ys, w, h );
1118                         x += w+xs+xs;
1119                         if ( x > 639 )  {
1120                                 x = 0;
1121                                 y += h + ys + ys;
1122                         }
1123
1124                 }
1125
1126                 gr_flip();
1127                 key_getch();
1128         }
1129 }
1130
1131 static int find_block_of(int n)
1132 {
1133         int i, cnt, nstart;
1134
1135         cnt=0;
1136         nstart = 0;
1137         for (i=0; i<MAX_BITMAPS; i++ )  {
1138                 if ( bm_bitmaps[i].type == BM_TYPE_NONE )       {
1139                         if (cnt==0) nstart = i;
1140                         cnt++;
1141                 } else
1142                         cnt=0;
1143                 if ( cnt == n ) return nstart;
1144         }
1145
1146         // Error( LOCATION, "Couldn't find block of %d frames\n", n );
1147         return -1;
1148 }
1149
1150 // ------------------------------------------------------------------
1151 // bm_load_animation()
1152 //
1153 //      input:          filename                =>              filename of animation
1154 //                                      nframes         =>              OUTPUT parameter:       number of frames in the animation
1155 //                                      fps                     =>              OUTPUT/OPTIONAL parameter: intended fps for the animation
1156 //
1157 // returns:             bitmap number of first frame in the animation
1158 //
1159 int bm_load_animation( char *real_filename, int *nframes, int *fps, int can_drop_frames)
1160 {
1161         int     i, n;
1162         anim    the_anim;
1163         CFILE   *fp;
1164         char filename[MAX_FILENAME_LEN];
1165
1166         if ( !bm_inited ) bm_init();
1167
1168         strcpy( filename, real_filename );
1169         char *p = strchr( filename, '.' );
1170         if ( p ) {
1171                 mprintf(( "Someone passed an extension to bm_load_animation for file '%s'\n", real_filename ));
1172                 //Int3();
1173                 *p = 0;
1174         }
1175         strcat( filename, ".ani" );
1176
1177         if ( (fp = cfopen(filename, "rb")) == NULL ) {
1178 //              Error(LOCATION,"Could not open filename %s in bm_load_ani()\n", filename);
1179                 return -1;
1180         }
1181
1182         int reduced = 0;
1183 #ifndef NDEBUG
1184         // for debug of ANI sizes
1185         strcpy(the_anim.name, real_filename);
1186 #endif
1187         anim_read_header(&the_anim, fp);
1188         if ( can_drop_frames )  {
1189                 if ( Bm_low_mem == 1 )  {
1190                         reduced = 1;
1191                         the_anim.total_frames = ( the_anim.total_frames+1)/2;
1192                 } else if ( Bm_low_mem == 2 )   {
1193                         the_anim.total_frames = 1;      
1194                 }
1195         }
1196         cfclose(fp);
1197
1198         *nframes = the_anim.total_frames;
1199         if ( fps != NULL )      {
1200                 if ( reduced )  {
1201                         *fps = the_anim.fps / 2;
1202                 } else {
1203                         *fps = the_anim.fps;
1204                 }
1205         }
1206
1207         // first check to see if this ani already has it's frames loaded
1208         for (i = 0; i < MAX_BITMAPS; i++) {
1209                 if ( (bm_bitmaps[i].type == BM_TYPE_ANI) && !stricmp(filename, bm_bitmaps[i].filename) ) {
1210                         break;
1211                 }
1212         }
1213         
1214         if ( i < MAX_BITMAPS ) {
1215                 // in low memory modes this can happen
1216                 if(!Bm_low_mem){
1217                         Assert(bm_bitmaps[i].info.ani.num_frames == *nframes);
1218                 }
1219                 return bm_bitmaps[i].handle;
1220         }
1221
1222         n = find_block_of(*nframes);
1223         if(n < 0){
1224                 return -1;
1225         }
1226         // Assert( n >= 0 );
1227
1228         int first_handle = bm_get_next_handle();
1229
1230         Assert ( strlen(filename) < MAX_FILENAME_LEN );
1231         for ( i = 0; i < *nframes; i++ ) {
1232                 memset( &bm_bitmaps[n+i], 0, sizeof(bitmap_entry) );
1233                 bm_bitmaps[n+i].info.ani.first_frame = n;
1234                 bm_bitmaps[n+i].info.ani.num_frames = ubyte(the_anim.total_frames);
1235                 bm_bitmaps[n+i].info.ani.fps = ubyte(the_anim.fps);
1236                 bm_bitmaps[n+i].bm.w = short(the_anim.width);
1237                 bm_bitmaps[n+i].bm.rowsize = short(the_anim.width);
1238                 bm_bitmaps[n+i].bm.h = short(the_anim.height);
1239                 if ( reduced )  {
1240                         bm_bitmaps[n+i].bm.w /= 2;
1241                         bm_bitmaps[n+i].bm.rowsize /= 2;
1242                         bm_bitmaps[n+i].bm.h /= 2;
1243                 }
1244                 bm_bitmaps[n+i].bm.flags = 0;
1245                 bm_bitmaps[n+i].bm.bpp = 0;
1246                 bm_bitmaps[n+i].bm.data = 0;
1247                 bm_bitmaps[n+i].bm.palette = NULL;
1248                 bm_bitmaps[n+i].type = BM_TYPE_ANI;
1249                 bm_bitmaps[n+i].palette_checksum = 0;
1250                 bm_bitmaps[n+i].signature = Bm_next_signature++;
1251                 bm_bitmaps[n+i].handle = first_handle*MAX_BITMAPS + n+i;
1252                 bm_bitmaps[n+i].last_used = -1;
1253
1254                 // fill in section info
1255                 bm_calc_sections(&bm_bitmaps[n+i].bm);
1256
1257                 if ( i == 0 )   {
1258                         sprintf( bm_bitmaps[n+i].filename, "%s", filename );
1259                 } else {
1260                         sprintf( bm_bitmaps[n+i].filename, "%s[%d]", filename, i );
1261                 }
1262         }
1263
1264         return bm_bitmaps[n].handle;
1265 }
1266
1267 // Gets info.   w,h,or flags,nframes or fps can be NULL if you don't care.
1268 void bm_get_info( int handle, int *w, int * h, ubyte * flags, int *nframes, int *fps, bitmap_section_info **sections )
1269 {
1270         bitmap * bmp;
1271
1272         if ( !bm_inited ) return;
1273
1274         int bitmapnum = handle % MAX_BITMAPS;
1275         Assert( bm_bitmaps[bitmapnum].handle == handle );               // INVALID BITMAP HANDLE!       
1276         
1277         if ( (bm_bitmaps[bitmapnum].type == BM_TYPE_NONE) || (bm_bitmaps[bitmapnum].handle != handle) ) {
1278                 if (w) *w = 0;
1279                 if (h) *h = 0;
1280                 if (flags) *flags = 0;
1281                 if (nframes) *nframes=0;
1282                 if (fps) *fps=0;
1283                 if (sections != NULL) *sections = NULL;
1284                 return;
1285         }
1286
1287         bmp = &(bm_bitmaps[bitmapnum].bm);
1288
1289         if (w) *w = bmp->w;
1290         if (h) *h = bmp->h;
1291         if (flags) *flags = bmp->flags;
1292         if ( bm_bitmaps[bitmapnum].type == BM_TYPE_ANI )        {
1293                 if (nframes) {
1294                         *nframes = bm_bitmaps[bitmapnum].info.ani.num_frames;
1295                 } 
1296                 if (fps) {
1297                         *fps= bm_bitmaps[bitmapnum].info.ani.fps;
1298                 }
1299         } else {
1300                 if (nframes) {
1301                         *nframes = 1;
1302                 } 
1303                 if (fps) {
1304                         *fps= 0;
1305                 }
1306         }
1307         if(sections != NULL){
1308                 *sections = &bm_bitmaps[bitmapnum].bm.sections;
1309         }
1310 }
1311
1312 uint bm_get_signature( int handle )
1313 {
1314         if ( !bm_inited ) bm_init();
1315
1316         int bitmapnum = handle % MAX_BITMAPS;
1317         Assert( bm_bitmaps[bitmapnum].handle == handle );               // INVALID BITMAP HANDLE
1318
1319         return bm_bitmaps[bitmapnum].signature;
1320 }
1321
1322 extern int palman_is_nondarkening(int r,int g, int b);
1323 static void bm_convert_format( int bitmapnum, bitmap *bmp, ubyte bpp, ubyte flags )
1324 {       
1325         int idx;        
1326         int r, g, b, a;
1327
1328         if(Fred_running || Pofview_running || Is_standalone){
1329                 Assert(bmp->bpp == 8);
1330
1331                 return;
1332         } else {
1333                 if(flags & BMP_AABITMAP){
1334                         Assert(bmp->bpp == 8);
1335                 } else {
1336                         Assert(bmp->bpp == 16);
1337                 }
1338         }
1339
1340         // maybe swizzle to be an xparent texture
1341         if(!(bmp->flags & BMP_TEX_XPARENT) && (flags & BMP_TEX_XPARENT)){
1342                 for(idx=0; idx<bmp->w*bmp->h; idx++){                   
1343                         
1344                         // if the pixel is transparent
1345                         if ( ((ushort*)bmp->data)[idx] == Gr_t_green.mask)      {
1346                                 switch(Bm_pixel_format){
1347                                 // 1555, all we need to do is zero the whole thing
1348                                 case BM_PIXEL_FORMAT_ARGB:
1349                                 case BM_PIXEL_FORMAT_ARGB_D3D:
1350                                         ((ushort*)bmp->data)[idx] = 0;
1351                                         break;
1352                                 // d3d format
1353                                 case BM_PIXEL_FORMAT_D3D:                                                                       
1354                                         r = g = b = a = 0;
1355                                         r /= Gr_t_red.scale;
1356                                         g /= Gr_t_green.scale;
1357                                         b /= Gr_t_blue.scale;
1358                                         a /= Gr_t_alpha.scale;
1359                                         ((ushort*)bmp->data)[idx] = (unsigned short)((a<<Gr_t_alpha.shift) | (r << Gr_t_red.shift) | (g << Gr_t_green.shift) |  (b << Gr_t_blue.shift));
1360                                         break;
1361                                 default:
1362                                         Int3();
1363                                 }
1364                         }
1365                 }
1366
1367                 bmp->flags |= BMP_TEX_XPARENT;
1368         }       
1369 }
1370
1371 // basically, map the bitmap into the current palette. used to be done for all pcx's, now just for
1372 // Fred, since its the only thing that uses the software tmapper
1373 void bm_swizzle_8bit_for_fred(bitmap_entry *be, bitmap *bmp, ubyte *data, ubyte *palette)
1374 {               
1375         int pcx_xparent_index = -1;
1376         int i;
1377         int r, g, b;
1378         ubyte palxlat[256];
1379
1380         for (i=0; i<256; i++ ) {
1381                 r = palette[i*3];
1382                 g = palette[i*3+1];
1383                 b = palette[i*3+2];
1384                 if ( g == 255 && r == 0 && b == 0 ) {
1385                         palxlat[i] = 255;
1386                         pcx_xparent_index = i;
1387                 } else {                        
1388                         palxlat[i] = (ubyte)(palette_find( r, g, b ));                  
1389                 }
1390         }               
1391         for (i=0; i<bmp->w * bmp->h; i++ ) {            
1392                 ubyte c = palxlat[data[i]];                     
1393                 data[i] = c;            
1394         }                       
1395         be->palette_checksum = gr_palette_checksum;     
1396 }
1397
1398 void bm_lock_pcx( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1399 {       
1400         ubyte *data, *palette;
1401         ubyte pal[768];
1402         palette = NULL;
1403
1404         // Unload any existing data
1405         bm_free_data( bitmapnum );      
1406
1407         // allocate bitmap data
1408         if(bpp == 8){
1409                 // Assert(Fred_running || Pofview_running || Is_standalone);            
1410                         data = (ubyte *)bm_malloc(bitmapnum, bmp->w * bmp->h );
1411                 #ifdef BMPMAN_NDEBUG
1412                         Assert( be->data_size == bmp->w * bmp->h );
1413                 #endif
1414                 palette = pal;
1415                 bmp->data = (ptr_u)data;
1416                 bmp->bpp = 8;
1417                 bmp->palette = gr_palette;
1418                 memset( data, 0, bmp->w * bmp->h);
1419         } else {
1420                 data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 2);       
1421                 bmp->bpp = 16;
1422                 bmp->data = (ptr_u)data;
1423                 bmp->palette = NULL;
1424                 memset( data, 0, bmp->w * bmp->h * 2);
1425         }       
1426
1427         Assert( &be->bm == bmp );
1428         #ifdef BMPMAN_NDEBUG
1429                 Assert( be->data_size > 0 );
1430         #endif
1431
1432         // some sanity checks on flags
1433         Assert(!((flags & BMP_AABITMAP) && (flags & BMP_TEX_ANY)));                                             // no aabitmap textures
1434         Assert(!((flags & BMP_TEX_XPARENT) && (flags & BMP_TEX_NONDARK)));                      // can't be a transparent texture and a nondarkening texture 
1435         Assert(!((flags & BMP_TEX_NONDARK) && (gr_screen.mode == GR_DIRECT3D)));        // D3D should never be trying to get nondarkening textures
1436
1437         if(bpp == 8){
1438                 int pcx_error=pcx_read_bitmap_8bpp( be->filename, data, palette );
1439                 if ( pcx_error != PCX_ERROR_NONE )      {
1440                         // Error( LOCATION, "Couldn't open '%s'\n", be->filename );
1441                         //Error( LOCATION, "Couldn't open '%s'\n", filename );
1442                         //return -1;
1443                 }
1444
1445                 // now swizzle the thing into the proper format
1446                 if(Fred_running || Pofview_running){
1447                         bm_swizzle_8bit_for_fred(be, bmp, data, palette);
1448                 }
1449         } else {        
1450                 int pcx_error;
1451
1452                 // load types
1453                 if(flags & BMP_AABITMAP){
1454                         pcx_error = pcx_read_bitmap_16bpp_aabitmap( be->filename, data );
1455                 } else if(flags & BMP_TEX_NONDARK){
1456                         pcx_error = pcx_read_bitmap_16bpp_nondark( be->filename, data );
1457                 } else {
1458                         pcx_error = pcx_read_bitmap_16bpp( be->filename, data );
1459                 }
1460                 if ( pcx_error != PCX_ERROR_NONE )      {
1461                         // Error( LOCATION, "Couldn't open '%s'\n", be->filename );
1462                         //Error( LOCATION, "Couldn't open '%s'\n", filename );
1463                         //return -1;
1464                 }
1465         }
1466
1467         #ifdef BMPMAN_NDEBUG
1468         Assert( be->data_size > 0 );
1469         #endif          
1470         
1471         bmp->flags = 0; 
1472         bm_convert_format( bitmapnum, bmp, bpp, flags );
1473 }
1474
1475 void bm_lock_ani( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1476 {       
1477         anim                            *the_anim;
1478         anim_instance   *the_anim_instance;
1479         bitmap                  *bm;
1480         ubyte                           *frame_data;
1481         int                             size, i;
1482         int                             first_frame, nframes;   
1483
1484         first_frame = be->info.ani.first_frame;
1485         nframes = bm_bitmaps[first_frame].info.ani.num_frames;
1486
1487         if ( (the_anim = anim_load(bm_bitmaps[first_frame].filename)) == NULL ) {
1488                 // Error(LOCATION, "Error opening %s in bm_lock\n", be->filename);
1489         }
1490
1491         if ( (the_anim_instance = init_anim_instance(the_anim, bpp)) == NULL ) {
1492                 // Error(LOCATION, "Error opening %s in bm_lock\n", be->filename);
1493                 anim_free(the_anim);
1494         }
1495
1496         int can_drop_frames = 0;
1497
1498         if ( the_anim->total_frames != bm_bitmaps[first_frame].info.ani.num_frames )    {
1499                 can_drop_frames = 1;
1500         }
1501         bm = &bm_bitmaps[first_frame].bm;
1502         if(bpp == 16){
1503                 size = bm->w * bm->h * 2;
1504         } else {
1505                 size = bm->w * bm->h;
1506         }
1507                 
1508         for ( i=0; i<nframes; i++ )     {
1509                 be = &bm_bitmaps[first_frame+i];
1510                 bm = &bm_bitmaps[first_frame+i].bm;
1511
1512                 // Unload any existing data
1513                 bm_free_data( first_frame+i );
1514
1515                 bm->flags = 0;
1516                 // briefing editor in Fred2 uses aabitmaps (ani's) - force to 8 bit
1517                 if(Fred_running || Is_standalone){
1518                         bm->bpp = 8;
1519                 } else {
1520                         bm->bpp = bpp;
1521                 }
1522                 bm->data = (ptr_u)bm_malloc(first_frame + i, size);
1523
1524                 frame_data = anim_get_next_raw_buffer(the_anim_instance, 0 ,flags & BMP_AABITMAP ? 1 : 0, bm->bpp);
1525
1526                 if ( frame_data == NULL ) {
1527                         // Error(LOCATION,"Fatal error locking .ani file: %s\n", be->filename);
1528                 }               
1529                 
1530                 ubyte *dptr, *sptr;
1531
1532                 sptr = frame_data;
1533                 dptr = (ubyte *)bm->data;
1534
1535                 if ( (bm->w!=the_anim->width) || (bm->h!=the_anim->height) )    {
1536                         // Scale it down
1537                         // Int3();                      // not ready yet - should only be ingame
1538         
1539                         // 8 bit
1540                         if(bpp == 8){
1541                                 int w,h;
1542                                 fix u, utmp, v, du, dv;
1543
1544                                 u = v = 0;
1545
1546                                 du = ( the_anim->width*F1_0 ) / bm->w;
1547                                 dv = ( the_anim->height*F1_0 ) / bm->h;
1548                                                                                                 
1549                                 for (h = 0; h < bm->h; h++) {
1550                                         ubyte *drow = &dptr[bm->w * h];
1551                                         ubyte *srow = &sptr[f2i(v)*the_anim->width];
1552
1553                                         utmp = u;
1554
1555                                         for (w = 0; w < bm->w; w++) {
1556                                                 *drow++ = srow[f2i(utmp)];
1557                                                 utmp += du;
1558                                         }
1559                                         v += dv;
1560                                 }                       
1561                         }
1562                         // 16 bpp
1563                         else {
1564                                 int w,h;
1565                                 fix u, utmp, v, du, dv;
1566
1567                                 u = v = 0;
1568
1569                                 du = ( the_anim->width*F1_0 ) / bm->w;
1570                                 dv = ( the_anim->height*F1_0 ) / bm->h;
1571                                                                                                 
1572                                 for (h = 0; h < bm->h; h++) {
1573                                         ushort *drow = &((ushort*)dptr)[bm->w * h];
1574                                         ushort *srow = &((ushort*)sptr)[f2i(v)*the_anim->width];
1575
1576                                         utmp = u;
1577
1578                                         for (w = 0; w < bm->w; w++) {
1579                                                 *drow++ = srow[f2i(utmp)];
1580                                                 utmp += du;
1581                                         }
1582                                         v += dv;
1583                                 }                       
1584                         }                       
1585                 } else {
1586                         // 1-to-1 mapping
1587                         memcpy(dptr, sptr, size);
1588                 }               
1589
1590                 bm_convert_format( first_frame+i, bm, bpp, flags );
1591
1592                 // Skip a frame
1593                 if ( (i < nframes-1)  && can_drop_frames )      {
1594                         frame_data = anim_get_next_raw_buffer(the_anim_instance, 0, flags & BMP_AABITMAP ? 1 : 0, bm->bpp);
1595                 }
1596
1597                 //mprintf(( "Checksum = %d\n", be->palette_checksum ));
1598         }
1599
1600         free_anim_instance(the_anim_instance);
1601         anim_free(the_anim);
1602 }
1603
1604
1605 void bm_lock_user( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1606 {
1607         // int idx;     
1608         // ushort bit_16;
1609
1610         // Unload any existing data
1611         bm_free_data( bitmapnum );      
1612
1613         switch( be->info.user.bpp )     {
1614         case 16:                        // user 16 bit bitmap
1615                 bmp->bpp = bpp;
1616                 bmp->flags = be->info.user.flags;               
1617                 bmp->data = (ptr_u)be->info.user.data;                                                          
1618                 break;  
1619         
1620         case 8:                 // Going from 8 bpp to something (probably only for aabitmaps)
1621                 /*
1622                 Assert(flags & BMP_AABITMAP);
1623                 bmp->bpp = 16;
1624                 bmp->data = (uint)malloc(bmp->w * bmp->h * 2);
1625                 bmp->flags = be->info.user.flags;
1626                 bmp->palette = NULL;
1627
1628                 // go through and map the pixels
1629                 for(idx=0; idx<bmp->w * bmp->h; idx++){                 
1630                         bit_16 = (ushort)((ubyte*)be->info.user.data)[idx];                     
1631                         Assert(bit_16 <= 255);
1632
1633                         // stuff the final result
1634                         memcpy((char*)bmp->data + (idx * 2), &bit_16, sizeof(ushort));
1635                 }
1636                 */              
1637                 Assert(flags & BMP_AABITMAP);
1638                 bmp->bpp = bpp;
1639                 bmp->flags = be->info.user.flags;               
1640                 bmp->data = (ptr_u)be->info.user.data;                                                          
1641                 break;
1642                 
1643         // default:
1644                 // Error( LOCATION, "Unhandled user bitmap conversion from %d to %d bpp", be->info.user.bpp, bmp->bpp );
1645         }
1646
1647         bm_convert_format( bitmapnum, bmp, bpp, flags );
1648 }
1649
1650 void bm_lock_tga( int handle, int bitmapnum, bitmap_entry *be, bitmap *bmp, ubyte bpp, ubyte flags )
1651 {
1652         ubyte *data;    
1653
1654         // Unload any existing data
1655         bm_free_data( bitmapnum );      
1656
1657         if(Fred_running || Is_standalone){
1658                 Assert(bpp == 8);
1659         } else {
1660                 Assert(bpp == 16);
1661         }
1662
1663         // should never try to make an aabitmap out of a targa
1664         Assert(!(flags & BMP_AABITMAP));
1665
1666         // allocate bitmap data 
1667         if(bpp == 16){
1668                 data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h * 2);       
1669         } else {
1670                 data = (ubyte*)bm_malloc(bitmapnum, bmp->w * bmp->h);   
1671         }
1672         bmp->bpp = bpp;
1673         bmp->data = (ptr_u)data;
1674         bmp->palette = NULL;
1675         if(bpp == 16){
1676                 memset( data, 0, bmp->w * bmp->h * 2);  
1677         } else {
1678                 memset( data, 0, bmp->w * bmp->h );     
1679         }
1680
1681         Assert( &be->bm == bmp );
1682         #ifdef BMPMAN_NDEBUG
1683         Assert( be->data_size > 0 );
1684         #endif
1685         
1686         int tga_error=targa_read_bitmap( be->filename, data, NULL, (bpp == 16) ? 2 : 1);
1687         if ( tga_error != TARGA_ERROR_NONE )    {
1688                 // Error( LOCATION, "Couldn't open '%s'\n", be->filename );
1689                 //Error( LOCATION, "Couldn't open '%s'\n", filename );
1690                 //return -1;
1691         }
1692
1693         #ifdef BMPMAN_NDEBUG
1694         Assert( be->data_size > 0 );
1695         #endif          
1696         
1697         bmp->flags = 0; 
1698         bm_convert_format( bitmapnum, bmp, bpp, flags );
1699 }
1700
1701 MONITOR( NumBitmapPage );
1702 MONITOR( SizeBitmapPage );
1703
1704 // This locks down a bitmap and returns a pointer to a bitmap
1705 // that can be accessed until you call bm_unlock.   Only lock
1706 // a bitmap when you need it!  This will convert it into the 
1707 // appropriate format also.
1708 bitmap * bm_lock( int handle, ubyte bpp, ubyte flags )
1709 {
1710         bitmap                  *bmp;
1711         bitmap_entry    *be;
1712
1713
1714         if ( !bm_inited ) bm_init();
1715
1716         int bitmapnum = handle % MAX_BITMAPS;
1717         Assert( bm_bitmaps[bitmapnum].handle == handle );               // INVALID BITMAP HANDLE
1718
1719 //      flags &= (~BMP_RLE);
1720
1721         // if we're on a standalone server, aways for it to lock to 8 bits
1722         if(Is_standalone){
1723                 bpp = 8;
1724                 flags = 0;
1725         } 
1726         // otherwise do it as normal
1727         else {
1728                 if(Fred_running || Pofview_running){
1729                         Assert( bpp == 8 );
1730                         Assert( (bm_bitmaps[bitmapnum].type == BM_TYPE_PCX) || (bm_bitmaps[bitmapnum].type == BM_TYPE_ANI) || (bm_bitmaps[bitmapnum].type == BM_TYPE_TGA));
1731                 } else {
1732                         if(flags & BMP_AABITMAP){
1733                                 Assert( bpp == 8 );
1734                         } else {
1735                                 Assert( bpp == 16 );
1736                         }
1737                 }
1738         }
1739
1740         be = &bm_bitmaps[bitmapnum];
1741         bmp = &be->bm;
1742
1743         // If you hit this assert, chances are that someone freed the
1744         // wrong bitmap and now someone is trying to use that bitmap.
1745         // See John.
1746         Assert( be->type != BM_TYPE_NONE );             
1747
1748         // Increment ref count for bitmap since lock was made on it.
1749         Assert(be->ref_count >= 0);
1750         be->ref_count++;                                        // Lock it before we page in data; this prevents a callback from freeing this
1751                                                                                         // as it gets read in
1752
1753         // Mark this bitmap as used this frame
1754         #ifdef BMPMAN_NDEBUG
1755         if ( be->used_this_frame < 255 )        {
1756                 be->used_this_frame++;
1757         }
1758         #endif
1759
1760         // if bitmap hasn't been loaded yet, then load it from disk
1761         // reread the bitmap from disk under certain conditions
1762         int pal_changed = 0;
1763         int rle_changed = 0;
1764         int fake_xparent_changed = 0;   
1765         if ( (bmp->data == 0) || (bpp != bmp->bpp) || pal_changed || rle_changed || fake_xparent_changed ) {
1766                 Assert(be->ref_count == 1);
1767
1768                 if ( be->type != BM_TYPE_USER ) {
1769                         if ( bmp->data == 0 ) {
1770                                 nprintf (("BmpMan","Loading %s for the first time.\n", be->filename));
1771                         } else if ( bpp != bmp->bpp ) {
1772                                 nprintf (("BmpMan","Reloading %s from bitdepth %d to bitdepth %d\n", be->filename, bmp->bpp, bpp));
1773                         } else if ( pal_changed ) {
1774                                 nprintf (("BmpMan","Reloading %s to remap palette\n", be->filename));
1775                         } else if ( rle_changed )       {
1776                                 nprintf (("BmpMan","Reloading %s to change RLE.\n", be->filename));
1777                         } else if ( fake_xparent_changed )      {
1778                                 nprintf (("BmpMan","Reloading %s to change fake xparency.\n", be->filename));
1779                         }
1780                 }
1781
1782                 MONITOR_INC( NumBitmapPage, 1 );
1783                 MONITOR_INC( SizeBitmapPage, bmp->w*bmp->h );
1784
1785                 if ( !Bm_paging )       {
1786                         if ( be->type != BM_TYPE_USER ) {
1787                                 char flag_text[64];
1788                                 strcpy( flag_text, "--" );                                                      
1789                                 nprintf(( "Paging", "Loading %s (%dx%dx%dx%s)\n", be->filename, bmp->w, bmp->h, bpp, flag_text ));
1790                         }
1791                 }
1792
1793                 // select proper format
1794                 if(flags & BMP_AABITMAP){
1795                         BM_SELECT_ALPHA_TEX_FORMAT();
1796                 } else if(flags & BMP_TEX_ANY){
1797                         BM_SELECT_TEX_FORMAT();                                 
1798                 } else {
1799                         BM_SELECT_SCREEN_FORMAT();
1800                 }
1801
1802                 switch ( be->type ) {
1803                 case BM_TYPE_PCX:
1804                         bm_lock_pcx( handle, bitmapnum, be, bmp, bpp, flags );
1805                         break;
1806
1807                 case BM_TYPE_ANI: 
1808                         bm_lock_ani( handle, bitmapnum, be, bmp, bpp, flags );
1809                         break;
1810
1811                 case BM_TYPE_USER:      
1812                         bm_lock_user( handle, bitmapnum, be, bmp, bpp, flags );
1813                         break;
1814
1815                 case BM_TYPE_TGA:
1816                         bm_lock_tga( handle, bitmapnum, be, bmp, bpp, flags );
1817                         break;
1818
1819                 default:
1820                         Warning(LOCATION, "Unsupported type in bm_lock -- %d\n", be->type );
1821                         return NULL;
1822                 }               
1823
1824                 // always go back to screen format
1825                 BM_SELECT_SCREEN_FORMAT();
1826         }
1827
1828         if ( be->type == BM_TYPE_ANI ) {
1829                 int i,first = bm_bitmaps[bitmapnum].info.ani.first_frame;
1830
1831                 for ( i=0; i< bm_bitmaps[first].info.ani.num_frames; i++ )      {
1832                         // Mark all the bitmaps in this bitmap or animation as recently used
1833                         bm_bitmaps[first+i].last_used = timer_get_milliseconds();
1834
1835                         // Mark all the bitmaps in this bitmap or animation as used for the usage tracker.
1836                         #ifdef BMPMAN_NDEBUG
1837                                 bm_bitmaps[first+i].used_count++;
1838                         #endif
1839                         bm_bitmaps[first+i].used_flags = flags;
1840                 }
1841         } else {
1842                 // Mark all the bitmaps in this bitmap or animation as recently used
1843                 be->last_used = timer_get_milliseconds();
1844
1845                 // Mark all the bitmaps in this bitmap or animation as used for the usage tracker.
1846                 #ifdef BMPMAN_NDEBUG
1847                         be->used_count++;
1848                 #endif
1849                 be->used_flags = flags;
1850         }
1851
1852         return bmp;
1853 }
1854
1855 // Unlocks a bitmap
1856 //
1857 // Decrements the ref_count member of the bitmap_entry struct.  A bitmap can only be unloaded
1858 // when the ref_count is 0.
1859 //
1860 void bm_unlock( int handle )
1861 {
1862         bitmap_entry    *be;
1863         bitmap                  *bmp;
1864
1865         int bitmapnum = handle % MAX_BITMAPS;
1866         Assert( bm_bitmaps[bitmapnum].handle == handle );       // INVALID BITMAP HANDLE
1867
1868         Assert(bitmapnum >= 0 && bitmapnum < MAX_BITMAPS);
1869         if ( !bm_inited ) bm_init();
1870
1871         be = &bm_bitmaps[bitmapnum];
1872         bmp = &be->bm;
1873
1874         be->ref_count--;
1875         Assert(be->ref_count >= 0);             // Trying to unlock data more times than lock was called!!!
1876
1877 }
1878
1879
1880 void bm_update()
1881 {
1882 }
1883
1884 char *bm_get_filename(int handle)
1885 {
1886         int n;
1887
1888         n = handle % MAX_BITMAPS;
1889         Assert(bm_bitmaps[n].handle == handle);         // INVALID BITMAP HANDLE
1890         return bm_bitmaps[n].filename;
1891 }
1892
1893 void bm_get_palette(int handle, ubyte *pal, char *name)
1894 {
1895         char *filename;
1896         int w,h;
1897
1898         int n= handle % MAX_BITMAPS;
1899         Assert( bm_bitmaps[n].handle == handle );               // INVALID BITMAP HANDLE
1900
1901         filename = bm_bitmaps[n].filename;
1902
1903         if (name)       {
1904                 strcpy( name, filename );
1905         }
1906
1907         int pcx_error=pcx_read_header( filename, &w, &h, pal );
1908         if ( pcx_error != PCX_ERROR_NONE ){
1909                 // Error(LOCATION, "Couldn't open '%s'\n", filename );
1910         }
1911 }
1912
1913 // --------------------------------------------------------------------------------------
1914 // bm_release()  - unloads the bitmap's data and entire slot, so bitmap 'n' won't be valid anymore
1915 //
1916 // parameters:          n               =>              index into bm_bitmaps ( index returned from bm_load() or bm_create() )
1917 //
1918 // returns:                     nothing
1919
1920 // opengl hack
1921 void opengl_free_texture_with_handle(int handle);
1922 void bm_release(int handle)
1923 {
1924         bitmap_entry    *be;
1925
1926         int n = handle % MAX_BITMAPS;
1927
1928         Assert(n >= 0 && n < MAX_BITMAPS);
1929         be = &bm_bitmaps[n];
1930
1931         if ( bm_bitmaps[n].type == BM_TYPE_NONE ) {
1932                 return; // Already been released?
1933         }
1934
1935         if ( bm_bitmaps[n].type != BM_TYPE_USER )       {
1936                 return;
1937         }
1938
1939         Assert( be->handle == handle );         // INVALID BITMAP HANDLE
1940
1941         // If it is locked, cannot free it.
1942         if (be->ref_count != 0) {
1943                 nprintf(("BmpMan", "tried to unload %s that has a lock count of %d.. not unloading\n", be->filename, be->ref_count));
1944                 return;
1945         }
1946
1947 // until opengl mode gets a proper texture manager, this will have to do
1948 #ifdef PLAT_UNIX
1949         opengl_free_texture_with_handle(handle);
1950 #endif
1951
1952         bm_free_data(n);
1953
1954         if ( bm_bitmaps[n].type == BM_TYPE_USER )       {
1955                 bm_bitmaps[n].info.user.data = NULL;
1956                 bm_bitmaps[n].info.user.bpp = 0;
1957         }
1958
1959
1960         bm_bitmaps[n].type = BM_TYPE_NONE;
1961
1962         // Fill in bogus structures!
1963
1964         // For debugging:
1965         strcpy( bm_bitmaps[n].filename, "IVE_BEEN_RELEASED!" );
1966         bm_bitmaps[n].signature = 0xDEADBEEF;                                                                   // a unique signature identifying the data
1967         bm_bitmaps[n].palette_checksum = 0xDEADBEEF;                                                    // checksum used to be sure bitmap is in current palette
1968
1969         // bookeeping
1970         #ifdef BMPMAN_NDEBUG
1971         bm_bitmaps[n].data_size = -1;                                                                   // How much data this bitmap uses
1972         #endif
1973         bm_bitmaps[n].ref_count = -1;                                                                   // Number of locks on bitmap.  Can't unload unless ref_count is 0.
1974
1975         // Bitmap info
1976         bm_bitmaps[n].bm.w = bm_bitmaps[n].bm.h = -1;
1977         
1978         // Stuff needed for animations
1979         // Stuff needed for user bitmaps
1980         memset( &bm_bitmaps[n].info, 0, sizeof(bm_extra_info) );
1981
1982         bm_bitmaps[n].handle = -1;
1983 }
1984
1985
1986
1987
1988
1989
1990 // --------------------------------------------------------------------------------------
1991 // bm_unload()  - unloads the data, but not the bitmap info.
1992 //
1993 // parameters:          n               =>              index into bm_bitmaps ( index returned from bm_load() or bm_create() )
1994 //
1995 // returns:                     0               =>              unload failed
1996 //                                              1               =>              unload successful
1997 //
1998 int bm_unload( int handle )
1999 {
2000         bitmap_entry    *be;
2001         bitmap                  *bmp;
2002
2003         int n = handle % MAX_BITMAPS;
2004
2005         Assert(n >= 0 && n < MAX_BITMAPS);
2006         be = &bm_bitmaps[n];
2007         bmp = &be->bm;
2008
2009         if ( be->type == BM_TYPE_NONE ) {
2010                 return 0;               // Already been released
2011         }
2012
2013         Assert( be->handle == handle );         // INVALID BITMAP HANDLE!
2014
2015         // If it is locked, cannot free it.
2016         if (be->ref_count != 0) {
2017                 nprintf(("BmpMan", "tried to unload %s that has a lock count of %d.. not unloading\n", be->filename, be->ref_count));
2018                 return 0;
2019         }
2020
2021         nprintf(("BmpMan", "unloading %s.  %dx%dx%d\n", be->filename, bmp->w, bmp->h, bmp->bpp));
2022         bm_free_data(n);                // clears flags, bbp, data, etc
2023
2024         return 1;
2025 }
2026
2027
2028 // unload all used bitmaps
2029 void bm_unload_all()
2030 {
2031         int i;
2032
2033         for (i = 0; i < MAX_BITMAPS; i++)       {
2034                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2035                         bm_unload(bm_bitmaps[i].handle);
2036                 }
2037         }
2038 }
2039
2040
2041 DCF(bmpman,"Shows/changes bitmap caching parameters and usage")
2042 {
2043         if ( Dc_command )       {
2044                 dc_get_arg(ARG_STRING);
2045                 if ( !strcmp( Dc_arg, "flush" ))        {
2046                         dc_printf( "Total RAM usage before flush: %d bytes\n", bm_texture_ram );
2047                         int i;
2048                         for (i = 0; i < MAX_BITMAPS; i++)       {
2049                                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2050                                         bm_free_data(i);
2051                                 }
2052                         }
2053                         dc_printf( "Total RAM after flush: %d bytes\n", bm_texture_ram );
2054                 } else if ( !strcmp( Dc_arg, "ram" ))   {
2055                         dc_get_arg(ARG_INT);
2056                         Bm_max_ram = Dc_arg_int*1024*1024;
2057                 } else {
2058                         // print usage, not stats
2059                         Dc_help = 1;
2060                 }
2061         }
2062
2063         if ( Dc_help )  {
2064                 dc_printf( "Usage: BmpMan keyword\nWhere keyword can be in the following forms:\n" );
2065                 dc_printf( "BmpMan flush    Unloads all bitmaps.\n" );
2066                 dc_printf( "BmpMan ram x    Sets max mem usage to x MB. (Set to 0 to have no limit.)\n" );
2067                 dc_printf( "\nUse '? BmpMan' to see status of Bitmap manager.\n" );
2068                 Dc_status = 0;  // don't print status if help is printed.  Too messy.
2069         }
2070
2071         if ( Dc_status )        {
2072                 dc_printf( "Total RAM usage: %d bytes\n", bm_texture_ram );
2073
2074
2075                 if ( Bm_max_ram > 1024*1024 )
2076                         dc_printf( "Max RAM allowed: %.1f MB\n", i2fl(Bm_max_ram)/(1024.0f*1024.0f) );
2077                 else if ( Bm_max_ram > 1024 )
2078                         dc_printf( "Max RAM allowed: %.1f KB\n", i2fl(Bm_max_ram)/(1024.0f) );
2079                 else if ( Bm_max_ram > 0 )
2080                         dc_printf( "Max RAM allowed: %d bytes\n", Bm_max_ram );
2081                 else
2082                         dc_printf( "No RAM limit\n" );
2083
2084
2085         }
2086 }
2087
2088 // Marks a texture as being used for this level
2089 void bm_page_in_texture( int bitmapnum, int nframes )
2090 {
2091         int i;
2092         for (i=0; i<nframes;i++ )       {
2093                 int n = bitmapnum % MAX_BITMAPS;
2094
2095                 bm_bitmaps[n+i].preloaded = 1;
2096
2097                 if ( D3D_enabled )      {
2098                         bm_bitmaps[n+i].used_flags = BMP_TEX_OTHER;
2099                 } else {                        
2100                         bm_bitmaps[n+i].used_flags = 0;
2101                 }
2102         }
2103 }
2104
2105 // Marks a texture as being used for this level
2106 // If num_frames is passed, assume this is an animation
2107 void bm_page_in_nondarkening_texture( int bitmapnum, int nframes )
2108 {
2109         int i;
2110         for (i=0; i<nframes;i++ )       {
2111                 int n = bitmapnum % MAX_BITMAPS;
2112
2113                 bm_bitmaps[n+i].preloaded = 4;
2114
2115                 if ( D3D_enabled )      {                       
2116                         bm_bitmaps[n+i].used_flags = BMP_TEX_NONDARK;
2117                 } else {
2118                         bm_bitmaps[n+i].used_flags = 0;
2119                 }
2120         }
2121 }
2122
2123 // marks a texture as being a transparent textyre used for this level
2124 // Marks a texture as being used for this level
2125 // If num_frames is passed, assume this is an animation
2126 void bm_page_in_xparent_texture( int bitmapnum, int nframes)
2127 {
2128         int i;
2129         for (i=0; i<nframes;i++ )       {
2130                 int n = bitmapnum % MAX_BITMAPS;
2131
2132                 bm_bitmaps[n+i].preloaded = 3;
2133
2134                 if ( D3D_enabled )      {
2135                         // bm_bitmaps[n+i].used_flags = BMP_NO_PALETTE_MAP;
2136                         bm_bitmaps[n+i].used_flags = BMP_TEX_XPARENT;
2137                 } else {
2138                         bm_bitmaps[n+i].used_flags = 0;
2139                 }
2140         }
2141 }
2142
2143 // Marks an aabitmap as being used for this level
2144 void bm_page_in_aabitmap( int bitmapnum, int nframes )
2145 {
2146         int i;
2147
2148         for (i=0; i<nframes;i++ )       {
2149                 int n = bitmapnum % MAX_BITMAPS;
2150
2151                 bm_bitmaps[n+i].preloaded = 2;
2152         
2153                 if ( D3D_enabled )      {
2154                         bm_bitmaps[n+i].used_flags = BMP_AABITMAP;
2155                 } else {
2156                         bm_bitmaps[n+i].used_flags = 0;
2157                 }
2158         }
2159 }
2160
2161
2162
2163 // Tell the bitmap manager to start keeping track of what bitmaps are used where.
2164 void bm_page_in_start()
2165 {
2166         int i;
2167
2168         Bm_paging = 1;
2169
2170         // Mark all as inited
2171         for (i = 0; i < MAX_BITMAPS; i++)       {
2172                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2173                         bm_unload(bm_bitmaps[i].handle);
2174                 }
2175                 bm_bitmaps[i].preloaded = 0;
2176                 #ifdef BMPMAN_NDEBUG
2177                         bm_bitmaps[i].used_count = 0;
2178                 #endif
2179                 bm_bitmaps[i].used_flags = 0;
2180         }
2181
2182 }
2183
2184 #ifndef PLAT_UNIX
2185 extern void gr_d3d_preload_init();
2186 extern int gr_d3d_preload(int bitmap_num, int is_aabitmap );
2187 #endif
2188 extern void gr_opengl_preload_init();
2189 extern int gr_opengl_preload(int bitmap_num, int is_aabitmap );
2190
2191 void bm_page_in_stop()
2192 {       
2193         int i;  
2194         int ship_info_index;
2195
2196         nprintf(( "BmpInfo","BMPMAN: Loading all used bitmaps.\n" ));
2197
2198         // Load all the ones that are supposed to be loaded for this level.
2199         int n = 0;
2200
2201         #ifdef BMPMAN_NDEBUG
2202         Bm_ram_freed = 0;
2203         #endif
2204
2205         int d3d_preloading = 1;
2206
2207 #ifndef PLAT_UNIX
2208         if (gr_screen.mode == GR_DIRECT3D) {
2209                 gr_d3d_preload_init();
2210         } else
2211 #endif  
2212         if (gr_screen.mode == GR_OPENGL) {
2213                 gr_opengl_preload_init();
2214         }
2215
2216         for (i = 0; i < MAX_BITMAPS; i++)       {
2217                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2218                         if ( bm_bitmaps[i].preloaded )  {
2219 #ifdef BMPMAN_SPECIAL_NONDARK
2220                                 // if this is a texture, check to see if a ship uses it
2221                                 ship_info_index = ship_get_texture(bm_bitmaps[i].handle);
2222                                 // use the colors from this ship
2223                                 if((ship_info_index >= 0) && (Ship_info[ship_info_index].num_nondark_colors > 0)){
2224                                         // mprintf(("Using custom pixels for %s\n", Ship_info[ship_info_index].name));
2225                                         palman_set_nondarkening(Ship_info[ship_info_index].nondark_colors, Ship_info[ship_info_index].num_nondark_colors);
2226                                 }
2227                                 // use the colors from the default table
2228                                 else {
2229                                         // mprintf(("Using default pixels\n"));
2230                                         palman_set_nondarkening(Palman_non_darkening_default, Palman_num_nondarkening_default);
2231                                 }
2232 #endif
2233
2234                                 // if preloaded == 3, load it as an xparent texture                             
2235                                 if(bm_bitmaps[i].used_flags == BMP_AABITMAP){
2236                                         bm_lock( bm_bitmaps[i].handle, 8, bm_bitmaps[i].used_flags );
2237                                 } else {
2238                                         bm_lock( bm_bitmaps[i].handle, 16, bm_bitmaps[i].used_flags );
2239                                 }
2240                                 bm_unlock( bm_bitmaps[i].handle );
2241
2242                                 if ( d3d_preloading )   {
2243 #ifndef PLAT_UNIX
2244                                         if (gr_screen.mode == GR_DIRECT3D) {
2245                                                 if ( !gr_d3d_preload(bm_bitmaps[i].handle, (bm_bitmaps[i].preloaded==2) ) )     {
2246                                                         mprintf(( "Out of VRAM.  Done preloading.\n" ));
2247                                                         d3d_preloading = 0;
2248                                                 }
2249                                         } else 
2250 #endif                                  
2251                                         if (gr_screen.mode == GR_OPENGL) {
2252                                                 if ( !gr_opengl_preload(bm_bitmaps[i].handle, (bm_bitmaps[i].preloaded==2) ) )  {
2253                                                         mprintf(( "Out of VRAM.  Done preloading.\n" ));
2254                                                         d3d_preloading = 0;
2255                                                 }
2256                                         }
2257                                 }
2258                                 
2259                                 n++;
2260                                 #ifdef BMPMAN_NDEBUG
2261                                 if ( Bm_ram_freed )     {
2262                                         nprintf(( "BmpInfo","BMPMAN: Not enough cache memory to load all level bitmaps\n" ));
2263                                         break;
2264                                 }
2265                                 #endif
2266                         } 
2267                 }
2268                 game_busy();
2269         }
2270         nprintf(( "BmpInfo","BMPMAN: Loaded %d bitmaps that are marked as used for this level.\n", n ));
2271
2272         int total_bitmaps = 0;
2273         for (i = 0; i < MAX_BITMAPS; i++)       {
2274                 if ( bm_bitmaps[i].type != BM_TYPE_NONE )       {
2275                         total_bitmaps++;
2276                 }
2277                 if ( bm_bitmaps[i].type == BM_TYPE_USER )       {
2278                         mprintf(( "User bitmap '%s'\n", bm_bitmaps[i].filename ));
2279                 }
2280         }       
2281
2282         mprintf(( "Bmpman: %d/%d bitmap slots in use.\n", total_bitmaps, MAX_BITMAPS ));
2283         //mprintf(( "Bmpman: Usage went from %d KB to %d KB.\n", usage_before/1024, usage_after/1024 ));
2284
2285         Bm_paging = 0;
2286 }
2287
2288 int bm_get_cache_slot( int bitmap_id, int separate_ani_frames )
2289 {
2290         int n = bitmap_id % MAX_BITMAPS;
2291
2292         Assert( bm_bitmaps[n].handle == bitmap_id );            // INVALID BITMAP HANDLE
2293
2294         bitmap_entry    *be = &bm_bitmaps[n];
2295
2296         if ( (!separate_ani_frames) && (be->type == BM_TYPE_ANI) )      {
2297                 return be->info.ani.first_frame;
2298         } 
2299
2300         return n;
2301
2302 }
2303
2304 // convert a 24 bit value to a 16 bit value
2305 void bm_24_to_16(int bit_24, ushort *bit_16)
2306 {
2307         ubyte *pixel = (ubyte*)&bit_24;
2308         ubyte alpha = 1;
2309
2310         bm_set_components((ubyte*)bit_16, (ubyte*)&pixel[0], (ubyte*)&pixel[1], (ubyte*)&pixel[2], &alpha);     
2311 }
2312
2313 extern int D3D_32bit;
2314
2315 void (*bm_set_components)(ubyte *pixel, ubyte *r, ubyte *g, ubyte *b, ubyte *a) = NULL;
2316
2317 void bm_set_components_argb(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2318 {
2319         // rgba 
2320         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2321         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2322         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2323         *((ushort*)pixel) &= ~(0x8000);
2324         if (*((ushort*)pixel) == (ushort)Gr_current_green->mask) {
2325                 *((ushort*)pixel) = 0;
2326         } else {
2327                 if(*av){
2328                         *((ushort*)pixel) |= 0x8000;
2329                 }
2330         }
2331 }
2332
2333 void bm_set_components_d3d(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2334 {
2335         // rgba 
2336         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2337         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2338         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2339         if(*av == 0){ 
2340                 *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2341         }
2342 }
2343
2344 void bm_set_components_argb_d3d_16_screen(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2345 {
2346         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2347         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2348         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2349         if(*av == 0){                           
2350                 *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2351         }                       
2352 }
2353
2354 void bm_set_components_argb_d3d_32_screen(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2355 {
2356         *((uint*)pixel) |= (uint)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2357         *((uint*)pixel) |= (uint)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2358         *((uint*)pixel) |= (uint)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2359         if(*av == 0){                           
2360                 *((uint*)pixel) = (uint)Gr_current_green->mask;         
2361         }
2362 }
2363
2364 void bm_set_components_argb_d3d_16_tex(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2365 {
2366         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2367         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2368         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2369         *((ushort*)pixel) &= ~(Gr_current_alpha->mask);
2370         if(*av){
2371                 *((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
2372         } else {
2373                 *((ushort*)pixel) = 0;
2374         }
2375 }
2376
2377 void bm_set_components_argb_d3d_32_tex(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2378 {
2379         *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2380         *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2381         *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2382         *((ushort*)pixel) &= ~(Gr_current_alpha->mask);
2383         if(*av){
2384                 *((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
2385         } else {
2386                 *((ushort*)pixel) = 0;
2387         }
2388 }
2389
2390 // for selecting pixel formats
2391 void BM_SELECT_SCREEN_FORMAT()
2392 {
2393         Gr_current_red = &Gr_red;
2394         Gr_current_green = &Gr_green;
2395         Gr_current_blue = &Gr_blue;
2396         Gr_current_alpha = &Gr_alpha;
2397
2398         // setup pointers
2399         if(gr_screen.mode == GR_GLIDE){
2400 #ifndef PLAT_UNIX
2401                 bm_set_components = bm_set_components_argb;
2402 #endif
2403         } else if(gr_screen.mode == GR_DIRECT3D){
2404                 if(Bm_pixel_format == BM_PIXEL_FORMAT_D3D){
2405                         bm_set_components = bm_set_components_d3d;
2406                 } else {
2407                         if(D3D_32bit){
2408                                 bm_set_components = bm_set_components_argb_d3d_32_screen;
2409                         } else {
2410                                 bm_set_components = bm_set_components_argb_d3d_16_screen;
2411                         }
2412                 }
2413         } else if(gr_screen.mode == GR_SOFTWARE){
2414                 bm_set_components = bm_set_components_argb;
2415         } else if(gr_screen.mode == GR_OPENGL){
2416                 bm_set_components = bm_set_components_argb_d3d_32_screen;
2417         }
2418 }
2419
2420 void BM_SELECT_TEX_FORMAT()
2421 {
2422         Gr_current_red = &Gr_t_red; 
2423         Gr_current_green = &Gr_t_green; 
2424         Gr_current_blue = &Gr_t_blue; 
2425         Gr_current_alpha = &Gr_t_alpha;
2426
2427         // setup pointers
2428         if(gr_screen.mode == GR_GLIDE){
2429                 bm_set_components = bm_set_components_argb;
2430         } else if(gr_screen.mode == GR_DIRECT3D){
2431                 if(Bm_pixel_format == BM_PIXEL_FORMAT_D3D){
2432                         bm_set_components = bm_set_components_d3d;
2433                 } else {
2434                         if(D3D_32bit){
2435                                 bm_set_components = bm_set_components_argb_d3d_32_tex;
2436                         } else {
2437                                 bm_set_components = bm_set_components_argb_d3d_16_tex;
2438                         }
2439                 }
2440         } else if(gr_screen.mode == GR_SOFTWARE){
2441                 bm_set_components = bm_set_components_argb;
2442         } else if(gr_screen.mode == GR_OPENGL){
2443                 bm_set_components = bm_set_components_argb_d3d_32_tex;
2444         }
2445 }
2446
2447 void BM_SELECT_ALPHA_TEX_FORMAT()
2448 {
2449         Gr_current_red = &Gr_ta_red; 
2450         Gr_current_green = &Gr_ta_green; 
2451         Gr_current_blue = &Gr_ta_blue; 
2452         Gr_current_alpha = &Gr_ta_alpha;
2453
2454         // setup pointers
2455         if(gr_screen.mode == GR_GLIDE){
2456                 bm_set_components = bm_set_components_argb;
2457         } else if(gr_screen.mode == GR_DIRECT3D){
2458                 if(Bm_pixel_format == BM_PIXEL_FORMAT_D3D){
2459                         bm_set_components = bm_set_components_d3d;
2460                 } else {
2461                         if(D3D_32bit){
2462                                 bm_set_components = bm_set_components_argb_d3d_32_tex;
2463                         } else {
2464                                 bm_set_components = bm_set_components_argb_d3d_16_tex;
2465                         }
2466                 }
2467         } else if(gr_screen.mode == GR_SOFTWARE){
2468                 bm_set_components = bm_set_components_argb;
2469         } else if(gr_screen.mode == GR_OPENGL){
2470                 bm_set_components = bm_set_components_argb_d3d_32_tex;
2471         }
2472 }
2473
2474 // set the rgba components of a pixel, any of the parameters can be -1
2475 /*
2476 void bm_set_components(ubyte *pixel, ubyte *rv, ubyte *gv, ubyte *bv, ubyte *av)
2477 {
2478         int bit_32 = 0;
2479
2480         // pick a byte size - 32 bits only if 32 bit mode d3d and screen format
2481         if(D3D_32bit && (Gr_current_red == &Gr_red)){
2482                 bit_32 = 1;
2483         }       
2484         
2485         if(bit_32){
2486                 *((uint*)pixel) |= (uint)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2487         } else {
2488                 *((ushort*)pixel) |= (ushort)(( (int)*rv / Gr_current_red->scale ) << Gr_current_red->shift);
2489         }               
2490         if(bit_32){
2491                 *((uint*)pixel) |= (uint)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2492         } else {
2493                 *((ushort*)pixel) |= (ushort)(( (int)*gv / Gr_current_green->scale ) << Gr_current_green->shift);
2494         }               
2495         if(bit_32){
2496                 *((uint*)pixel) |= (uint)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2497         } else {
2498                 *((ushort*)pixel) |= (ushort)(( (int)*bv / Gr_current_blue->scale ) << Gr_current_blue->shift);
2499         }
2500         
2501         // 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
2502         //        ergo, we need to do this _last_
2503         switch(Bm_pixel_format){
2504         // glide has an alpha channel so we have to unset ir or set it each time
2505         case BM_PIXEL_FORMAT_ARGB:
2506                 Assert(!bit_32);
2507                 *((ushort*)pixel) &= ~(0x8000);
2508                 if(*av){
2509                         *((ushort*)pixel) |= 0x8000;
2510                 }
2511                 break;
2512         
2513         // this d3d format has no alpha channel, so only make it "transparent", never make it "non-transparent"
2514         case BM_PIXEL_FORMAT_D3D:                       
2515                 Assert(!bit_32);
2516                 if(*av == 0){ 
2517                         *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2518                 }
2519                 break;
2520
2521         // nice 1555 texture format
2522         case BM_PIXEL_FORMAT_ARGB_D3D:                                          
2523                 // if we're writing to normal texture format
2524                 if(Gr_current_red == &Gr_t_red){                                        
2525                         Assert(!bit_32);
2526                         *((ushort*)pixel) &= ~(Gr_current_alpha->mask);
2527                         if(*av){
2528                                 *((ushort*)pixel) |= (ushort)(Gr_current_alpha->mask);
2529                         } else {
2530                                 *((ushort*)pixel) = 0;
2531                         }
2532                 }
2533                 // otherwise if we're writing to screen format, still do it the green mask way
2534                 else {                  
2535                         if(*av == 0){
2536                                 if(bit_32){
2537                                         *((uint*)pixel) = (uint)Gr_current_green->mask;
2538                                 } else {
2539                                         *((ushort*)pixel) = (ushort)Gr_current_green->mask;
2540                                 }
2541                         }
2542                 }                       
2543                 break;
2544         }       
2545 }
2546 */
2547
2548 // get the rgba components of a pixel, any of the parameters can be NULL
2549 void bm_get_components(ubyte *pixel, ubyte *r, ubyte *g, ubyte *b, ubyte *a)
2550 {
2551         int bit_32 = 0;
2552
2553         // pick a byte size - 32 bits only if 32 bit mode d3d and screen format
2554         if(D3D_32bit && (Gr_current_red == &Gr_red)){
2555                 bit_32 = 1;
2556         }
2557
2558         if(r != NULL){
2559                 if(bit_32){
2560                         *r = ubyte(( (*((uint*)pixel) & Gr_current_red->mask)>>Gr_current_red->shift)*Gr_current_red->scale);
2561                 } else {
2562                         *r = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_red->mask)>>Gr_current_red->shift)*Gr_current_red->scale);
2563                 }
2564         }
2565         if(g != NULL){
2566                 if(bit_32){
2567                         *g = ubyte(( (*((uint*)pixel) & Gr_current_green->mask) >>Gr_current_green->shift)*Gr_current_green->scale);
2568                 } else {
2569                         *g = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_green->mask) >>Gr_current_green->shift)*Gr_current_green->scale);
2570                 }
2571         }
2572         if(b != NULL){
2573                 if(bit_32){
2574                         *b = ubyte(( (*((uint*)pixel) & Gr_current_blue->mask)>>Gr_current_blue->shift)*Gr_current_blue->scale);
2575                 } else {
2576                         *b = ubyte(( ( ((ushort*)pixel)[0] & Gr_current_blue->mask)>>Gr_current_blue->shift)*Gr_current_blue->scale);
2577                 }
2578         }
2579
2580         // get the alpha value
2581         if(a != NULL){          
2582                 *a = 1;
2583
2584                 switch(Bm_pixel_format){
2585                 // glide has an alpha channel so we have to unset ir or set it each time
2586                 case BM_PIXEL_FORMAT_ARGB:                      
2587                         Assert(!bit_32);
2588                         if(!( ((ushort*)pixel)[0] & 0x8000)){
2589                                 *a = 0;
2590                         } 
2591                         break;
2592
2593                 // this d3d format has no alpha channel, so only make it "transparent", never make it "non-transparent"
2594                 case BM_PIXEL_FORMAT_D3D:
2595                         Assert(!bit_32);
2596                         if( *((ushort*)pixel) == Gr_current_green->mask){ 
2597                                 *a = 0;
2598                         }
2599                         break;
2600
2601                 // nice 1555 texture format mode
2602                 case BM_PIXEL_FORMAT_ARGB_D3D:  
2603                         // if we're writing to a normal texture, use nice alpha bits
2604                         if(Gr_current_red == &Gr_t_red){                                
2605                                 Assert(!bit_32);
2606
2607                                 if(!(*((ushort*)pixel) & Gr_current_alpha->mask)){
2608                                         *a = 0;
2609                                 }
2610                         }
2611                         // otherwise do it as normal
2612                         else {
2613                                 if(bit_32){
2614                                         if(*((int*)pixel) == Gr_current_green->mask){ 
2615                                                 *a = 0;
2616                                         }
2617                                 } else {
2618                                         if(*((ushort*)pixel) == Gr_current_green->mask){ 
2619                                                 *a = 0;
2620                                         }
2621                                 }
2622                         }
2623                 }
2624         }
2625 }
2626
2627 // get filename
2628 void bm_get_filename(int bitmapnum, char *filename)
2629 {
2630         int n = bitmapnum % MAX_BITMAPS;
2631
2632         // return filename
2633         strcpy(filename, bm_bitmaps[n].filename);
2634 }
2635
2636 // given a bitmap and a section, return the size (w, h)
2637 void bm_get_section_size(int bitmapnum, int sx, int sy, int *w, int *h)
2638 {
2639         int bw, bh;
2640         bitmap_section_info *sections;
2641
2642         // bogus input?
2643         Assert((w != NULL) && (h != NULL));
2644         if((w == NULL) || (h == NULL)){
2645                 return;
2646         }
2647
2648         // get bitmap info
2649         bm_get_info(bitmapnum, &bw, &bh, NULL, NULL, NULL, &sections);
2650
2651         // determine the width and height of this section
2652         *w = sx < (sections->num_x - 1) ? MAX_BMAP_SECTION_SIZE : bw - sections->sx[sx];
2653         *h = sy < (sections->num_y - 1) ? MAX_BMAP_SECTION_SIZE : bh - sections->sy[sy];                                                                                
2654 }
2655