JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
whitespace changes: return types in function definitions on previous line, deleted...
[vor.git] / main.c
1 /* Variations on RockDodger
2  * Space Rocks copyright (C) 2001 Paul Holt <pad@pcholt.com>
3  *
4  * Project fork 2004, Jason Woofenden and Joshua Grams.
5  * (a whole bunch of modifications and project rename)
6
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by the
9  * Free Software Foundation; either version 2 of the License, or (at your
10  * option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */
21
22 #undef DEBUG
23
24 extern int font_height;
25 void clearBuffer();
26
27 #include "config.h"
28 #include "file.h"
29 #include "sound.h"
30
31 #include <math.h>
32 #include <SDL/SDL.h>
33 #include <SDL/SDL_image.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39
40 #include "SFont.h"
41
42 #define CONDERROR(a) if((a)) {initerror = strdup(SDL_GetError());return 1;}
43 #define NULLERROR(a) CONDERROR((a) == NULL)
44
45 // ************************************* STRUCTS
46 struct rock_struct {
47         // Array of black pixel coordinates. This is scanned 
48         // every frame to see if it's still black, and as
49         // soon as it isn't we BLOW UP
50         float x,y,xvel,yvel;
51         int active;
52         int dead;  // has been blown out of the way
53                    // to make room for a new ship appearing.
54         SDL_Surface *image;
55         int type_number;
56 }; 
57 struct black_point_struct {
58         int x,y;
59 };
60 struct bangdots {
61         // Bang dots have the same colour as shield dots.
62         // Bang dots get darker as they age.
63         // Some are coloured the same as the ex-ship.
64         float x,y,dx,dy;
65         Uint16 c; // when zero, use heatcolor[bangdotlife]
66         float life;     // When reduced to 0, set active = 0
67         int active;
68         float decay;// Amount by which to reduce life each time dot is drawn
69 };
70 struct enginedots {
71         // Engine dots stream out the back of the ship, getting darker as they go.
72         int active;
73         float x,y,dx,dy;
74         // The life of an engine dot 
75         // is a number starting at between 0 and 50 and counting backward.
76         float life;     // When reduced to 0, set active = 0
77 };
78 struct spacedot {
79         // Space dots are harmless background items
80         // All are active. When one falls off the edge, another is created at the start.
81         float x,y,dx;
82         Uint16 color;
83 };
84 // High score table
85 struct highscore {
86         int score;
87         char *name;
88         int allocated;
89 } high[] = {
90         {13000,"Pad",0},
91         {12500,"Pad",0},
92         {6500,"Pad",0},
93         {5000,"Pad",0},
94         {3000,"Pad",0},
95         {2500,"Pad",0},
96         {2000,"Pad",0},
97         {1500,"Pad",0}
98 };
99
100 // ************************************* VARS
101 // SDL_Surface global variables
102 SDL_Surface 
103         *surf_screen,   // Screen
104         *surf_b_variations, // "variations" banner
105         *surf_b_on, // "on" banner
106         *surf_b_rockdodger, // "rockdodger" banner
107         *surf_b_game,   // Title element "game"
108         *surf_b_over,   // Title element "over"
109         *surf_ship,             // Spaceship element
110         *surf_life,     // Indicator of number of ships remaining
111         *surf_rock[NROCKS],     // THE ROCKS
112         *surf_deadrock[NROCKS], // THE DEAD ROCKS
113         *surf_font_big; // The big font
114
115 // Structure global variables
116 struct enginedots edot[MAXENGINEDOTS], *dotptr = edot;
117 struct rock_struct rock[MAXROCKS], *rockptr = rock;
118 struct black_point_struct black_point[MAXBLACKPOINTS], *blackptr = black_point;
119 struct bangdots bdot[MAXBANGDOTS], *bdotptr = bdot;
120 struct spacedot sdot[MAXSPACEDOTS];
121
122 // Other global variables
123 char topline[1024];
124 char *initerror = "";
125 char name[1024], debug1[1024];
126
127 float xship,yship = 240.0;      // X position, 0..XSIZE
128 float xvel,yvel;        // Change in X position per tick.
129 float rockrate,rockspeed;
130 float movementrate;
131 float yscroll;
132 float scrollvel;
133
134 int nships,score,initticks,ticks_since_last, last_ticks;
135 int gameover;
136 int countdown = 0;
137 int maneuver = 0;
138 int sound_flag = 1, music_flag = 0;
139 int tail_plume = 0; // display big engine at the back?
140 int friction = 0;       // should there be friction?
141 int scorerank;
142 float fadetimer = 0,faderate;
143
144 int pausedown = 0,paused = 0;
145
146 // bangdot start (bd1) and end (bd2) position:
147 int bd1 = 0, bd2 = 0;
148
149 int xoffset[NROCKS][MAXROCKHEIGHT];
150
151 enum states {
152         TITLE_PAGE,
153         GAMEPLAY,
154         DEAD_PAUSE,
155         GAME_OVER,
156         HIGH_SCORE_ENTRY,
157         HIGH_SCORE_DISPLAY,
158         DEMO
159 };
160 enum states state = TITLE_PAGE;
161 float state_timeout = 600.0;
162
163 const int fakesin[] = {0,1,0,-1};
164 const int fakecos[] = {1,0,-1,0};
165 #define NSEQUENCE 2
166 char *sequence[] = {
167         "Press SPACE to start",
168         "http://qualdan.com/vor/"
169 };
170
171 int bangdotlife, nbangdots;
172 Uint16 heatcolor[W*3];
173
174 char *data_dir;
175 extern char *optarg;
176 extern int optind, opterr, optopt;
177
178 float dist_sq(float x1, float y1, float x2, float y2)
179 {
180         return (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1);
181 }
182
183 // ************************************* FUNCS
184
185 void
186 read_high_score_table() {
187         FILE *f;
188         int i;
189         
190         f = open_score_file("r");
191         if(f) {
192                 // If the file exists, read from it
193                 for(i = 0; i<8; i++) {
194                         char s[1024];
195                         int highscore;
196                         if(fscanf (f, "%d %[^\n]", &highscore, s) != 2) {
197                                 break;
198                         }
199                         if(high[i].allocated) {
200                                 free(high[i].name);
201                         }
202                         high[i].name = strdup(s);
203                         high[i].score = highscore;
204                         high[i].allocated = 1;
205                 }
206                 fclose(f);
207         }
208 }
209
210 void
211 write_high_score_table() {
212         FILE *f;
213         int i;
214         
215         f = open_score_file("w");
216         if(f) {
217                 // If the file exists, write to it
218                 for(i = 0; i<8; i++) {
219                         fprintf (f, "%d %s\n", high[i].score, high[i].name);
220                 }
221                 fclose(f);
222         }
223 }
224
225 void
226 snprintscore(char *s, size_t n, int score) {
227         int min = score/60000;
228         int sec = score/1000%60;
229         int tenths = score%1000/100;
230         if(min) {
231                 snprintf(s, n, "%2d:%.2d.%d", min, sec, tenths);
232         } else {
233                 snprintf(s, n, " %2d.%d", sec, tenths);
234         }
235 }
236
237 float
238 rnd() {
239         return (float)random()/(float)RAND_MAX;
240 }
241
242 void
243 init_engine_dots() {
244         int i;
245         for(i = 0; i<MAXENGINEDOTS; i++) {
246                 edot[i].active = 0;
247         }
248 }
249
250 void
251 init_space_dots() {
252         int i,intensity;
253         for(i = 0; i<MAXSPACEDOTS; i++) {
254                 float r;
255
256                 sdot[i].x = rnd()*(XSIZE-5);
257                 sdot[i].y = rnd()*(YSIZE-5);
258
259                 r = rnd()*rnd();
260
261                 sdot[i].dx = -r*4;
262                 // -1/((1-r) + .3);
263                 intensity = (int)(r*180 + 70);
264                 sdot[i].color = SDL_MapRGB(surf_screen->format,intensity,intensity,intensity);
265
266         }
267 }
268
269 void
270 makebangdots(int xbang, int ybang, int xvel, int yvel, SDL_Surface *s, int power) {
271
272         // TODO - stop generating dots after a certain amount of time has passed, to cope with slower CPUs.
273         // TODO - generate and display dots in a circular buffer
274
275         int x,y,endcount;
276         Uint16 *rawpixel,c;
277         double theta,r;
278         int begin_generate;
279
280         begin_generate = SDL_GetTicks();
281
282         SDL_LockSurface(s);
283         rawpixel = (Uint16 *) s->pixels;
284
285         //for(n = 0; n <= power/2; n++) {
286
287         endcount = 0;
288         while (endcount<3) {
289                 for(x = 0; x<s->w; x++) {
290                         for(y = 0; y<s->h; y++) {
291                                 c = rawpixel[s->pitch/2*y + x];
292                                 if(c && c != SDL_MapRGB(s->format,0,255,0)) {
293
294                                         theta = rnd()*M_PI*2;
295
296                                         r = 1-(rnd()*rnd());
297
298                                         bdot[bd2].dx = (power/50.0)*45.0*cos(theta)*r + xvel;
299                                         bdot[bd2].dy = (power/50.0)*45.0*sin(theta)*r + yvel;
300                                         bdot[bd2].x = x + xbang;
301                                         bdot[bd2].y = y + ybang;
302
303                                         // Replace the last few bang dots with the pixels from the exploding object
304                                         bdot[bd2].c = (endcount>0)?c:0;
305                                         bdot[bd2].life = 100;
306                                         bdot[bd2].decay = rnd()*3 + 1;
307                                         bdot[bd2].active = 1;
308
309                                         bd2++;
310                                         bd2 %= MAXBANGDOTS;
311
312                                         // If the circular buffer is filled, who cares? They've had their chance.
313                                         //if(bd2 == bd1-1) goto exitloop;
314
315                                 }
316                         }
317                 }
318
319                 if(SDL_GetTicks() - begin_generate > 7) endcount++;
320         }
321
322         SDL_UnlockSurface(s);
323
324 }
325
326 void
327 draw_bang_dots(SDL_Surface *s) {
328         int i;
329         int first_i, last_i;
330         Uint16 *rawpixel;
331         rawpixel = (Uint16 *) s->pixels;
332
333         first_i = -1;
334
335         for(i = bd1; (bd1 <= bd2)?(i<bd2):(i >= bd1 && i < bd2); last_i = ++i) {
336
337                 i %= MAXBANGDOTS;
338
339                 if(bdot[i].x <= 0 || bdot[i].x >= XSIZE || bdot[i].y <= 0 || bdot[i].y >= YSIZE) {
340                         // If the dot has drifted outside the perimeter, kill it
341                         bdot[i].active = 0;
342                 }
343
344                 if(bdot[i].active) {
345                         if(first_i < 0)
346                         first_i = i;
347                         //last_i = i + 1;
348                         rawpixel[(int)(s->pitch/2*(int)(bdot[i].y)) + (int)(bdot[i].x)] = bdot[i].c ? bdot[i].c : heatcolor[(int)(bdot[i].life*3)];
349                         bdot[i].life -= bdot[i].decay;
350                         bdot[i].x += bdot[i].dx*movementrate;
351                         bdot[i].y += bdot[i].dy*movementrate + yscroll;
352
353                         if(bdot[i].life<0)
354                         bdot[i].active = 0;
355                 }
356         }
357
358         if(first_i >= 0) {
359                 bd1 = first_i;
360                 bd2 = last_i;
361         }
362         else {
363                 bd1 = 0;
364                 bd2 = 0;
365         }
366
367 }
368
369
370 void
371 draw_space_dots(SDL_Surface *s) {
372         int i;
373         Uint16 *rawpixel;
374         rawpixel = (Uint16 *) s->pixels;
375
376         for(i = 0; i<MAXSPACEDOTS; i++) {
377                 if(sdot[i].y<0) {
378                         sdot[i].y = 0;
379                 }
380                 rawpixel[(int)(s->pitch/2*(int)sdot[i].y) + (int)(sdot[i].x)] = sdot[i].color;
381                 sdot[i].x += sdot[i].dx*movementrate;
382                 sdot[i].y += yscroll;
383                 if(sdot[i].y > YSIZE) {
384                         sdot[i].y -= YSIZE;
385                 } else if(sdot[i].y < 0) {
386                         sdot[i].y += YSIZE;
387                 }
388                 if(sdot[i].x<0) {
389                         sdot[i].x = XSIZE;
390                 }
391         }
392 }
393
394 void
395 draw_engine_dots(SDL_Surface *s) {
396         int i;
397         Uint16 *rawpixel;
398         rawpixel = (Uint16 *) s->pixels;
399
400         for(i = 0; i<MAXENGINEDOTS; i++) {
401                 if(edot[i].active) {
402                         edot[i].x += edot[i].dx*movementrate;
403                         edot[i].y += edot[i].dy*movementrate + yscroll;
404                         if((edot[i].life -= movementrate*3)<0 || edot[i].y<0 || edot[i].y>YSIZE) {
405                                 edot[i].active = 0;
406                         } else if(edot[i].x<0 || edot[i].x>XSIZE) {
407                                 edot[i].active = 0;
408                         } else {
409                                 int heatindex;
410                                 heatindex = edot[i].life * 6;
411                                 //rawpixel[(int)(s->pitch/2*(int)(edot[i].y)) + (int)(edot[i].x)] = lifecolor[(int)(edot[i].life)];
412                                 rawpixel[(int)(s->pitch/2*(int)(edot[i].y)) + (int)(edot[i].x)] = heatindex>3*W ? heatcolor[3*W-1] : heatcolor[heatindex];
413                         }
414                 }
415         }
416 }
417
418 void
419 create_engine_dots(int newdots) {
420         int i;
421         double theta,r,dx,dy;
422
423         if(!tail_plume) return;
424
425         if(state == GAMEPLAY) {
426                 for(i = 0; i<newdots*movementrate; i++) {
427                         if(dotptr->active == 0) {
428                                 theta = rnd()*M_PI*2;
429                                 r = rnd();
430                                 dx = cos(theta)*r;
431                                 dy = sin(theta)*r;
432
433                                 dotptr->active = 1;
434                                 dotptr->x = xship + surf_ship->w/2-14;
435                                 dotptr->y = yship + surf_ship->h/2 + (rnd()-0.5)*5-1;
436                                 dotptr->dx = 10*(dx-1.5) + xvel;
437                                 dotptr->dy = 1*dy + yvel;
438                                 dotptr->life = 45 + rnd(1)*5;
439
440                                 dotptr++;
441                                 if(dotptr-edot >= MAXENGINEDOTS) {
442                                         dotptr = edot;
443                                 }
444                         }
445                 }
446         }
447 }
448
449 void
450 create_engine_dots2(int newdots, int m) {
451         int i;
452         double theta, theta2, dx, dy, adx, ady;
453
454         // Don't create fresh engine dots when
455         // the game is not being played and a demo is not beng shown
456         if(state != GAMEPLAY && state != DEMO) return;
457
458         for(i = 0; i<newdots; i++) {
459                 if(dotptr->active == 0) {
460                         theta = rnd()*M_PI*2;
461                         theta2 = rnd()*M_PI*2;
462
463                         dx = cos(theta) * fabs(cos(theta2));
464                         dy = sin(theta) * fabs(cos(theta2));
465                         adx = fabs(dx);
466                         ady = fabs(dy);
467
468
469                         dotptr->active = 1;
470                         dotptr->x = xship + surf_ship->w/2 + (rnd()-0.5)*3;
471                         dotptr->y = yship + surf_ship->h/2 + (rnd()-0.5)*3;
472
473                         switch(m) {
474                                 case 0:
475                                         dotptr->x -= 14;
476                                         dotptr->dx = -20*adx + xvel;
477                                         dotptr->dy = 2*dy + yvel;
478                                         dotptr->life = 60 * adx;
479                                 break;
480                                 case 1:
481                                         dotptr->dx = 2*dx + xvel;
482                                         dotptr->dy = -20*ady + yvel;
483                                         dotptr->life = 60 * ady;
484                                 break;
485                                 case 2:
486                                         dotptr->x += 14;
487                                         dotptr->dx = 20*adx + xvel;
488                                         dotptr->dy = 2*dy + yvel;
489                                         dotptr->life = 60 * adx;
490                                 break;
491                                 case 3:
492                                         dotptr->dx = 2*dx + xvel;
493                                         dotptr->dy = 20*ady + yvel;
494                                         dotptr->life = 60 * ady;
495                                 break;
496                         }
497                         dotptr++;
498                         if(dotptr-edot >= MAXENGINEDOTS) {
499                                 dotptr = edot;
500                         }
501                 }
502         }
503 }
504
505 void
506 drawdots(SDL_Surface *s) {
507         int m, scorepos, n;
508
509         SDL_LockSurface(s);
510         // Draw the background stars aka space dots
511         draw_space_dots(s);
512
513         // Draw the score when playing the game or whn the game is freshly over
514         if(1 || state == GAMEPLAY || state == DEAD_PAUSE || state == GAME_OVER ) {
515                 SDL_UnlockSurface(s);
516
517                 scorepos = XSIZE-250;
518                 n = snprintf(topline, 50, "Time: ");
519                 snprintscore(topline + n, 50-n, score);
520                 PutString(s,scorepos,0,topline);
521
522                 SDL_LockSurface(s);
523         }
524
525         // Draw all the engine dots
526         draw_engine_dots(s);
527
528         // Create more engine dots comin out da back
529         if(!gameover)
530         create_engine_dots(200);
531
532         // Create engine dots out the side we're moving from
533         for(m = 0; m<4; m++) {
534                 if(maneuver & 1<<m) { // 'maneuver' is a bit field
535                         create_engine_dots2(80,m);
536                 }
537         }
538
539         // Draw all outstanding bang dots
540         //if(bangdotlife-- > 0) 
541         draw_bang_dots(s);
542
543         SDL_UnlockSurface(s);
544 }
545
546 int
547 init(int fullscreen) {
548
549         int i,j;
550         SDL_Surface *temp;
551         Uint16 *raw_pixels;
552         Uint32 flag;
553
554         // Where are our data files?
555         if(!find_files()) exit(1);
556         read_high_score_table();
557
558         if(sound_flag) {
559                 // Initialize SDL with audio and video
560                 if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) {
561                         sound_flag = 0;
562                         printf ("Can't open sound, starting without it\n");
563                         atexit(SDL_Quit);
564                 } else {
565                         atexit(SDL_Quit);
566                         atexit(SDL_CloseAudio);
567                         sound_flag = init_sound();
568                 }
569         } else {
570                 // Initialize with video only
571                 CONDERROR(SDL_Init(SDL_INIT_VIDEO) != 0);
572                 atexit(SDL_Quit);
573         }
574
575         play_tune(0);
576
577         // Attempt to get the required video size
578         flag = SDL_DOUBLEBUF | SDL_HWSURFACE;
579         if(fullscreen) flag |= SDL_FULLSCREEN;
580         surf_screen = SDL_SetVideoMode(XSIZE,YSIZE,16,flag);
581
582         // Set the title bar text
583         SDL_WM_SetCaption("Variations on Rockdodger", "VoR");
584
585         NULLERROR(surf_screen);
586
587         // Set the heat color from the range 0 (cold) to 300 (blue-white)
588         for(i = 0; i<W*3; i++) {
589                 heatcolor[i] = SDL_MapRGB(
590                         surf_screen->format,
591                         (i<W)?(i*M/W):(M),(i<W)?0:(i<2*W)?((i-W)*M/W):M,(i<2*W)?0:((i-W)*M/W) // Got that?
592                 );
593         }
594
595         // Load the banners
596         NULLERROR(temp = IMG_Load(load_file("banners/variations.png")));
597         NULLERROR(surf_b_variations = SDL_DisplayFormat(temp));
598
599         NULLERROR(temp = IMG_Load(load_file("banners/on.png")));
600         NULLERROR(surf_b_on = SDL_DisplayFormat(temp));
601
602         NULLERROR(temp = IMG_Load(load_file("banners/rockdodger.png")));
603         NULLERROR(surf_b_rockdodger = SDL_DisplayFormat(temp));
604
605         NULLERROR(temp = IMG_Load(load_file("banners/game.png")));
606         NULLERROR(surf_b_game = SDL_DisplayFormat(temp));
607
608         NULLERROR(temp = IMG_Load(load_file("banners/over.png")));
609         NULLERROR(surf_b_over = SDL_DisplayFormat(temp));
610
611         surf_font_big = IMG_Load(load_file(BIG_FONT_FILE));
612         InitFont(surf_font_big);
613
614         // Load the spaceship graphic.
615         NULLERROR(temp = IMG_Load(load_file("sprites/ship.png")));
616         NULLERROR(surf_ship = SDL_DisplayFormat(temp));
617
618         // Load the life indicator (small ship) graphic.
619         NULLERROR(temp = IMG_Load(load_file("indicators/life.png")));
620         NULLERROR(surf_life = SDL_DisplayFormat(temp));
621
622         // Create the array of black points;
623         SDL_LockSurface(surf_ship);
624         raw_pixels = (Uint16 *) surf_ship->pixels;
625         for(i = 0; i<surf_ship->w; i++) {
626                 for(j = 0; j<surf_ship->h; j++) {
627                         if(raw_pixels[j*(surf_ship->pitch)/2 + i] == 0) {
628                                 blackptr->x = i;
629                                 blackptr->y = j;
630                                 blackptr++;
631                         }
632                 }
633         }
634
635         SDL_UnlockSurface(surf_ship);
636
637         init_engine_dots();
638         init_space_dots();
639
640         // Load all our lovely rocks
641         for(i = 0; i<NROCKS; i++) {
642                 char a[100];
643
644                 sprintf(a,load_file("sprites/rock%d.png"),i);
645                 NULLERROR(temp = IMG_Load(a));
646                 NULLERROR(surf_rock[i] = SDL_DisplayFormat(temp));
647
648                 sprintf(a,load_file("sprites/deadrock%d.png"),i);
649                 NULLERROR(temp = IMG_Load(a));
650                 NULLERROR(surf_deadrock[i] = SDL_DisplayFormat(temp));
651         }
652
653         // Remove the mouse cursor
654 #ifdef SDL_DISABLE
655         SDL_ShowCursor(SDL_DISABLE);
656 #endif
657
658         return 0;
659 }
660
661 int
662 draw() {
663         int i;
664         SDL_Rect src,dest;
665         struct black_point_struct *p;
666         Uint16 *raw_pixels;
667         int bang, offset, x;
668         char *text;
669         float fadegame,fadeover;
670
671         bang = 0;
672
673         src.x = 0;
674         src.y = 0;
675         dest.x = 0;
676         dest.y = 0;
677
678         // Draw a fully black background
679         SDL_FillRect(surf_screen,NULL,0);
680
681         // Draw the background dots
682         drawdots(surf_screen);
683
684         // Draw ship
685         if(!gameover && (state == GAMEPLAY || state == DEMO) ) {
686                 src.w = surf_ship->w;
687                 src.h = surf_ship->h;
688                 dest.w = src.w;
689                 dest.h = src.h;
690                 dest.x = (int)xship;
691                 dest.y = (int)yship;
692                 SDL_BlitSurface(surf_ship,&src,surf_screen,&dest);
693         }
694
695         // Draw all the rocks, in all states
696         for(i = 0; i<MAXROCKS; i++) {
697                 if(rock[i].active) {
698
699                         src.w = rock[i].image->w;
700                         src.h = rock[i].image->h;
701                         dest.w = src.w;
702                         dest.h = src.h;
703                         dest.x = (int) rock[i].x;
704                         dest.y = (int) rock[i].y;
705
706                         // Draw the rock
707                         SDL_BlitSurface(rock[i].image,&src,surf_screen,&dest);
708
709                 }
710         }
711
712         // If it's game over, show the game over graphic in the dead centre
713         switch (state) {
714                 case GAME_OVER:
715                         if(fadetimer<3.0/faderate) {
716                                 fadegame = fadetimer/(3.0/faderate);
717                         } else {
718                                 fadegame = 1.0;
719                         }
720
721                         if(fadetimer<3.0/faderate) {
722                                 fadeover = 0.0;
723                         } else if(fadetimer<6.0/faderate) {
724                                 fadeover = ((3.0/faderate)-fadetimer)/(6.0/faderate);
725                         } else {
726                                 fadeover = 1.0;
727                         }
728
729                         src.w = surf_b_game->w;
730                         src.h = surf_b_game->h;
731                         dest.w = src.w;
732                         dest.h = src.h;
733                         dest.x = (XSIZE-src.w)/2;
734                         dest.y = (YSIZE-src.h)/2-40;
735                         SDL_SetAlpha(surf_b_game, SDL_SRCALPHA, (int)(fadegame*(200 + 55*cos(fadetimer += movementrate/1.0))));
736                         SDL_BlitSurface(surf_b_game,&src,surf_screen,&dest);
737
738                         src.w = surf_b_over->w;
739                         src.h = surf_b_over->h;
740                         dest.w = src.w;
741                         dest.h = src.h;
742                         dest.x = (XSIZE-src.w)/2;
743                         dest.y = (YSIZE-src.h)/2 + 40;
744                         SDL_SetAlpha(surf_b_over, SDL_SRCALPHA, (int)(fadeover*(200 + 55*sin(fadetimer))));
745                         SDL_BlitSurface(surf_b_over,&src,surf_screen,&dest);
746                 break;
747
748                 case TITLE_PAGE:
749
750                         src.w = surf_b_variations->w;
751                         src.h = surf_b_variations->h;
752                         dest.w = src.w;
753                         dest.h = src.h;
754                         dest.x = (XSIZE-src.w)/2 + cos(fadetimer/6.5)*10;
755                         dest.y = (YSIZE/2-src.h)/2 + sin(fadetimer/5.0)*10;
756                         SDL_SetAlpha(surf_b_variations, SDL_SRCALPHA, (int)(200 + 55*sin(fadetimer += movementrate/2.0)));
757                         SDL_BlitSurface(surf_b_variations,&src,surf_screen,&dest);
758
759                         src.w = surf_b_on->w;
760                         src.h = surf_b_on->h;
761                         dest.w = src.w;
762                         dest.h = src.h;
763                         dest.x = (XSIZE-src.w)/2 + cos((fadetimer + 1.0)/6.5)*10;
764                         dest.y = (YSIZE/2-src.h)/2 + surf_b_variations->h + 20 + sin((fadetimer + 1.0)/5.0)*10;
765                         SDL_SetAlpha(surf_b_on, SDL_SRCALPHA, (int)(200 + 55*sin(fadetimer-1.0)));
766                         SDL_BlitSurface(surf_b_on,&src,surf_screen,&dest);
767
768                         src.w = surf_b_rockdodger->w;
769                         src.h = surf_b_rockdodger->h;
770                         dest.w = src.w;
771                         dest.h = src.h;
772                         dest.x = (XSIZE-src.w)/2 + cos((fadetimer + 2.0)/6.5)*10;
773                         dest.y = (YSIZE/2-src.h)/2 + surf_b_variations->h + surf_b_on->h + 40 + sin((fadetimer + 2.0)/5)*10;
774                         SDL_SetAlpha(surf_b_rockdodger, SDL_SRCALPHA, (int)(200 + 55*sin(fadetimer-2.0)));
775                         SDL_BlitSurface(surf_b_rockdodger,&src,surf_screen,&dest);
776
777                         text = "Version " VERSION;
778                         x = (XSIZE-SFont_wide(text))/2 + sin(fadetimer/4.5)*10;
779                         PutString(surf_screen,x,YSIZE-50 + sin(fadetimer/2)*5,text);
780
781                         text = sequence[(int)(fadetimer/40)%NSEQUENCE];
782                         //text = "Press SPACE to start!";
783                         x = (XSIZE-SFont_wide(text))/2 + cos(fadetimer/4.5)*10;
784                         PutString(surf_screen,x,YSIZE-100 + cos(fadetimer/3)*5,text);
785                 break;
786
787                 case HIGH_SCORE_ENTRY:
788
789                         if(score >= high[7].score) {
790                                 play_tune(2);
791                                 if(SFont_Input (surf_screen, 330, 50 + (scorerank + 2)*font_height, 300, name)) {
792                                         // Insert name into high score table
793
794                                         // Lose the lowest name forever (loser!)
795                                         //if(high[7].allocated)
796                                         //      free(high[7].name);                     // THIS WAS CRASHING SO I REMOVED IT
797
798                                         // Insert new high score
799                                         high[scorerank].score = score;
800                                         high[scorerank].name = strdup(name);    // MEMORY NEVER FREED!
801                                         high[scorerank].allocated = 1;
802                         
803                                         // Set the global name string to "", ready for the next winner
804                                         name[0] = 0;
805                         
806                                         // Change state to briefly show high scores page
807                                         state = HIGH_SCORE_DISPLAY;
808                                         state_timeout = 200;
809
810                                         // Write the high score table to the file
811                                         write_high_score_table();
812                         
813                                         // Play the title page tune
814                                         play_tune(0);
815                                 }
816                         } else {
817                                 state = HIGH_SCORE_DISPLAY;
818                                 state_timeout = 400;
819                         }
820                 // FALL THROUGH
821
822                 case HIGH_SCORE_DISPLAY:
823                         // Display de list o high scores mon.
824                         PutString(surf_screen,180,50,"High scores");
825                         for(i = 0; i<8; i++) {
826                                 char s[1024];
827                                 sprintf(s, "#%1d",i + 1);
828                                 PutString(surf_screen, 150, 50 + (i + 2)*font_height,s);
829                                 snprintscore(s, 1024, high[i].score);
830                                 PutString(surf_screen, 200, 50 + (i + 2)*font_height,s);
831                                 sprintf(s, "%3s", high[i].name);
832                                 PutString(surf_screen, 330, 50 + (i + 2)*font_height,s);
833                         }
834
835         }
836
837         if(!gameover && state == GAMEPLAY) {
838                 SDL_LockSurface(surf_screen);
839                 raw_pixels = (Uint16 *) surf_screen->pixels;
840                 // Check that the black points on the ship are
841                 // still black, and not covered up by rocks.
842                 for(p = black_point; p<blackptr; p++) { 
843                         offset = surf_screen->pitch/2 * (p->y + (int)yship) + p->x + (int)xship;
844                         if(raw_pixels[offset]) {
845                                 // Set the bang flag
846                                 bang = 1;
847                         }
848                 }
849                 SDL_UnlockSurface(surf_screen);
850         }
851
852         // Draw all the little ships
853         if(state == GAMEPLAY || state == DEAD_PAUSE || state == GAME_OVER)
854         for(i = 0; i<nships-1; i++) {
855                 src.w = surf_life->w;
856                 src.h = surf_life->h;
857                 dest.w = src.w;
858                 dest.h = src.h;
859                 dest.x = (i + 1)*(src.w + 10);
860                 dest.y = 20;
861                 SDL_BlitSurface(surf_life,&src,surf_screen,&dest);
862         }
863
864
865         // Update the score
866         /*
867         n = SDL_GetTicks()-initticks;
868         if(score)
869         ticks_since_last = n-score;
870         score = n;
871         */
872
873         ticks_since_last = SDL_GetTicks()-last_ticks;
874         last_ticks = SDL_GetTicks();
875         if(ticks_since_last>200 || ticks_since_last<0) {
876                 movementrate = 0;
877         }
878         else {
879                 movementrate = ticks_since_last/50.0;
880                 if(state == GAMEPLAY) {
881                         score += ticks_since_last;
882                 }
883         }
884
885         // Update the surface
886         SDL_Flip(surf_screen);
887
888
889         return bang;
890 }
891
892 int
893 gameloop() {
894         int i = 0;
895         Uint8 *keystate;
896
897
898         for(;;) {
899                 if(!paused) {
900                         // Count down the game loop timer, and change state when it gets to zero or less;
901
902                         if((state_timeout -= movementrate*3) < 0) {
903                                 switch(state) {
904                                         case DEAD_PAUSE:
905                                                 // Create a new ship and start all over again
906                                                 state = GAMEPLAY;
907                                                 play_tune(1);
908                                                 xship -= 50;
909                                         break;
910                                         case GAME_OVER:
911                                                 state = HIGH_SCORE_ENTRY;
912                                                 clearBuffer();
913                                                 name[0] = 0;
914                                                 state_timeout = 5.0e6;
915
916                                                 if(score >= high[7].score) {
917                                                         // Read the high score table from the storage file
918                                                         read_high_score_table();
919
920                                                         // Find ranking of this score, store as scorerank
921                                                         for(i = 0; i<8; i++) {
922                                                         if(high[i].score <= score) {
923                                                                 scorerank = i;
924                                                                 break;
925                                                         }
926                                                         }
927
928                                                         // Move all lower scores down a notch
929                                                         for(i = 7; i >= scorerank; i--)
930                                                         high[i] = high[i-1];
931
932                                                         // Insert blank high score
933                                                         high[scorerank].score = score;
934                                                         high[scorerank].name = "";
935                                                         high[scorerank].allocated = 0;
936                                                 }
937
938                                         break;
939                                         case HIGH_SCORE_DISPLAY:
940                                                 state = TITLE_PAGE;
941                                                 state_timeout = 500.0;
942                                         break;
943                                         case HIGH_SCORE_ENTRY:
944                                                 // state = TITLE_PAGE;
945                                                 // play_tune(1);
946                                                 // state_timeout = 100.0;
947                                         break;
948                                         case TITLE_PAGE:
949                                                 state = HIGH_SCORE_DISPLAY;
950                                                 state_timeout = 200.0;
951                                         break;
952                                 }
953                         } else {
954                                 if(state == DEAD_PAUSE) {
955                                         float blast_radius = BLAST_RADIUS * state_timeout / 20.0;
956                                         if(xship < 60) xship = 60;
957                                         for(i = 0; i<MAXROCKS; i++ ) {
958                                                 float dx, dy, n;
959                                                 if(rock[i].x <= 0) continue;
960                                                 dx = rock[i].x - xship;
961                                                 dy = rock[i].y - yship;
962                                                 n = sqrt(dx*dx + dy*dy);
963                                                 if(n < blast_radius) {
964                                                         n *= 20;
965                                                         rock[i].xvel += rockrate*(dx+30)/n;
966                                                         rock[i].yvel += rockrate*dy/n;
967                                                         rock[i].dead = 1;
968                                                 }
969                                         }
970                                 }
971                         }
972
973                         if(--countdown <= 0 && (rnd()*100.0<(rockrate += 0.025))) {
974                                 // Create a rock
975                                 rockptr++;
976                                 if(rockptr-rock >= MAXROCKS) {
977                                         rockptr = rock;
978                                 }
979                                 if(!rockptr->active) {
980                                         rockptr->x = (float)XSIZE;
981                                         rockptr->xvel = -(rockspeed)*(1 + rnd());
982                                         rockptr->yvel = rnd()-0.5;
983                                         rockptr->type_number = random() % NROCKS;
984                                         rockptr->image = surf_rock[rockptr->type_number];// [random()%NROCKS];
985                                         rockptr->active = 1;
986                                         rockptr->y = rnd()*(YSIZE + rockptr->image->h);
987                                 }
988                                 if(movementrate>0.1) {
989                                         countdown = (int)(ROCKRATE/movementrate);
990                                 } else {
991                                         countdown = 0;
992                                 }
993                         }
994
995                         // FRICTION?
996                         if(friction) {
997                                 xvel *= pow((double)0.9,(double)movementrate);
998                                 yvel *= pow((double)0.9,(double)movementrate);
999                                 // if(abs(xvel)<0.00001) xvel = 0;
1000                                 // if(abs(yvel)<0.00001) yvel = 0;
1001                         }
1002
1003                         // INERTIA
1004                         xship += xvel*movementrate;
1005                         yship += yvel*movementrate;
1006
1007                         // SCROLLING
1008                         yscroll = yship - (YSIZE / 2);
1009                         yscroll += yvel * 25;
1010                         yscroll /= -25;
1011                         yscroll = ((scrollvel * (12 - movementrate)) + (yscroll * movementrate)) / 12;
1012                         scrollvel = yscroll;
1013                         yscroll = yscroll*movementrate;
1014                         yship += yscroll;
1015                         
1016                         // Move all the rocks
1017                         for(i = 0; i < MAXROCKS; i++) {
1018                                 if(rock[i].active) {
1019                                         rock[i].x += rock[i].xvel*movementrate;
1020                                         rock[i].y += rock[i].yvel*movementrate + yscroll;
1021                                         if(rock[i].y > YSIZE || rock[i].y < -rock[i].image->h) {
1022                                                 if(rock[i].dead) {
1023                                                         rock[i].dead = 0;
1024                                                         rock[i].active = 0;
1025                                                 } else {
1026                                                         // wrap
1027                                                         rock[i].y = (YSIZE - rock[i].image->h) - rock[i].y;
1028                                                         rock[i].y += (rock[i].yvel*movementrate + yscroll) * 1.01;
1029                                                 }
1030                                         }
1031                                         if(rock[i].x < -rock[i].image->w || rock[i].x > XSIZE) {
1032                                                 rock[i].active = 0;
1033                                                 rock[i].dead = 0;
1034                                         }
1035                                 }
1036                         }
1037
1038
1039                         // BOUNCE X
1040                         if(xship<0 || xship>XSIZE-surf_ship->w) {
1041                                 // BOUNCE from left and right wall
1042                                 xship -= xvel*movementrate;
1043                                 xvel *= -0.99;
1044                         }
1045
1046                         // BOUNCE Y
1047                         if(yship<0 || yship>YSIZE-surf_ship->h) {
1048                                 // BOUNCE from top and bottom wall
1049                                 yship -= yvel;
1050                                 yvel *= -0.99;
1051                         }
1052
1053
1054                         if(draw() && state == GAMEPLAY) {
1055                                 // Play the explosion sound
1056                                 play_sound(0);
1057                                 makebangdots(xship,yship,xvel,yvel,surf_ship,30);
1058                                 if(--nships <= 0) {
1059                                         gameover = 1;
1060                                         state = GAME_OVER;
1061                                         state_timeout = 200.0;
1062                                         fadetimer = 0.0;
1063                                         faderate = movementrate;
1064                                 }
1065                                 else {
1066                                         state = DEAD_PAUSE;
1067                                         state_timeout = 20.0;
1068                                         xvel = 0;
1069                                         yvel = 0;
1070                                 }
1071                         }
1072
1073                         SDL_PumpEvents();
1074                         keystate = SDL_GetKeyState(NULL);
1075
1076                         if(state != HIGH_SCORE_ENTRY && (keystate[SDLK_q] || keystate[SDLK_ESCAPE])) {
1077                                 return 0;
1078                         }
1079
1080                         if(keystate[SDLK_SPACE] && (state == HIGH_SCORE_DISPLAY || state == TITLE_PAGE || state == DEMO)) {
1081
1082                                 for(i = 0; i<MAXROCKS; i++ ) {
1083                                         rock[i].active = 0;
1084                                         rock[i].dead = 0;
1085                                 }
1086
1087                                 rockrate = 54.0;
1088                                 rockspeed = 5.0;
1089
1090                                 nships = 4;
1091                                 score = 0;
1092
1093                                 state = GAMEPLAY;
1094                                 play_tune(1);
1095
1096                                 xvel = -1;
1097                                 gameover = 0;
1098                                 yvel = 0;
1099                                 xship = 0;
1100                                 yship = YSIZE/2;
1101
1102                         }
1103
1104                         maneuver = 0;
1105                 } else {
1106                         SDL_PumpEvents();
1107                         keystate = SDL_GetKeyState(NULL);
1108                 }
1109
1110                 if(state == GAMEPLAY) {
1111                         if(!gameover) {
1112
1113                                 if(!paused) {
1114                                         if(keystate[SDLK_UP] | keystate[SDLK_c])                { yvel -= 1.5*movementrate; maneuver |= 1<<3;}
1115                                         if(keystate[SDLK_DOWN] | keystate[SDLK_t])              { yvel += 1.5*movementrate; maneuver |= 1<<1;}
1116                                         if(keystate[SDLK_LEFT] | keystate[SDLK_h])              { xvel -= 1.5*movementrate; maneuver |= 1<<2;}
1117                                         if(keystate[SDLK_RIGHT] | keystate[SDLK_n])             { xvel += 1.5*movementrate; maneuver |= 1;}
1118                                         if(keystate[SDLK_3])            { SDL_SaveBMP(surf_screen, "snapshot.bmp"); }
1119                                 }
1120
1121                                 if(keystate[SDLK_p] | keystate[SDLK_s]) {
1122                                         if(!pausedown) {
1123                                                 paused = !paused;
1124                                                 if(paused) {
1125                                                         SDL_Rect src,dest;
1126                                                         src.w = surf_b_variations->w;
1127                                                         src.h = surf_b_variations->h;
1128                                                         dest.w = src.w;
1129                                                         dest.h = src.h;
1130                                                         dest.x = (XSIZE-src.w)/2;
1131                                                         dest.y = (YSIZE-src.h)/2;
1132                                                         SDL_BlitSurface(surf_b_variations,&src,surf_screen,&dest);
1133                                                         // Update the surface
1134                                                         SDL_Flip(surf_screen);
1135                                                 }
1136                                                 pausedown = 1;
1137                                         }
1138                                 } else {
1139                                         pausedown = 0;
1140                                 }
1141
1142                         }
1143                         else {
1144                                 paused = 0;
1145                                 pausedown = 0;
1146                         }
1147                 } else if(state == GAME_OVER) {
1148                         if(keystate[SDLK_SPACE]) {
1149                                 state_timeout = -1;
1150                         }
1151                 }
1152         }
1153 }
1154
1155 int
1156 main(int argc, char **argv) {
1157         int i, x, fullscreen;
1158
1159         fullscreen = 0;
1160         tail_plume = 0;
1161         friction = 0;
1162         sound_flag = 1;
1163         music_flag = 0;
1164
1165         while ((x = getopt(argc,argv,"efhmps")) >= 0) {
1166                 switch(x) {
1167                         case 'e': // engine
1168                                 tail_plume = 1;
1169                         break;
1170                         case 'f': // fullscreen
1171                                 fullscreen = 1;
1172                         break;
1173                         case 'h': // help
1174                                 printf("Variations on RockDodger\n"
1175                                        " -e big tail [E]ngine\n"
1176                                        " -f [F]ull screen\n"
1177                                        " -h this [H]elp message\n"
1178                                        " -m enable [M]usic\n"
1179                                        " -p original [P]hysics (friction)\n"
1180                                        " -s [S]ilent (no sound)\n");
1181                                 exit(0);
1182                         break;
1183                         case 'm': // music
1184                                 music_flag = 1;
1185                         case 'p': // physics
1186                                 friction = 1;
1187                         break;
1188                         case 's': // silent
1189                                 sound_flag = 0;
1190                                 music_flag = 0;
1191                         break;
1192                 }
1193         }
1194
1195         if(init(fullscreen)) {
1196                 printf ("ta: '%s'\n",initerror);
1197                 return 1;
1198         }
1199
1200         for(i = 0; i<MAXROCKS; i++) {
1201                 rock[i].active = 0;
1202                 rock[i].dead = 0;
1203         }
1204         rockrate = 54.0;
1205         rockspeed = 5.0;
1206         initticks = SDL_GetTicks();
1207         gameloop();
1208
1209         return 0;
1210 }