]> icculus.org git repositories - taylor/freespace2.git/blob - src/palman/palman.cpp
added copyright header
[taylor/freespace2.git] / src / palman / palman.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/Palman/PalMan.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Palette manager routines
16  *
17  * $Log$
18  * Revision 1.3  2002/06/09 04:41:25  relnev
19  * added copyright header
20  *
21  * Revision 1.2  2002/05/07 03:16:48  theoddone33
22  * The Great Newline Fix
23  *
24  * Revision 1.1.1.1  2002/05/03 03:28:10  root
25  * Initial import.
26  *
27  * 
28  * 5     3/31/99 8:24p Dave
29  * Beefed up all kinds of stuff, incluging beam weapons, nebula effects
30  * and background nebulae. Added per-ship non-dimming pixel colors.
31  * 
32  * 4     2/05/99 12:52p Dave
33  * Fixed Glide nondarkening textures.
34  * 
35  * 3     2/03/99 6:06p Dave
36  * Groundwork for FS2 PXO usertracker support.  Gametracker support next.
37  * 
38  * 2     10/07/98 10:53a Dave
39  * Initial checkin.
40  * 
41  * 1     10/07/98 10:50a Dave
42  * 
43  * 55    5/20/98 9:46p John
44  * added code so the places in code that change half the palette don't
45  * have to clear the screen.
46  * 
47  * 54    5/16/98 4:37p John
48  * 
49  * 53    5/16/98 4:34p John
50  * fixed bug where only colors divisible by 4 would work.
51  * 
52  * 52    5/15/98 3:28p John
53  * fixed bug with blue nondarkening colors
54  * 
55  * 51    5/14/98 3:38p John
56  * Added in more non-darkening colors for Adam.  Had to fix some bugs in
57  * BmpMan and Ani stuff to get this to work.
58  * 
59  * 50    5/13/98 10:22p John
60  * Added cfile functions to read/write rle compressed blocks of data.
61  * Made palman use it for .clr files.  Made alphacolors calculate on the
62  * fly rather than caching to/from disk.
63  * 
64  * 49    4/30/98 4:53p John
65  * Restructured and cleaned up cfile code.  Added capability to read off
66  * of CD-ROM drive and out of multiple pack files.
67  * 
68  * 48    4/20/98 4:44p John
69  * Fixed problems with black being xparent on model cache rneders.  Made
70  * model cache key off of detail level setting and framerate.
71  * 
72  * 47    4/15/98 5:44p John
73  * Made no colors except green map to 0,255,0
74  * 
75  * 46    4/09/98 11:04p John
76  * Changed ID's in output files to make more sense.
77  * 
78  * 45    4/01/98 5:35p John
79  * Made only the used POFs page in for a level.   Reduced some interp
80  * arrays.    Made custom detail level work differently.
81  * 
82  * 44    3/25/98 8:08p John
83  * Restructured software rendering into two modules; One for windowed
84  * debug mode and one for DirectX fullscreen.   
85  * 
86  * 43    3/24/98 3:58p John
87  * Put in (hopefully) final gamma setting code.
88  * 
89  * 42    2/24/98 1:59p John
90  * Made fade table use a gamma
91  * 
92  * 41    1/29/98 8:18a John
93  * Put in some commented out hooks for RGB lighting
94  * 
95  * 40    1/19/98 6:15p John
96  * Fixed all my Optimized Build compiler warnings
97  * 
98  * 39    1/10/98 1:14p John
99  * Added explanation to debug console commands
100  * 
101  * 38    12/21/97 4:33p John
102  * Made debug console functions a class that registers itself
103  * automatically, so you don't need to add the function to
104  * debugfunctions.cpp.  
105  * 
106  * 37    12/17/97 5:11p John
107  * Added brightening back into fade table.  Added code for doing the fast
108  * dynamic gun flashes and thruster flashes.
109  * 
110  * 36    12/17/97 1:16p John
111  * Made bright white not fade.
112  * 
113  * 35    12/03/97 4:48p Adam
114  * JOHN: Made engine glow scale, made thrust blend be additive.
115  * 
116  * 34    12/02/97 4:00p John
117  * Added first rev of thruster glow, along with variable levels of
118  * translucency, which retquired some restructing of palman.
119  * 
120  * 33    11/22/97 1:05p John
121  * added back in reverse palette lookup table.
122  * 
123  * 32    11/21/97 1:32p John
124  * made palette caching work on game palette better.
125  * 
126  * 31    11/21/97 11:32a John
127  * Added nebulas.   Fixed some warpout bugs.
128  * 
129  * 30    11/14/97 12:31p John
130  * Fixed some DirectX bugs.  Moved the 8-16 xlat tables into Graphics
131  * libs.  Made 16-bpp DirectX modes know what bitmap format they're in.
132  * 
133  * 29    10/31/97 10:48a John
134  * upped clr version to force rebuild after changing palette code.
135  * 
136  * 28    10/14/97 8:08a John
137  * added a bunch more 16 bit support
138  * 
139  * 27    10/03/97 9:10a John
140  * added better antialiased line drawer
141  * 
142  * 26    9/20/97 8:16a John
143  * Made .clr files go into the Cache directory. Replaced cfopen(name,NULL)
144  * to delete a file with cf_delete.
145  * 
146  * 25    9/09/97 3:39p Sandeep
147  * warning level 4 bugs
148  * 
149  * 24    7/28/97 5:08p John
150  * changed the color blending calculations.
151  * 
152  * 23    7/17/97 11:37a John
153  * made the fullscreen and windowed use separate palette cache files.
154  * 
155  * 22    7/16/97 5:29p John
156  * added palette table caching and made scaler and liner no light tmapper
157  * do alpha blending in 8 bpp mode.
158  * 
159  * 21    7/16/97 3:07p John
160  * 
161  * 20    7/10/97 2:06p John
162  * added code to specify alphablending type for bitmaps.
163  * 
164  * 19    6/11/97 6:00p John
165  * sped up alpha matching a bit.
166  * 
167  * 18    6/11/97 5:49p John
168  * Changed palette code to only recalculate alphacolors when needed, not
169  * when palette changes.
170  * 
171  * 17    6/11/97 1:13p John
172  * Started fixing all the text colors in the game.
173  * 
174  * 16    5/21/97 11:06a Lawrance
175  * added user_palette_find()
176  * 
177  * 15    5/14/97 10:53a John
178  * fixed some discrepencies between d3d and software palette setting.
179  * 
180  * 14    5/12/97 12:27p John
181  * Restructured Graphics Library to add support for multiple renderers.
182  * 
183  * 13    4/10/97 4:47p John
184  * used .3R .5G .1B for color matching.  Made palette brightening not be
185  * quite so much.
186  * 
187  * 12    4/08/97 5:18p John
188  * First rev of decent (dynamic, correct) lighting in FreeSpace.
189  * 
190  * 11    11/26/96 6:50p John
191  * Added some more hicolor primitives.  Made windowed mode run as current
192  * bpp, if bpp is 8,16,or 32.
193  * 
194  * 10    11/26/96 2:53p Allender
195  * simplify restore palette code
196  * 
197  * 9     11/26/96 9:44a Allender
198  * allow for use of different bitmap palettes
199  *
200  * $NoKeywords: $
201  */
202
203 #include "pstypes.h"
204 #include "cfile.h"
205 #include "palman.h"
206 #include "bmpman.h"
207 #include "2d.h"
208 #include "pcxutils.h"
209 #include "parselo.h"
210 #include "grinternal.h"
211
212 #define SQUARE(x) ((x)*(x))
213
214 #define NUM_BLEND_TABLES 3
215 float blend_table_factors[NUM_BLEND_TABLES] = { 0.5f, 1.0f, 1.2f };
216
217 ubyte palette_org[256*3];
218 ubyte gr_palette[256*3];
219 ubyte gr_fade_table[(256*34)*2];
220 static ubyte palette_blend_table[NUM_BLEND_TABLES*256*256];
221
222 int palette_blend_table_calculated = 0;
223 int palette_fade_table_calculated = 0;
224
225 uint gr_palette_checksum = 0;
226
227 uint palman_screen_signature = 0;
228
229 #define LOOKUP_SIZE (64*64*64)
230 ubyte palette_lookup[64*64*64];
231
232 static char palette_name[128] = { "none" };
233
234 static int Palman_restrict_colors = 0;
235
236 //extern ubyte palette_org[256*3];
237
238 int Palman_num_nondarkening_default = 0;
239 ubyte Palman_non_darkening_default[MAX_NONDARK_COLORS][3];
240
241 int Palman_num_nondarkening = 0;
242 ubyte Palman_non_darkening[MAX_NONDARK_COLORS][3];
243
244 int palman_is_nondarkening(int r,int g, int b)
245 {
246         int i;  
247
248         for (i=0; i<Palman_num_nondarkening; i++ )      {
249                 if ( (r==Palman_non_darkening[i][0]) && (g==Palman_non_darkening[i][1]) && (b==Palman_non_darkening[i][2]) )    {
250                         return 1;
251                 }
252         }
253         return 0;
254 }
255
256 void palman_load_pixels()
257 {
258         // open pixels.tbl
259         read_file_text("pixels.tbl");
260         reset_parse();
261
262         // parse pixels 
263         while(!optional_string("#END")){
264                 // nondarkening pixel
265                 if(required_string("+ND")){
266                         stuff_byte(&Palman_non_darkening_default[Palman_num_nondarkening_default][0]);
267                         stuff_byte(&Palman_non_darkening_default[Palman_num_nondarkening_default][1]);
268                         stuff_byte(&Palman_non_darkening_default[Palman_num_nondarkening_default++][2]);
269                 }
270         }
271
272         // set this to be the active table
273         palman_set_nondarkening(Palman_non_darkening_default, Palman_num_nondarkening_default);
274 }
275
276 void palman_set_nondarkening(ubyte colors[MAX_NONDARK_COLORS][3], int size)
277 {
278         // if we're supposed to use the passed table
279         memcpy(Palman_non_darkening, colors, MAX_NONDARK_COLORS * 3);
280         Palman_num_nondarkening = size;
281 }
282
283 void palette_cache_clear()
284 {
285         int i;
286
287         for (i=0; i<LOOKUP_SIZE; i++ )  {
288                 palette_lookup[i] = 255;
289         }
290 }
291
292 int palette_cache_find( int r, int g, int b )
293 {
294         if ( !palman_is_nondarkening(r,g,b))    {
295                 int value = ((r/4)<<12)+((g/4)<<6)+(b/4);
296                 if ( palette_lookup[value] != 255 )     {
297                         return palette_lookup[value];
298                 }
299         }
300         return -1;
301 }
302
303 void palette_cache_add( int r, int g, int b, int index )
304 {
305         int value = ((r/4)<<12)+((g/4)<<6)+(b/4);
306
307         if ( !palman_is_nondarkening(r,g,b))    {
308                 palette_lookup[value] = (ubyte)index;
309         }
310 }
311
312 char palette_base_filename[128] = { "default" };
313 int palette_base_loaded = 0;
314
315 void palette_load_table( char * filename )
316 {
317         int i;
318         int w, h;
319         int pcx_error;
320
321         strcpy( palette_base_filename, filename );
322         char * p = strchr(palette_base_filename,'.');
323         if ( p )        {
324                 *p = 0;
325         }
326
327         pcx_error = pcx_read_header(palette_base_filename, &w, &h, palette_org );
328         if ( pcx_error != PCX_ERROR_NONE )      {
329                 // Read the old .256 file
330                 CFILE *fp;
331                 int fsize;
332                 fp = cfopen( palette_base_filename, "rb" );
333                 if ( fp==NULL)
334                         Error( LOCATION, "Can't open palette file <%s>",palette_base_filename);
335
336                 fsize   = cfilelength( fp );
337                 Assert( fsize == 9472 );
338                 cfread( palette_org, 256*3, 1, fp );
339                 cfclose(fp);
340
341                 for (i=0; i<768; i++ )  {       
342                         palette_org[i] = ubyte((palette_org[i]*255)/63);
343                 }
344         }
345
346         palette_base_loaded = 1;
347
348         gr_set_palette(palette_base_filename, palette_org);
349 }
350
351
352 DCF(palette,"Loads a new palette")
353 {
354         if ( Dc_command )       {
355                 dc_get_arg(ARG_STRING|ARG_NONE);
356                 if ( Dc_arg_type == ARG_NONE )  {
357                 } else {
358                         palette_load_table( Dc_arg );
359                 }
360         }
361         if ( Dc_help )  {
362                 dc_printf( "Usage: palette filename\nLoads the palette file.\n" );
363         }
364
365 }
366
367 int Palman_allow_any_color = 0;
368
369
370 uint palette_find( int r, int g, int b )
371 {
372         int i, j;
373         int best_value, best_index, value;
374
375         int     is_transparent = 0;
376         if ( (r == 0) && (g==255) && (b==0) )   {
377                 is_transparent = 1;
378         }
379
380         int restrict = 0;
381         if ( Palman_restrict_colors && (!Palman_allow_any_color) )      {
382                 restrict = 1;
383         }
384                         
385 //      int     rgb = ((r/4)<<12)+((g/4)<<6)+(b/4);
386
387         i = palette_cache_find(r,g,b);
388         if ( i != -1 )  {
389                 if ( restrict ) {
390                         if ( i > 127 )  {
391                                 return i;
392                         }
393                 } else {
394                         return i;
395                 }
396         }
397
398         best_value = 1000000000;
399         best_index = -1;
400
401         int bottom_color = 0;
402         if ( restrict ) {
403                 bottom_color = 128;
404         }
405
406         j=3*bottom_color; 
407
408         for (i=bottom_color; i<255; i++ )       {
409                 int pr, pg, pb;
410
411                 pr = gr_palette[j];
412                 pg = gr_palette[j+1];
413                 pb = gr_palette[j+2];
414
415                 value = SQUARE(r-pr) + SQUARE(g-pg) + SQUARE(b-pb);
416
417                 if ( (best_index==-1) || (value < best_value) ) {
418                         // Don't map anything to 0,255,0 (transparent) ever, except 0,255,0
419                         if (value==0) {
420                                 palette_cache_add( r, g, b, i );
421                                 return i;
422                         }
423                         // Not an exact match, so don't let anything map to a nondarkening color.
424                         if ( (!is_transparent) && (!palman_is_nondarkening( pr, pg, pb ))  )    {
425                                 best_value = value;
426                                 best_index = i;
427                         }
428                 }
429                 j += 3;
430         }
431
432         if ( best_index == -1 ) {
433                 best_index = bottom_color;
434         }
435
436         palette_cache_add( r, g, b, best_index );
437         return best_index;
438 }
439
440 // version 0 - initial revision
441 // version 2 - changed 16-bpp fade table to include the 1.5 brightening factor
442 // version 3 - changed to put black in color 0 all the time
443 // version 4 - took out all truecolor lookup tables
444 // version 5 - changed palette to use 254 entries for nebula, made color mapping different
445 // version 6 - took out 1.5 brightness
446 // version 7 - added blending tables
447 // version 8 - made glows use additive blending
448 // version 9 - made 255,255,255 not fade
449 // version 10 - made fade table go to white again for anything l above 0.75.
450 // version 11 - made fade table go from 0-1 instead of 0-0.75
451 // version 12 - added variable gamma
452 // version 13 - Reduced blending tables from 5 to 3. Save 128KB RAM.
453 // version 14 - made palette never map anything to green.
454 // version 15 - made green blending with anything be black
455 // version 16 - added compression
456 // version 17 - added more nondarkening colors
457 // version 18 - fixed bug with blue nondarkening colors
458 // version 19 - fixed bug where only colors divisible by 4 got used.
459 // version 20 - added flag to only use lower 128 colors for palette.
460 #define PAL_ID 'LAPV'                   // VPAL (Volition Palette)
461 #define PAL_VERSION  20
462 #define PAL_LAST_COMPATIBLE_VERSION 20
463
464 void palette_write_cached1( char *name )
465 {
466         CFILE *fp;
467         char new_name[128];
468
469         strcpy( new_name, name );
470         strcat( new_name, ".clr" );
471         
472 //      mprintf(( "Writing palette cache file '%s'\n", new_name ));
473
474         fp = cfopen( new_name, "wb", CFILE_NORMAL, CF_TYPE_CACHE );
475         if ( !fp ) return;
476         
477         cfwrite_uint( PAL_ID, fp );
478         cfwrite_int(PAL_VERSION, fp );
479         cfwrite( &gr_palette_checksum, 4, 1, fp );
480
481         cfwrite_compressed( &gr_palette, 256*3, 1, fp );                                                // < 1 KB
482
483         cfwrite_compressed( &palette_lookup, LOOKUP_SIZE, 1, fp );                      // 256KB
484         
485         if ( palette_fade_table_calculated )    {
486                 cfwrite_int(1,fp);
487                 cfwrite_int(Gr_gamma_int,fp);
488                 cfwrite_compressed( &gr_fade_table,   256*34*2, 1, fp );                // 17KB
489         } else {
490                 cfwrite_int(0,fp);
491         }
492         
493         if ( palette_blend_table_calculated )   {
494                 cfwrite_int(NUM_BLEND_TABLES,fp);
495                 cfwrite_compressed( &palette_blend_table,  256*256, NUM_BLEND_TABLES, fp );     //64KB*
496         } else {
497                 cfwrite_int(0,fp);
498         }
499
500         cfclose(fp);
501 //      mprintf(( "Done.\n" ));
502 }
503
504 // Returns TRUE if successful, else 0
505
506 int palette_read_cached( char *name )
507 {
508         CFILE *fp;
509         char new_name[128];
510         int version;
511         uint id, new_checksum;
512         ubyte new_palette[768];
513
514         strcpy( new_name, name );
515         strcat( new_name, ".clr" );
516
517 //      mprintf(( "Reading palette '%s'\n", name ));
518         
519         fp = cfopen( new_name, "rb", CFILE_NORMAL, CF_TYPE_CACHE );
520
521         // Couldn't find file
522         if ( !fp ) {
523                 mprintf(( "No cached palette file\n" ));
524                 return 0;
525         }
526
527         id  = cfread_uint( fp );
528         if ( id != PAL_ID )     {
529                 mprintf(( "Cached palette file has incorrect ID\n" ));
530                 cfclose(fp);
531                 return 0;
532         }
533         version = cfread_int( fp );
534         if ( version < PAL_LAST_COMPATIBLE_VERSION ) {
535                 mprintf(( "Cached palette file is an older incompatible version\n" ));
536                 cfclose(fp);
537                 return 0;
538         }
539         
540         cfread( &new_checksum, 4, 1, fp );
541         if ( gr_palette_checksum != new_checksum )      {
542                 mprintf(( "Cached palette file is out of date (Checksum)\n" ));
543                 cfclose(fp);
544                 return 0;
545         }
546
547         cfread_compressed( &new_palette, 256*3, 1, fp );
548         if ( memcmp( new_palette, gr_palette, 768 ) )   {
549                 mprintf(( "Cached palette file is out of date (Contents)\n" ));
550                 cfclose(fp);
551                 return 0;
552         }
553
554         cfread_compressed( &palette_lookup, LOOKUP_SIZE, 1, fp );                       // 256KB
555
556         int fade_table_saved = cfread_int(fp);
557         
558         if ( fade_table_saved ) {
559                 int new_gamma;
560                 cfread( &new_gamma, 4, 1, fp );
561                 cfread_compressed( &gr_fade_table,   256*34*2, 1, fp );         // 17KB
562                 if ( new_gamma == Gr_gamma_int )        {
563                         palette_fade_table_calculated = 1;
564                 } else {
565                         palette_fade_table_calculated = 0;
566                 }
567         } else {
568                 palette_fade_table_calculated = 0;
569         }
570         
571         int num_blend_tables_saved = cfread_int(fp);
572         if ( (num_blend_tables_saved == NUM_BLEND_TABLES) && (num_blend_tables_saved>0))        {
573                 palette_blend_table_calculated = 1;
574                 cfread_compressed( &palette_blend_table,  256*256, NUM_BLEND_TABLES, fp );      //64KB*
575         } else {
576                 palette_blend_table_calculated = 0;
577         }
578
579         cfclose(fp);
580
581 //      mprintf(( "Done.\n" ));
582
583         return 1;
584 }
585
586 void palman_create_blend_table(float factor, ubyte *table)
587 {
588         int i;
589
590         // Make the blending table
591         for (i=0; i<256; i++ )  {
592                 int j, r, g, b;
593                 float si, fr, fg, fb, br, bg, bb;
594                 float Sf, Df;
595
596                 fr = i2fl(gr_palette[i*3+0]);
597                 fg = i2fl(gr_palette[i*3+1]);
598                 fb = i2fl(gr_palette[i*3+2]);
599
600                 // Make everything blended with Xparent be black
601                 if ( i==255 )   {
602                         fr = fg = fb = 0.0f;
603                 }
604
605                 si = (( fr+fg+fb ) / (256.0f*3.0f)) * factor;
606
607                 if ( factor > 1.0f )    {
608                         if ( si > 1.0f )        {
609                                 Sf = 1.0f;
610                                 Df = 0.0f;
611                         } else  {
612                                 Sf = 1.0f;
613                                 Df = 1.0f - si;
614                         }
615                 } else {
616                         if ( si > 1.0f )        {
617                                 Sf = 1.0f;
618                                 Df = 0.0f;
619                         } else  {
620                                 Sf = si;
621                                 Df = 1.0f;
622                         }
623                         Sf = factor;
624                         Df = 1.0f;
625                 }
626  
627 //              Sf = Df =1.0f;
628
629                 for (j=0; j<256; j++ )  {
630                         br = i2fl(gr_palette[j*3+0]);
631                         bg = i2fl(gr_palette[j*3+1]);
632                         bb = i2fl(gr_palette[j*3+2]);
633
634                         // Make all things on top of Xparent be black
635                         if ( j==255 )   {
636                                 br = bg = bb = 0.0f;
637                         }
638
639                         r = fl2i( fr*Sf + br*Df );
640                         g = fl2i( fg*Sf + bg*Df );
641                         b = fl2i( fb*Sf + bb*Df );
642
643                         int max = r;
644                         if ( g > max ) max = g;
645                         if ( b > max ) max = b;
646                         if ( max > 255 )        {
647                                 r = (255*r)/max;
648                                 g = (255*g)/max;
649                                 b = (255*b)/max;
650                         }
651                         if ( r > 255 ) r = 255; else if ( r < 0 ) r = 0;
652                         if ( g > 255 ) g = 255; else if ( g < 0 ) g = 0;
653                         if ( b > 255 ) b = 255; else if ( b < 0 ) b = 0;
654
655                         if ( i == 255 )
656                                 table[i*256+j] = (unsigned char)j;
657                         else {
658                                 // If background transparent, and color isn't bright, call it transparent.
659                                 if ( j == 255 && ((r+g+b) < 110))       {
660                                         table[i*256+j] = 255;
661                                 } else {
662                                         table[i*256+j] = (unsigned char)palette_find(r,g,b);
663                                 }
664                         }
665                 }
666         }
667 }
668
669 void palette_flush()
670 {
671         // DB 2/3/99 - I think this was causing some wacky unhandled exceptions at game shutdown. Since we don't use palettes anymore.....
672         /*
673         if ( stricmp( palette_name, "none" ) )  {
674                 palette_write_cached1( palette_name );
675         }
676         */
677 }
678
679
680 // When gr_set_palette is called, it fills in gr_palette and then calls this
681 // function, which should update all the tables.
682 // Pass NULL to flush current palette.
683 void palette_update(char *name_with_extension, int restrict_font_to_128)
684 {
685 //      int i;
686         uint tmp_checksum;
687         char name[128];
688
689         Palman_restrict_colors = restrict_font_to_128;
690         
691 //      mprintf(( "<<<<<<<<< PALETTE UPDATE (%s) >>>>>>>>>>>\n", (name_with_extension?name_with_extension:"null") ));
692
693         strcpy( name, name_with_extension );
694         char *p = strchr( name, '.' );
695         if ( p ) *p = 0;
696
697         strcpy( palette_name, name );
698
699         tmp_checksum = palette_compute_checksum( gr_palette );
700         if ( tmp_checksum == gr_palette_checksum ) return;
701
702         gr_palette_checksum = tmp_checksum;
703
704         // Clear the lookup cache, since the palette has changed
705         palette_cache_clear();
706         palette_blend_table_calculated = 0;
707         palette_fade_table_calculated = 0;
708
709         // For "none" palettes, don't calculate tables
710         if ( !stricmp( name, "none" ) ) {
711                 bm_update();                    // update the bitmap palette's
712                 return;
713         }
714
715         // Read in the cached info if there is any.
716         if ( palette_read_cached( name ) )      {
717                 bm_update();                    // update the bitmap palette's
718                 return;
719         }
720         
721         bm_update();                    // update the bitmap palette's
722 }
723
724 ubyte *palette_get_fade_table()
725 {
726         int i,l;
727
728         if ( palman_screen_signature != gr_screen.signature )   {
729                 palman_screen_signature = gr_screen.signature;
730                 palette_fade_table_calculated = 0;
731         }
732
733
734         if ( !palette_fade_table_calculated )   {
735                 //mprintf(( "Creating fading table..." ));      
736
737                 for (i=0; i<256; i++ )  {
738                         int r, g, b;
739                         int ur, ug, ub;
740                         r = gr_palette[i*3+0];
741                         g = gr_palette[i*3+1];
742                         b = gr_palette[i*3+2];
743
744                         if ( palman_is_nondarkening(r,g,b))             {
745                                 // Make pure white not fade
746                                 for (l=0; l<32; l++ )   {
747                                         gr_fade_table[((l+1)*256)+i] = (unsigned char)i;
748                                 }
749                         } else {
750                                 for (l=0; l<32; l++ )   {
751
752                                         if ( l < 24 )   {
753                                                 float f = (float)pow(i2fl(l)/23.0f, 1.0f/Gr_gamma);
754                                                 ur = fl2i(i2fl(r)*f); if ( ur > 255 ) ur = 255;
755                                                 ug = fl2i(i2fl(g)*f); if ( ug > 255 ) ug = 255;
756                                                 ub = fl2i(i2fl(b)*f); if ( ub > 255 ) ub = 255;
757                                         } else {
758                                                 int x,y;
759                                                 int gi, gr, gg, gb;
760                         
761                                                 gi = (r+g+b)/3;
762
763                                                 #ifdef RGB_LIGHTING
764                                                         gr = r;
765                                                         gg = g;
766                                                         gb = gi*2;
767                                                 #else
768                                                         gr = r*2;
769                                                         gg = g*2;
770                                                         gb = b*2;
771                                                 #endif
772                                 
773                                                 x = l-24;                       // x goes from 0 to 7
774                                                 y = 31-l;                       // y goes from 7 to 0
775
776                                                 ur = ((gr*x)+(r*y))/7; if ( ur > 255 ) ur = 255;
777                                                 ug = ((gg*x)+(g*y))/7; if ( ug > 255 ) ug = 255;
778                                                 ub = ((gb*x)+(b*y))/7; if ( ub > 255 ) ub = 255;
779                                         }
780                                         gr_fade_table[((l+1)*256)+i] = (unsigned char)palette_find( ur, ug, ub );
781
782                                 }
783                         }
784                         gr_fade_table[ (0*256)+i ] = gr_fade_table[ (1*256)+i ];
785                         gr_fade_table[ (33*256)+i ] = gr_fade_table[ (32*256)+i ];
786                 }
787
788                 // Mirror the fade table
789                 for (i=0; i<34; i++ )   {
790                         for ( l = 0; l < 256; l++ )     {
791                                 gr_fade_table[ ((67-i)*256)+l ] = gr_fade_table[ (i*256)+l ];
792                         }
793                 }
794
795 //              mprintf(( "done\n" ));  
796                 palette_fade_table_calculated = 1;
797         }
798
799         return &gr_fade_table[0];
800 }
801
802
803 ubyte *palette_get_blend_table(float alpha)
804 {
805         int i;
806
807         if ( !palette_blend_table_calculated )  {
808 //              mprintf(( "Creating blending table..." ));      
809                 for (i=0; i<NUM_BLEND_TABLES; i++ )     {
810                         palman_create_blend_table(blend_table_factors[i], &palette_blend_table[i*256*256] );
811                 }
812 //              mprintf(( "done\n" ));  
813                 palette_blend_table_calculated = 1;
814         }
815         
816         for (i=0; i<NUM_BLEND_TABLES; i++ )     {
817                 if ( alpha <= blend_table_factors[i] )  
818                         break;
819         } 
820         if ( i<0 ) i = 0;
821         if ( i>NUM_BLEND_TABLES-1 ) i = NUM_BLEND_TABLES-1;
822
823         return &palette_blend_table[i*256*256];
824 }
825
826
827
828 // compute a simple checksum on the given palette.  Used by the bitmap manager
829 // to determine if we need to reload a new palette for a bitmap.  Code liberally
830 // stolen from descent networking checksum code
831 uint palette_compute_checksum( ubyte *pal )
832 {
833         int i;
834         uint sum1, sum2;
835
836         sum1 = sum2 = 0;
837
838         for (i = 0; i < 768; i++) {
839                 sum1 += (uint)pal[i];
840                 if ( sum1 >= 255 ) sum1 -= 255;
841                 sum2 += sum1;
842         }
843         sum2 %= 255;
844
845         return ((sum1<<8)+sum2);
846 }
847
848 // this function takes a bitmap number and sets the game palette to the palette of this
849 // bitmap.
850 void palette_use_bm_palette(int n)
851 {
852         ubyte tmp[768];
853         char name[128];
854
855         bm_get_palette(n, tmp, name);                           // get the palette for this bitmap
856
857         gr_set_palette(name, tmp);                              // load the new palette.
858 }
859
860 void palette_restore_palette()
861 {
862         ubyte tmp[768];
863         memcpy(tmp, palette_org, 3*256);
864
865         if ( palette_base_loaded )              {
866                 gr_set_palette(palette_base_filename, tmp);
867         }
868 }
869