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