]> icculus.org git repositories - taylor/freespace2.git/blob - src/anim/animplay.cpp
various big-endian fixes, mainly networking support related
[taylor/freespace2.git] / src / anim / animplay.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/Anim/AnimPlay.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * C module for playing back anim files
16  *
17  * $Log$
18  * Revision 1.7  2006/04/26 19:48:58  taylor
19  * various big-endian fixes, mainly networking support related
20  *
21  * Revision 1.6  2005/08/12 08:55:13  taylor
22  * sync up talking head fixes from FS2_Open code base (still not 100%)
23  *
24  * Revision 1.5  2004/09/20 01:31:44  theoddone33
25  * GCC 3.4 fixes.
26  *
27  * Revision 1.4  2004/06/11 00:27:06  tigital
28  * byte-swapping changes for bigendian systems
29  *
30  * Revision 1.3  2002/06/09 04:41:15  relnev
31  * added copyright header
32  *
33  * Revision 1.2  2002/05/07 03:16:43  theoddone33
34  * The Great Newline Fix
35  *
36  * Revision 1.1.1.1  2002/05/03 03:28:08  root
37  * Initial import.
38  *
39  * 
40  * 9     9/13/99 11:26p Andsager
41  * Add debug code to check for poorly sized anis
42  * 
43  * 8     8/26/99 9:45a Dave
44  * First pass at easter eggs and cheats.
45  * 
46  * 7     7/16/99 1:49p Dave
47  * 8 bit aabitmaps. yay.
48  * 
49  * 6     7/13/99 1:15p Dave
50  * 32 bit support. Whee!
51  * 
52  * 5     6/10/99 10:34a Dave
53  * Removed unnecessary assert.
54  * 
55  * 4     11/30/98 1:07p Dave
56  * 16 bit conversion, first run.
57  * 
58  * 3     10/22/98 6:14p Dave
59  * Optimized some #includes in Anim folder. Put in the beginnings of
60  * parse/localization support for externalized strings and tstrings.tbl
61  * 
62  * 2     10/07/98 10:52a Dave
63  * Initial checkin.
64  * 
65  * 1     10/07/98 10:48a Dave
66  * 
67  * 38    6/23/98 4:18p Hoffoss
68  * Fixed some bugs with AC release build.
69  * 
70  * 37    5/18/98 5:59p Hoffoss
71  * Made command briefing advanced now once the speech stops and animation
72  * has fully played once, whichever is longer.
73  * 
74  * 36    5/14/98 6:29p Hoffoss
75  * Fixed some warnings a release rebuild all turned up.
76  * 
77  * 35    5/07/98 3:11a Lawrance
78  * Implement custom streaming code
79  * 
80  * 34    4/27/98 3:36p Dave
81  * 
82  * 33    3/25/98 8:43p Hoffoss
83  * Changed anim_play() to not be so damn complex when you try and call it.
84  * 
85  * 32    2/05/98 9:21p John
86  * Some new Direct3D code.   Added code to monitor a ton of stuff in the
87  * game.
88  * 
89  * 31    1/19/98 11:37p Lawrance
90  * Fixing Optimization build warnings
91  * 
92  * 30    1/19/98 3:09p Hoffoss
93  * Only free an anim instance if it is actually playing.
94  * 
95  * 29    1/14/98 6:43p Lawrance
96  * Add ref_count to anim struct, so we don't free multiple times
97  * 
98  * 28    12/30/97 6:44p John
99  * Made g3_Draw_bitmap functions account for aspect of bitmap.
100  * 
101  * 27    12/27/97 2:35p John
102  * Restructed some code so that if the memory-mapped file open fails, it
103  * will still read it the old-fashioned, non-memory mapped way.
104  * 
105  * 26    12/24/97 9:10p Lawrance
106  * take out some debugging statements
107  * 
108  * 25    12/24/97 8:57p Lawrance
109  * Added anim_ignore_next_frametime()
110  * 
111  * 24    12/07/97 2:06p Dave
112  * Removed some debug frame-checking code.
113  * 
114  * 23    12/06/97 2:55p Dave
115  * 
116  * 22    11/29/97 2:05p John
117  * made g3_draw_bitmap and g3_draw_rotated bitmap take w&h, not w/2 & h/2,
118  * like they used to incorrectly assume.   Added code to model to read in
119  * thruster radius's.
120  * 
121  * 21    11/20/97 5:36p Dave
122  * Hooked in a bunch of main hall changes (including sound). Made it
123  * possible to reposition (rewind/ffwd) 
124  * sound buffer pointers. Fixed animation direction change framerate
125  * problem.
126  * 
127  * 20    11/20/97 4:33p Sandeep
128  * ALAN: ensure instance->paused gets initialized
129  * 
130  * 19    11/20/97 4:12p Lawrance
131  * when paused, don't increment time_elapsed
132  * 
133  * 18    11/19/97 8:28p Dave
134  * Hooked in Main Hall screen. Put in Anim support for ping ponging
135  * animations as well as general reversal of anim direction.
136  * 
137  * 17    9/11/97 4:17p Allender
138  * use _MAX_PATH instead of MAX_FILENAME_LENGTH for anim_play since it is
139  * called from MoviePlayer with full path
140  * 
141  * 16    9/11/97 10:49a Lawrance
142  * improve anim_show_next_frame()
143  * 
144  * 15    9/10/97 4:59p Lawrance
145  * improve comments to anim_play() function
146  * 
147  * 14    9/03/97 4:19p John
148  * changed bmpman to only accept ani and pcx's.  made passing .pcx or .ani
149  * to bm_load functions not needed.   Made bmpman keep track of palettes
150  * for bitmaps not mapped into game palettes.
151  * 
152  * 13    8/30/97 2:11p Lawrance
153  * allow animations to loop
154  * 
155  * 12    8/25/97 11:13p Lawrance
156  * support framerate independent playback with the option of now advancing
157  * more than one frame at a time
158  * 
159  * 11    8/22/97 8:20a Lawrance
160  * display scrolling text properly, with indicator that text exitsts to be
161  * scrolled
162  * 
163  * 10    8/21/97 5:11p Lawrance
164  * frame numbering for ANI's now is from 0 -> total_frames-1.
165  * 
166  * 9     8/19/97 9:30a Lawrance
167  * print out reason if file doesn't open right
168  * 
169  * 8     7/28/97 10:42p Lawrance
170  * re-did interface to unpack_frame() to make more general
171  * 
172  * 7     7/21/97 11:41a Lawrance
173  * make playback time of .ani files keyed of frametime
174  * 
175  * 6     7/20/97 6:57p Lawrance
176  * supporting new RLE format
177  * 
178  * 5     7/11/97 11:54a John
179  * added rotated 3d bitmaps.
180  * 
181  * 4     6/27/97 4:36p Lawrance
182  * update pal translation table when gr_screen.signature changes
183  * 
184  * 3     6/26/97 3:00p Lawrance
185  * fix bug with playing 3d anims
186  * 
187  * 2     6/26/97 12:12a Lawrance
188  * supporting anti-aliased bitmap animations
189  * 
190  * 1     6/23/97 5:09p Lawrance
191  * 
192  * 24    6/03/97 5:53p Lawrance
193  * don't unload bitmap after bm_create
194  * 
195  * $NoKeywords: $
196  */
197
198 #include "animplay.h"
199 #include "linklist.h"
200 #include "timer.h"
201 #include "bmpman.h"
202 #include "2d.h"
203 #include "3d.h"
204 #include "grinternal.h"
205 #include "pcxutils.h"
206 #include "packunpack.h"
207 #include "cfile.h"
208
209 static color Color_xparent;
210
211 anim *first_anim = NULL;
212 anim_instance anim_free_list;
213 anim_instance anim_render_list;
214
215 #define MAX_ANIM_INSTANCES 25
216 anim_instance anim_render_instance[MAX_ANIM_INSTANCES];
217
218 int Anim_paused;        // global variable to pause the playing back of anims
219 int Anim_inited = FALSE;
220
221 fix t1,t2;
222
223 int Anim_ignore_frametime=0;    // flag used to ignore frametime... useful when need to avoid saturated frametimes
224
225 // -------------------------------------------------------------------------------------------------
226 // anim_init() will queue all the anim_render_instance[] elements onto the anim_free_list
227 //
228 void anim_init()
229 {
230         int i;
231
232         if ( Anim_inited == TRUE )
233                 return;
234
235         list_init( &anim_free_list );
236         list_init( &anim_render_list );
237
238         // Link all anim render slots into the free list
239         for (i=1; i < MAX_ANIM_INSTANCES; i++)  {
240                 list_append(&anim_free_list, &anim_render_instance[i]);
241         }
242         
243         Anim_paused = 0;
244         Anim_inited = TRUE;
245 }
246
247 // -------------------------------------------------------------------------------------------------
248 // anim_render_all() will display the frames for the currently playing anims
249 //
250 void anim_render_all(int screen_id, float frametime)
251 {
252         anim_instance* A;
253         anim_instance* temp;
254
255         A = GET_FIRST(&anim_render_list);
256         while( A !=END_OF_LIST(&anim_render_list) )     {
257                 temp = GET_NEXT(A);
258                 if ( A->screen_id == screen_id ) {
259                         if ( Anim_ignore_frametime ) {
260                                 frametime = 0.0f;
261                                 Anim_ignore_frametime=0;
262                         }
263                         if ( anim_show_next_frame(A, frametime) == -1 ) {
264                                 A->data = NULL;
265                                 anim_release_render_instance(A);        
266                         }
267                 }
268                 A = temp;
269         }
270 }
271
272 // -------------------------------------------------------------------------------------------------
273 // anim_render_one() will display the frames for the passed animation, it will ignore animations which
274 // do not have the same id as the passed screen_id
275 //
276 void anim_render_one(int screen_id, anim_instance *ani, float frametime)
277 {
278         // make sure this guy's screen id matches the passed one
279         if(screen_id != ani->screen_id){
280                 return;
281         }
282
283         // otherwise render it  
284         if ( Anim_ignore_frametime ) {
285                 frametime = 0.0f;
286                 Anim_ignore_frametime=0;
287         }
288         if ( anim_show_next_frame(ani, frametime) == -1 ) {
289                 ani->data = NULL;
290                 anim_release_render_instance(ani);      
291         }       
292 }
293
294 MONITOR(NumANIPlayed);
295
296 // Setup an anim_play_struct for passing into anim_play().  Will fill in default values, which you
297 // can then change before calling anim_play().
298 //
299 void anim_play_init(anim_play_struct *aps, anim *a_info, int x, int y)
300 {
301         aps->anim_info = a_info;
302         aps->x = x;
303         aps->y = y;
304         aps->start_at = 0;
305         aps->stop_at = a_info->total_frames - 1;
306         aps->screen_id = 0;
307         aps->world_pos = NULL;
308         aps->radius = 0.0f;
309         aps->framerate_independent = 0;
310         aps->color = NULL;
311         aps->skip_frames = 1;
312         aps->looped = 0;
313         aps->ping_pong = 0;
314 }
315
316 // -------------------------------------------------------------------------------------------------
317 // anim_play() will add an anim instance to the anim_render_list.  This will cause the
318 // anim to be played at the x,y position specified in the parameter list.
319 //
320 // input:
321 //
322 //              anim_info       =>      the compressed animation that we should make an instance from
323 //              x                               =>      x position of animation to play at (top left corner)
324 //              y                               =>      y position of animation to play at ( top left corner)
325 //              start_at                =>      frame number to start at (note: numbering is from 0->num_frames-1)
326 //              stop_at         =>      frame number to stop at (note: numbering is from 0->num_frames-1)
327 //              screen_id       =>      OPTIONAL (default value 0): screen signature so animation only plays when
328 //                                                      anim_render_all() called with that same signature
329 //              world_pos       =>      OPTIONAL (default value NULL): only give a world pos when you want to
330 //                                                      play the animation at a 3D location.  You must specify radius when
331 //                                                      this is non-null.
332 //              radius          =>      OPTIONAL (default value 0): only needed when the animation is playing
333 //                                                      as a 3D animation (this is only when world_pos in not NULL).
334 //              fi                              =>      OPTIONAL (default value 0): framerate indepentdent flag, when set TRUE
335 //                                                      the animation will skip frames if necessary to maintain the fps value
336 //                                                      associated with the animation
337 //              color                   =>      OPTIONAL (default value NULL) address of an alpha color struct.  Only
338 //                                                      required when the animation should be drawn with an alpha color.
339 //              skip_frames     => OPTIONAL (default value 1) should anim skip frames when doing framerate
340 //                   independent playback
341 //              looped          =>      OPTIONAL (default value 0) should anim play looped (ie forever)
342 //
343 // returns:
344 //
345 //              pointer to instance     => success
346 //              NULL                                            => if anim anim could not be played
347 //
348 anim_instance *anim_play(anim_play_struct *aps)
349 {
350         Assert( aps->anim_info != NULL );
351         Assert( aps->start_at >= 0 );
352         Assert( aps->stop_at < aps->anim_info->total_frames );
353         // Assert( aps->stop_at >= aps->start_at );
354         Assert( !(aps->looped && aps->ping_pong) );  // shouldn't have these both set at once
355
356         MONITOR_INC(NumANIPlayed, 1);
357         
358         // if (aps->ping_pong && !(aps->anim_info->flags & ANF_ALL_KEYFRAMES));
359
360         anim_instance *instance;
361
362         // Find next free anim instance slot on queue
363         instance = GET_FIRST(&anim_free_list);
364         Assert( instance != &anim_free_list );  // shouldn't have the dummy element
365
366         // remove instance from the free list
367         list_remove( &anim_free_list, instance );
368
369         // insert instance onto the end of anim_render_list
370         list_append( &anim_render_list, instance );
371
372         aps->anim_info->instance_count++;
373         instance->frame_num = -1;
374         instance->last_frame_num = -99;
375         instance->parent = aps->anim_info;
376         instance->data = aps->anim_info->data;
377         if ( anim_instance_is_streamed(instance) ) {
378                 instance->file_offset = instance->parent->file_offset;
379         }
380         instance->frame = (ubyte *) malloc(instance->parent->width * instance->parent->height * 2);
381         Assert( instance->frame != NULL );
382         instance->time_elapsed = 0.0f;
383         instance->stop_at = aps->stop_at;
384         instance->x = aps->x;
385         instance->y = aps->y;
386         instance->world_pos = aps->world_pos;
387         instance->radius = aps->radius;
388         instance->framerate_independent = aps->framerate_independent;
389         instance->last_bitmap = -1;
390         instance->stop_now = FALSE;
391         instance->screen_id = aps->screen_id;
392         instance->aa_color = aps->color;
393         instance->skip_frames = aps->skip_frames;
394         instance->looped = aps->looped;
395         instance->ping_pong = aps->ping_pong;
396         instance->direction = ANIM_DIRECT_FORWARD;
397         instance->paused = 0;
398         instance->loop_count = 0;
399         if ( aps->color == NULL ){
400                 instance->xlate_pal = 1;
401         } else {
402                 instance->xlate_pal = 0;
403         }
404
405         // determining the start_at frame is more complicated, since it must be a key-frame.
406         // Futhermore, need to subtract 1 from key-frame number, since frame number is always
407         // incremented the first time anim_show_next_frame() is called
408
409         instance->start_at = aps->start_at;
410
411         if ( aps->start_at > 0 ) {
412                 key_frame *keyp;
413                 int idx;
414                 int key = 0;
415                 int offset = 0;
416                 int frame_num = aps->start_at;
417
418                 keyp = instance->parent->keys;
419                 idx = 0;
420                 while (idx < instance->parent->num_keys) {
421                         if (key == frame_num)
422                                 break;
423
424                         key = keyp[idx].frame_num - 1;
425                         offset = keyp[idx].offset;
426
427                         idx++;
428                 }
429                 /*while (keyp) {
430                         if (( (keyp->frame_num-1) <= frame_num) && ( (keyp->frame_num-1) > key)) {  // find closest key
431                                 key = keyp->frame_num-1;
432                                 offset = keyp->offset;
433                                 if ( key == frame_num )
434                                         break;
435                         }
436
437                         keyp = keyp->next;
438                 }*/
439
440                 if (key > instance->frame_num) {  // best key is closer than current position
441                         instance->frame_num = key;
442                         if ( anim_instance_is_streamed(instance) ) {
443                                 instance->file_offset = instance->parent->file_offset + offset;
444                         } else {
445                                 instance->data = instance->parent->data + offset;
446                         }
447
448                 }
449
450                 instance->frame_num--;  // required
451         }
452
453         return instance;
454 }
455
456 // -----------------------------------------------------------------------------
457 //      anim_show_next_frame()
458 //
459 //      This function is called to blit the next frame of an anim instance to the 
460 // screen.  This is normally called by the anim_render_all() function.
461 //
462 //      input:  instance                =>              pointer to animation instance
463 //                              frametime       =>              time elapsed since last call, in seconds
464 //
465 int anim_show_next_frame(anim_instance *instance, float frametime)
466 {
467         int             bitmap_id, bitmap_flags=0, new_frame_num, frame_diff=0, i, n_frames=0,frame_save;
468         float           percent_through, decompress_time, render_time, time;
469         vertex  image_vertex;
470         int aabitmap = 0;
471         int bpp = 16;
472
473         Assert( instance != NULL );
474
475         instance->time_elapsed += frametime;
476
477         // Advance to the next frame, if we determine enough time has elapsed.
478         if(instance->direction == ANIM_DIRECT_FORWARD)
479                 n_frames = instance->stop_at - instance->start_at + 1;
480         else if(instance->direction == ANIM_DIRECT_REVERSE)
481                 n_frames = instance->start_at - instance->stop_at + 1;
482         time = n_frames / i2fl(instance->parent->fps);
483
484         percent_through = instance->time_elapsed / time;
485
486         if(instance->direction == ANIM_DIRECT_FORWARD)
487                 new_frame_num = instance->start_at - 1 + fl2i(percent_through * n_frames + 0.5f);
488         else
489                 new_frame_num = instance->start_at - 1 - fl2i(percent_through * n_frames + 0.5f);
490
491         frame_save = instance->frame_num;
492
493         // If framerate independent, use the new_frame_num... unless instance->skip_frames is
494         // FALSE, then only advance a maximum of one frame (this is needed since some big animations
495         // should just play slower rather than taking the hit of decompressing multiple frames and
496         // creating an even greater slowdown    
497         if (instance->framerate_independent) {
498                 if(instance->direction == ANIM_DIRECT_FORWARD){
499                         if ( new_frame_num > instance->last_frame_num) {
500                                 if ( instance->skip_frames )
501                                         instance->frame_num = new_frame_num;
502                                 else
503                                         instance->frame_num++;
504                         }
505                 } else if(instance->direction == ANIM_DIRECT_REVERSE){
506                         if( new_frame_num < instance->last_frame_num) {
507                                 if ( instance->skip_frames )
508                                         instance->frame_num = new_frame_num;
509                                 else
510                                         instance->frame_num--;
511                         }
512                 }
513         }
514         else {                  
515                 if(instance->direction == ANIM_DIRECT_FORWARD){
516                         if ( new_frame_num > instance->last_frame_num) {
517                                 instance->frame_num++;
518                         }
519                 } else if(instance->direction == ANIM_DIRECT_REVERSE){
520                         if ( new_frame_num < instance->last_frame_num) {
521                                 instance->frame_num--;
522                         }
523                 }                       
524         }
525
526         if(instance->direction == ANIM_DIRECT_FORWARD){
527                 if ( instance->frame_num < instance->start_at ) {
528                         instance->frame_num = instance->start_at;
529                 }       
530         } else if(instance->direction == ANIM_DIRECT_REVERSE){
531                 if ( instance->frame_num > instance->start_at ) {
532                         instance->frame_num = instance->start_at;
533                 }       
534         }
535
536         if ( instance->stop_now == TRUE ) {
537                 return -1;
538         }
539
540         // If past the last frame, clamp to the last frame and then set the stop_now flag in the
541         // anim instance.  The next iteration, the animation will stop.
542         if(instance->direction == ANIM_DIRECT_FORWARD){
543                 if (instance->frame_num >= instance->stop_at ) {
544                         if (instance->looped) {                                                                         // looped animations
545                                 instance->frame_num = instance->stop_at;
546                                 instance->time_elapsed = 0.0f;
547                         } else if(instance->ping_pong) {                                                        // pingponged animations
548                                 instance->frame_num = instance->stop_at;
549                                 // instance->time_elapsed = 0.0f;
550                                 anim_reverse_direction(instance);
551                         } else {                                                                                                                        // one-shot animations
552                                 instance->frame_num = instance->stop_at;
553                                 instance->last_frame_num = instance->frame_num;
554                                 instance->stop_now = TRUE;
555                         }
556                 }
557         } else if(instance->direction == ANIM_DIRECT_REVERSE){
558                 if (instance->frame_num <= instance->stop_at ) {
559                         if (instance->looped) {                                                                         // looped animations
560                                 instance->frame_num = instance->stop_at;
561                                 instance->time_elapsed = 0.0f;
562                         } else if(instance->ping_pong) {                                                        // pingponged animations
563                                 instance->frame_num = instance->stop_at;
564                                 // instance->time_elapsed = 0.0f;
565                                 anim_reverse_direction(instance);
566                         } else {                                                                                                                        // one-shot animations
567                                 instance->frame_num = instance->stop_at+1;
568                                 instance->last_frame_num = instance->frame_num;
569                                 instance->stop_now = TRUE;
570                         }
571                 }
572         }
573
574         if(instance->direction == ANIM_DIRECT_FORWARD){
575                 if( instance->last_frame_num >= instance->start_at ) {
576                         frame_diff = instance->frame_num - instance->last_frame_num;            
577                 } else {
578                         frame_diff = 1;
579                 }
580         } else if(instance->direction == ANIM_DIRECT_REVERSE){
581                 if( instance->last_frame_num <= instance->start_at ) {
582                         frame_diff = instance->last_frame_num - instance->frame_num;
583                 } else {
584                         frame_diff = 1;
585                 }
586         }               
587         Assert(frame_diff >= 0);
588         //      nprintf(("Alan","FRAME DIFF: %d\n",frame_diff));
589         Assert( instance->frame_num >= 0 && instance->frame_num < instance->parent->total_frames );
590
591         // if the anim is paused, ignore all the above changes and still display this frame
592         if(instance->paused || Anim_paused){
593                 instance->frame_num = frame_save;
594                 instance->time_elapsed -= frametime;
595                 frame_diff = 0;
596         }
597
598         if (instance->parent->flags & ANF_XPARENT){
599                 // bitmap_flags = BMP_XPARENT;
600                 bitmap_flags = 0;
601         } 
602         bpp = 16;
603         if(instance->aa_color != NULL){
604                 bitmap_flags |= BMP_AABITMAP;
605                 aabitmap = 1;
606                 bpp = 8;
607         }       
608
609         if ( frame_diff > 0 ) {
610                 instance->last_frame_num = instance->frame_num;         
611
612                 t1 = timer_get_fixed_seconds();
613                 for ( i = 0; i < frame_diff; i++ ) {
614                         anim_check_for_palette_change(instance);                        
615
616                         // if we're playing backwards, every frame must be a keyframe and we set the data ptr here
617                         if(instance->direction == ANIM_DIRECT_REVERSE){
618                                 if ( anim_instance_is_streamed(instance) ) {
619                                         instance->file_offset = instance->parent->file_offset + instance->parent->keys[instance->frame_num-1].offset;
620                                 } else {
621                                         instance->data = instance->parent->data + instance->parent->keys[instance->frame_num-1].offset;
622                                 }
623                         }
624
625                         ubyte *temp = NULL;
626                         int temp_file_offset = 0;                       
627
628                         // if we're using bitmap polys
629                         if(Gr_bitmap_poly){
630                                 BM_SELECT_TEX_FORMAT();
631                         }
632
633                         if ( anim_instance_is_streamed(instance) ) {
634                                 if ( instance->xlate_pal ){
635                                         temp_file_offset = unpack_frame_from_file(instance, instance->frame, instance->parent->width*instance->parent->height, instance->parent->palette_translation, aabitmap, bpp);
636                                 } else {
637                                         temp_file_offset = unpack_frame_from_file(instance, instance->frame, instance->parent->width*instance->parent->height, NULL, aabitmap, bpp);
638                                 }
639                         } else {
640                                 if ( instance->xlate_pal ){
641                                         temp = unpack_frame(instance, instance->data, instance->frame, instance->parent->width*instance->parent->height, instance->parent->palette_translation, aabitmap, bpp);
642                                 } else {
643                                         temp = unpack_frame(instance, instance->data, instance->frame, instance->parent->width*instance->parent->height, NULL, aabitmap, bpp);
644                                 }
645                         }
646
647                         // always go back to screen format
648                         BM_SELECT_SCREEN_FORMAT();
649
650                         if(instance->direction == ANIM_DIRECT_FORWARD){
651                                 if ( anim_instance_is_streamed(instance) ) {
652                                         instance->file_offset = temp_file_offset;
653                                 } else {
654                                         instance->data = temp;
655                                 }
656                         }                       
657                 }
658                 t2 = timer_get_fixed_seconds();
659         }
660         else {
661                 t2=t1=0;
662         }
663
664         // this only happens when the anim is being looped, we need to reset the last_frame_num
665         if ( (instance->time_elapsed == 0) && (instance->looped) ) {
666                 instance->last_frame_num = -1;
667                 instance->frame_num = -1;
668                 instance->data = instance->parent->data;
669                 instance->file_offset = instance->parent->file_offset;
670                 instance->loop_count++;
671         }
672                 
673         decompress_time = f2fl(t2-t1);
674
675         t1 = timer_get_fixed_seconds();
676         if ( frame_diff == 0 && instance->last_bitmap != -1 ) {
677                 bitmap_id = instance->last_bitmap;
678         }
679         else {
680                 if ( instance->last_bitmap != -1 ){
681                         bm_release(instance->last_bitmap);
682                 }
683                 bitmap_id = bm_create(16, instance->parent->width, instance->parent->height, instance->frame, bitmap_flags);
684         }
685         
686         if ( bitmap_id == -1 ) {
687                 // anim has finsished playing, free the instance frame data
688                 anim_release_render_instance(instance); 
689                 return -1;
690
691                 // NOTE: there is no need to free the instance, since it was pre-allocated as 
692                 //       part of the anim_free_list
693         }
694         else {
695                 gr_set_bitmap(bitmap_id, GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
696                 
697                 // determine x,y to display the bitmap at
698                 if ( instance->world_pos == NULL ) {
699                         if ( instance->aa_color == NULL ) {
700                                 gr_bitmap(instance->x, instance->y);
701                         }
702                         else {
703                                 gr_set_color_fast( (color*)instance->aa_color );
704                                 gr_aabitmap(instance->x, instance->y);
705                         }
706                 }
707                 else {
708                         g3_rotate_vertex(&image_vertex,instance->world_pos);
709                         Assert(instance->radius != 0.0f);
710                         g3_draw_bitmap(&image_vertex, 0, instance->radius*1.5f, TMAP_FLAG_TEXTURED );
711                 }
712
713                 //bm_release(bitmap_id);
714                 instance->last_bitmap = bitmap_id;
715         }
716
717         t2 = timer_get_fixed_seconds();
718         render_time = f2fl(t2-t1);
719
720 //      nprintf(("Alan","DECOMPRESS: %.3fms  RENDER: %.3fms\n", decompress_time*1000, render_time*1000));
721
722         return 0;
723 }
724
725 // -----------------------------------------------------------------------------
726 //      anim_stop_playing()
727 //
728 //      Stop an anim instance that is on the anim_render_list from playing
729 //
730 int anim_stop_playing(anim_instance* instance)
731 {
732         Assert(instance != NULL);
733
734         if ( anim_playing(instance) ) {
735                 anim_release_render_instance(instance);
736         }
737         return 0;
738 }
739
740 // -----------------------------------------------------------------------------
741 //      anim_release_render_instance()
742 //
743 //      Free a particular animation instance that is on the anim_render_list.  Do
744 // not call this function to free an animation instance in general (use 
745 // free_anim_instance() for that), only when you want to free an instance
746 // that is on the anim_render_list
747 //
748 void anim_release_render_instance(anim_instance* instance)
749 {
750         Assert( instance != NULL );
751         Assert(instance->frame);
752         free(instance->frame);
753         instance->frame = NULL;
754         instance->parent->instance_count--;
755
756         if ( instance->last_bitmap != -1 ) {
757                 bm_release(instance->last_bitmap); 
758                 instance->last_bitmap = -1;
759         }
760
761         // remove instance from anim_render_list
762         list_remove( &anim_render_list, instance );
763
764         // insert instance into the anim_free_list
765         list_append( &anim_free_list, instance );
766 }
767
768 // -----------------------------------------------------------------------------
769 //      anim_release_all_instances()
770 //
771 //      Free all anim instances that are on the anim_render_list.
772 //
773 //      input:  screen_id       =>              optional parameter that lets you only free a subset
774 //                                                                              of the anim instances.  A screen_id of 0 is the default
775 //                                                                              value, and this is used for animations that always play
776 //                                                                              when they are placed on the aim_render_list.
777 //
778 void anim_release_all_instances(int screen_id)
779 {
780         anim_instance* A;
781         anim_instance* temp;
782
783         if ( Anim_inited == FALSE )
784                 return;
785
786         A = GET_FIRST(&anim_render_list);
787         while( A !=END_OF_LIST(&anim_render_list) )     {
788                 temp = GET_NEXT(A);
789                 if ( A->screen_id == screen_id || screen_id == 0 ) {
790                         anim_release_render_instance(A);
791                 }
792                 A = temp;
793         }
794 }
795
796 // -----------------------------------------------------------------------------
797 //      anim_read_header()
798 //
799 // Read the header of a .ani file.  Below is the format of a .ani header
800 //
801 //      #bytes  |       description
802 //      2                       |       obsolete, kept for compatibility with old versions
803 //      2                       |       version number
804 //      2                       |       fps
805 //      1                       |       transparent red value
806 //      1                       |       transparent green value
807 //      1                       |       transparent blue value
808 //      2                       |       width
809 //      2                       |       height
810 //      2                       |       number of frames
811 //      2                       |       packer code
812 //      763                     |       palette
813 //      2                       |       number of key frames
814 //      2                       |       key frame number        }               repeats
815 //      4                       |       key frame offset        }               repeats
816 //      4                       |       compressed data length
817 //
818 void anim_read_header(anim *ptr, CFILE *fp)
819 {
820         ptr->width = cfread_short(fp);
821         // If first 2 bytes are zero, this means we are using a new format, which includes
822         // a version, and fps values.  This is only done since a version number was not included
823         // in the original header.
824
825         // default
826         Color_xparent.red = 0;
827         Color_xparent.green = 255;
828         Color_xparent.blue = 0;
829
830         if ( ptr->width == 0 ) {
831                 ptr->version = cfread_short(fp);
832                 ptr->fps = cfread_short(fp);
833
834                 // version 2 added a custom transparency color
835                 if ( ptr->version >= 2 ) {
836                         cfread(&Color_xparent.red, 1, 1, fp);
837                         cfread(&Color_xparent.green, 1, 1, fp);
838                         cfread(&Color_xparent.blue, 1, 1, fp);
839                 }
840
841                 ptr->width = cfread_short(fp);
842         }
843         else {
844                 ptr->version = 0;
845                 ptr->fps = 30;
846         }
847         
848         ptr->height = cfread_short(fp);
849
850 #ifndef NDEBUG
851         // get size of ani compared to power of 2
852         int r, floor_pow;
853         r = ptr->height;
854         floor_pow = 0;
855         
856         while(r >= 2) {
857                 r /= 2;
858                 floor_pow++;
859         }
860
861         int floor_size = (int) pow(2, floor_pow);
862         int diff = ptr->height - floor_size;
863         float waste = 100.0f * float((floor_size - diff))/(2.0f *(float)floor_size);
864
865         if (diff != 0) {
866                 if (ptr->height > 16) {
867                         mprintf(("ANI %s with size %dx%d (%.1f%% wasted)\n", ptr->name, ptr->height, ptr->height, waste));
868                 }
869         }
870 #endif
871
872         ptr->total_frames = cfread_short(fp);
873         ptr->packer_code = cfread_ubyte(fp);
874         cfread(&ptr->palette, 256, 3, fp);
875         ptr->num_keys = cfread_short(fp);
876
877         // store xparent colors
878         ptr->xparent_r = Color_xparent.red;
879         ptr->xparent_g = Color_xparent.green;
880         ptr->xparent_b = Color_xparent.blue;
881
882         if(ptr->total_frames == ptr->num_keys){
883                 ptr->flags |= ANF_ALL_KEYFRAMES;
884         }
885 }
886
887 // -----------------------------------------------------------------------------
888 //      anim_load()
889 //
890 // Load an animation.  This stores the compressed data, which instances
891 // of the animation can reference.  Must be free'ed later with anim_free()
892 //
893 // input:       name                            =>              filename of animation
894 //                              file_mapped             =>              boolean, whether to use memory-mapped file or not.
895 //                                                                                      Memory-mapped files will page in the animation from disk
896 //                                                                                      as it is needed, but performance is not as good
897 //
898 //      returns:        pointer to anim that is loaded  => sucess
899 //                              NULL                                                                            =>      failure
900 //
901 anim *anim_load(char *real_filename, int file_mapped)
902 {
903         anim                    *ptr;
904         CFILE                   *fp;
905         int                     count,idx;
906         char name[_MAX_PATH];
907
908 //      file_mapped = 0;
909
910         Assert ( real_filename != NULL );
911
912         strcpy( name, real_filename );
913         char *p = strchr( name, '.' );
914         if ( p ) {
915                 *p = 0;
916         }
917         strcat( name, ".ani" );
918
919         ptr = first_anim;
920         while (ptr) {
921                 if (!stricmp(name, ptr->name))
922                         break;
923
924                 ptr = ptr->next;
925         }
926
927         if (!ptr) {
928                 fp = cfopen(name, "rb");
929                 if ( !fp )
930                         return NULL;
931
932                 ptr = (anim *) malloc(sizeof(anim));
933                 Assert(ptr);
934
935                 ptr->flags = 0;
936                 ptr->next = first_anim;
937                 first_anim = ptr;
938                 Assert(strlen(name) < _MAX_PATH - 1);
939                 strcpy(ptr->name, name);
940                 ptr->instance_count = 0;
941                 ptr->width = 0;
942                 ptr->height = 0;
943                 ptr->total_frames = 0;
944                 ptr->keys = NULL;
945                 ptr->ref_count=0;
946
947                 anim_read_header(ptr, fp);
948
949                 if(ptr->num_keys > 0){
950                         ptr->keys = (key_frame*)malloc(sizeof(key_frame) * ptr->num_keys);
951                         Assert(ptr->keys != NULL);
952                 }                       
953
954                 // store how long the anim should take on playback (in seconds)
955                 ptr->time = i2fl(ptr->total_frames)/ptr->fps;
956
957                 for(idx=0;idx<ptr->num_keys;idx++){
958                         ptr->keys[idx].frame_num = 0;
959                         cfread(&ptr->keys[idx].frame_num, 2, 1, fp);
960                         cfread(&ptr->keys[idx].offset, 4, 1, fp);
961             ptr->keys[idx].frame_num = INTEL_INT( ptr->keys[idx].frame_num );
962             ptr->keys[idx].offset = INTEL_INT( ptr->keys[idx].offset );
963                 }
964
965                 /*prev_keyp = &ptr->keys;
966                 count = ptr->num_keys;
967                 while (count--) {
968                         keyp = (key_frame *) malloc(sizeof(key_frame));
969                         keyp->next = *prev_keyp;
970                         *prev_keyp = keyp;
971                         prev_keyp = &keyp->next;
972
973                         keyp->frame_num = 0;
974                         cfread(&keyp->frame_num, 2, 1, fp);
975                         cfread(&keyp->offset, 4, 1, fp);
976                 }*/
977                 cfread(&count, 4, 1, fp);       // size of compressed data
978         count = INTEL_INT( count );
979
980                 ptr->cfile_ptr = NULL;
981
982                 if ( file_mapped ) {
983                         // Try mapping the file to memory 
984                         ptr->flags |= ANF_MEM_MAPPED;
985                         ptr->cfile_ptr = cfopen(name, "rb", CFILE_MEMORY_MAPPED);
986                 }
987
988                 // couldn't memory-map file... must be in a packfile, so stream manually
989                 if ( file_mapped && !ptr->cfile_ptr ) {
990                         ptr->flags &= ~ANF_MEM_MAPPED;
991                         ptr->flags |= ANF_STREAMED;
992                         ptr->cfile_ptr = cfopen(name, "rb");
993                 }
994
995                 ptr->cache = NULL;
996
997                 // If it opened properly as mem-mapped (or streamed)
998                 if (ptr->cfile_ptr != NULL)     {
999                         // VERY IMPORTANT STEP
1000                         // Set the data pointer to the compressed data (which is not at the start of the
1001                         // file).  Use ftell() to find out how far we've already parsed into the file
1002                         //
1003                         int offset;
1004                         offset = cftell(fp);
1005                         ptr->file_offset = offset;
1006                         if ( ptr->flags & ANF_STREAMED ) {
1007                                 ptr->data = NULL;
1008                                 ptr->cache_file_offset = ptr->file_offset;
1009                                 ptr->cache = (ubyte*)malloc(ANI_STREAM_CACHE_SIZE+2);
1010                                 Assert(ptr->cache);
1011                                 cfseek(ptr->cfile_ptr, offset, CF_SEEK_SET);
1012                                 cfread(ptr->cache, ANI_STREAM_CACHE_SIZE, 1, ptr->cfile_ptr);
1013                         } else {
1014                                 ptr->data = (ubyte*)cf_returndata(ptr->cfile_ptr) + offset;
1015                         }
1016                 } else {
1017                         // Not a memory mapped file (or streamed)
1018                         ptr->flags &= ~ANF_MEM_MAPPED;
1019                         ptr->flags &= ~ANF_STREAMED;
1020                         ptr->data = (ubyte *) malloc(count);
1021                         ptr->file_offset = -1;
1022                         cfread(ptr->data, count, 1, fp);
1023                 }
1024
1025                 cfclose(fp);
1026
1027                 // store screen signature, so we can tell if palette changes
1028                 ptr->screen_sig = gr_screen.signature;
1029
1030                 anim_set_palette(ptr);
1031         }
1032
1033         ptr->ref_count++;
1034         return ptr;
1035 }
1036
1037 // ---------------------------------------------------
1038 //      anim_free()
1039 //
1040 // Free an animation that was loaded with anim_load().  All instances
1041 // referencing this animation must be free'ed or get an assert.
1042 //
1043 int anim_free(anim *ptr)
1044 {
1045         Assert ( ptr != NULL );
1046         anim *list, **prev_anim;
1047
1048         list = first_anim;
1049         prev_anim = &first_anim;
1050         while (list && (list != ptr)) {
1051                 prev_anim = &list->next;
1052                 list = list->next;
1053         }
1054
1055         if ( !list )
1056                 return -2;
1057
1058         // only free when ref_count is 0
1059         ptr->ref_count--;
1060         if ( ptr->ref_count > 0 ) 
1061                 return -1;
1062
1063         // only free if there are no playing instances
1064         if ( ptr->instance_count > 0 )
1065                 return -1;
1066
1067         if(ptr->keys != NULL){
1068                 free(ptr->keys);
1069                 ptr->keys = NULL;
1070         }
1071
1072         if ( ptr->flags & (ANF_MEM_MAPPED|ANF_STREAMED) ) {
1073                 cfclose(ptr->cfile_ptr);
1074                 if ( ptr->cache ) {
1075                         free(ptr->cache);
1076                 }
1077         }
1078         else {
1079                 Assert(ptr->data);
1080                 free(ptr->data);
1081         }
1082
1083         *prev_anim = ptr->next;
1084         free(ptr);
1085         return 0;
1086 }
1087
1088
1089 // ---------------------------------------------------------------------
1090 // anim_playing()
1091 //
1092 // Return if an anim is playing or not.  
1093 //
1094 int anim_playing(anim_instance *ai)
1095 {
1096         Assert(ai != NULL);
1097         if ( ai->frame == NULL )
1098                 return 0;
1099         else 
1100                 return 1;
1101 }
1102
1103
1104 // ---------------------------------------------------------------------
1105 // anim_level_init()
1106 //
1107 // Called at the beginning of a mission to initialize any mission dependent
1108 // anim data.
1109 //
1110 void anim_level_init()
1111 {
1112 }
1113
1114 // ---------------------------------------------------------------------
1115 // anim_level_close()
1116 //
1117 // Called after the end of a mission to clean up any mission dependent 
1118 // anim data. 
1119 //
1120 void anim_level_close()
1121 {
1122         anim_release_all_instances();
1123 }
1124
1125 // ---------------------------------------------------
1126 //      anim_write_frames_out()
1127 //
1128 //      Write the frames of a .ani file out to disk as .pcx files.
1129 // Use naming convention: filename0000.pcx, filename0001.pcx etc.
1130 //
1131 // return:              0       =>              success
1132 //                                      -1      =>              failed
1133 //
1134 int anim_write_frames_out(char *filename)
1135 {
1136         anim                            *source_anim;
1137         anim_instance   *ai;
1138         char                            root_name[256], pcxname[256];
1139         char                            buf[64];
1140         int                             i,j;
1141         ubyte                           **row_data;
1142
1143         strcpy(root_name, filename);
1144         root_name[strlen(filename)-4] = 0;
1145
1146         source_anim = anim_load(filename);
1147         if ( source_anim == NULL ) 
1148                 return -1;
1149
1150         ai = init_anim_instance(source_anim, 16);
1151
1152         row_data = (ubyte**)malloc((source_anim->height+1) * 4);
1153
1154         for ( i = 0; i < source_anim->total_frames; i++ ) {
1155                 anim_get_next_raw_buffer(ai, 0, 0, 16);
1156                 strcpy(pcxname, root_name);
1157                 sprintf(buf,"%04d",i);
1158                 strcat(pcxname, buf);
1159
1160                 for ( j = 0; j < source_anim->height; j++ ) {
1161                         row_data[j] = &ai->frame[j*source_anim->width];
1162                 }
1163
1164
1165                 pcx_write_bitmap( pcxname,
1166                                                                 source_anim->width,
1167                                                                 source_anim->height,
1168                                                                 row_data,
1169                                                                 source_anim->palette);
1170
1171                 printf(".");
1172
1173         }
1174         printf("\n");
1175         free(row_data);
1176         return 0;
1177 }
1178
1179 // ---------------------------------------------------
1180 //      anim_display_info()
1181 //
1182 //      Display information and statistics about a .ani file.
1183 //      This is called when -i switch is on when running ac.exe
1184 //
1185 void anim_display_info(char *real_filename)
1186 {
1187         CFILE                           *fp;
1188         anim                            A;
1189         float                           percent;
1190         int                             i, uncompressed, compressed, *key_frame_nums=NULL, tmp;
1191         char filename[MAX_FILENAME_LEN];
1192
1193         strcpy( filename, real_filename );
1194         char *p = strchr( filename, '.' );
1195         if ( p ) {
1196                 *p = 0;
1197         }
1198         strcat( filename, ".ani" );
1199
1200         fp = cfopen(filename, "rb");
1201         if ( !fp ) {
1202                 printf("Fatal error opening %s", filename);
1203                 return;
1204         }
1205
1206         anim_read_header(&A, fp);
1207         // read the keyframe frame nums and offsets
1208         key_frame_nums = (int*)malloc(sizeof(int)*A.num_keys);
1209         Assert(key_frame_nums != NULL);
1210         for ( i = 0; i < A.num_keys; i++ ) {
1211                 key_frame_nums[i] = 0;
1212                 cfread(&key_frame_nums[i], 2, 1, fp);
1213                 cfread(&tmp, 4, 1, fp);
1214 //printf("key frame num: %d,%d\n", key_frame_nums[i],tmp);
1215         }
1216
1217         cfread(&compressed, 4, 1, fp);
1218
1219         uncompressed = A.width * A.height * A.total_frames;     // 8 bits per pixel
1220         percent = i2fl(compressed) / uncompressed * 100.0f;
1221
1222         printf("%% of uncompressed size:    %.0f%%\n", percent);
1223         printf("Width:                     %d\n", A.width);
1224         printf("Height:                    %d\n", A.height);
1225         printf("Total Frames:              %d\n", A.total_frames);
1226
1227 #ifndef NDEBUG
1228         printf("Key Frames:                %d\n", A.num_keys);
1229         if ( A.num_keys > 1 && (A.total_frames != A.num_keys) ) {
1230                 printf("key list: (");
1231                 for ( i = 0; i < A.num_keys; i++ ) {
1232                         if ( i < A.num_keys-1 ) 
1233                                 printf("%d, ", key_frame_nums[i]);
1234                         else
1235                                 printf("%d)\n", key_frame_nums[i]);
1236                 }
1237         }
1238 #endif
1239
1240         printf("FPS:                       %d\n", A.fps);
1241
1242 #ifndef NDEBUG
1243         printf("Transparent RGB:           (%d,%d,%d)\n", A.xparent_r, A.xparent_g, A.xparent_b); 
1244 #endif
1245
1246         printf("ac version:                %d\n", A.version);
1247
1248         if ( key_frame_nums != NULL ) {
1249                 free(key_frame_nums);
1250         }
1251
1252         cfclose(fp);
1253 }
1254
1255 void anim_reverse_direction(anim_instance *ai)
1256 {
1257         int temp;
1258
1259         if(!(ai->parent->flags & ANF_ALL_KEYFRAMES)){
1260                  // you're not allowed to call anim_reverse_direction(...) unless every frame is a keyframe!!!!
1261                  // The God of Delta-RLE demands it be thus.
1262                 Int3();
1263         }
1264                 
1265         // flip the animation direction
1266         if(ai->direction == ANIM_DIRECT_FORWARD){
1267                 ai->direction = ANIM_DIRECT_REVERSE;                            
1268         } else if(ai->direction == ANIM_DIRECT_REVERSE){
1269                 ai->direction = ANIM_DIRECT_FORWARD;
1270         }
1271
1272         // flip frame_num and last_frame_num
1273         temp = ai->frame_num;
1274         ai->frame_num = ai->last_frame_num;
1275         ai->last_frame_num = temp;
1276
1277         // flip the start and stop at frames
1278         temp = ai->stop_at;
1279         ai->stop_at = ai->start_at;
1280         ai->start_at = temp;
1281
1282         // make sure to sync up the time correctly 
1283         if(ai->direction == ANIM_DIRECT_FORWARD){
1284                 ai->time_elapsed = ((float)ai->frame_num - (float)ai->start_at - 1.0f) / (float)ai->parent->fps;        
1285         } else if(ai->direction == ANIM_DIRECT_REVERSE) {
1286                 ai->time_elapsed = ((float)ai->start_at - (float)ai->frame_num - 1.0f) / (float)ai->parent->fps;        
1287         }       
1288 }
1289
1290 void anim_pause(anim_instance *ai)
1291 {
1292         ai->paused = 1;
1293 }
1294
1295 void anim_unpause(anim_instance *ai)
1296 {
1297         ai->paused = 0;
1298 }
1299
1300 void anim_ignore_next_frametime()
1301 {
1302         Anim_ignore_frametime=1;
1303 }
1304
1305 int anim_instance_is_streamed(anim_instance *ai)
1306 {
1307         Assert(ai);
1308         return ( ai->parent->flags & ANF_STREAMED );
1309 }
1310
1311 unsigned char anim_instance_get_byte(anim_instance *ai, int offset)
1312 {
1313         int absolute_offset;
1314         anim *parent;
1315         
1316         Assert(ai);
1317         Assert(ai->parent->cfile_ptr);
1318         Assert(ai->parent->flags & ANF_STREAMED);
1319
1320         parent = ai->parent;
1321         absolute_offset = ai->file_offset + offset;
1322
1323         // maybe in cache?
1324         int cache_offset;
1325         cache_offset = absolute_offset - parent->cache_file_offset;
1326         if ( (cache_offset >= 0) && (cache_offset < ANI_STREAM_CACHE_SIZE) ) {
1327                 return parent->cache[cache_offset];
1328         } else {
1329                 // fill cache
1330                 cfseek(parent->cfile_ptr, absolute_offset, CF_SEEK_SET);
1331                 cfread(parent->cache, ANI_STREAM_CACHE_SIZE, 1, parent->cfile_ptr);
1332                 parent->cache_file_offset = absolute_offset;
1333                 return parent->cache[0];
1334         }
1335 }
1336