summaryrefslogtreecommitdiffstats
path: root/nyan.c
blob: 5613f6dcbef9f3034af6f54fa38dd832d9d10786 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/* ============================================================================================ */
/* This software is created by LAMMJohnson and comes with no warranty of any kind.              */
/*                                                                                              */
/* If you like this software and would like to contribute to its continued improvement          */
/* then please feel free to submit bug reports here: www.github.com/LAMMJohnson                 */
/*                                                                                              */
/* This program is licensed under the GPLv3 and in support of Free and Open Source              */
/* Software in general. The full license can be found at http://www.gnu.org/licenses/gpl.html   */
/* ============================================================================================ */
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_mixer.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef XINERAMA
#include <X11/Xlib.h>
#include <X11/extensions/Xinerama.h>
#endif /* XINERAMA */
#include "list.h" /* Linked list implementation */

#define BUF_SZ  1024

/* Type definitions */
typedef struct {
    int x, y;
} coords;

typedef struct cat_instance cat_instance;
struct cat_instance {
    coords loc;
    struct list_head list;
};

typedef struct sparkle_instance sparkle_instance;
struct sparkle_instance {
    unsigned int frame, speed;
    int frame_mov;
    unsigned int layer;
    coords loc;
    struct list_head list;
};

/* Predecs */
static void add_sparkle(void);
static void add_cat(unsigned int x, unsigned int y);
static void cleanup(void);
static void clear_screen(void);
static void draw_cats(unsigned int frame);
static void draw_sparkles(void);
static void* ec_malloc(unsigned int size);
static void errout(char *str);
static void fillsquare(SDL_Surface* surf, int x, int y, int w, int h, Uint32 col);
static void handle_args(int argc, char** argv);
static void handle_input(void);
static void init(void);
static void load_images(void);
static SDL_Surface* load_image(const char* path);
static void load_resource_data(void);
static void load_music(void);
static void putpix(SDL_Surface* surf, int x, int y, Uint32 col);
static void restart_music(void);
static void run(void);
static void stretch_images(void);
static void update_sparkles(void);
static void usage(char* exname);
#ifdef XINERAMA
static void xinerama_add_cats(void);
#endif /* XINERAMA */

/* Globals */
static unsigned int                 FRAMERATE = 14;
static unsigned int                 SCREEN_BPP = 32;
static unsigned int                 SCREEN_WIDTH = 800;
static unsigned int                 SCREEN_HEIGHT = 600;
static SDL_Surface*                 screen = NULL;
static SDL_Event                    event;
static int                          running = 1;
static int                          SURF_TYPE = SDL_HWSURFACE;
static int                          sound = 1;
static int                          sound_volume = 128;
static int                          fullscreen = 1;
static int                          catsize = 0;
static int                          cursor = 0;
#ifdef XINERAMA
static Display*                     dpy;
#endif /* XINERAMA */
static int                          curr_frame = 0;
static int                          sparkle_spawn_counter = 0;
static Mix_Music*                   music;
static SDL_Surface**                cat_img;
static SDL_Surface**                sparkle_img;
static SDL_Surface**                stretch_cat;
static SDL_Surface**                image_set;
static Uint32                       bgcolor;
static char*                        RESOURCE_PATH = NULL;
static char*                        LOC_BASE_PATH = "res";
static char*                        OS_BASE_PATH = "/usr/share/nyancat";
static int                          ANIM_FRAMES_FG = 0;
static int                          ANIM_FRAMES_BG = 0;
static LIST_HEAD(sparkle_list);
static LIST_HEAD(cat_list);

/* Function definitions */
static void
add_sparkle(void) {
    sparkle_instance* new;

    new = ec_malloc(sizeof(sparkle_instance));
    new->loc.x = screen->w + 80;
    new->loc.y = (rand() % (screen->h + sparkle_img[0]->h)) - sparkle_img[0]->h;
    new->frame = 0;
    new->frame_mov = 1;
    new->speed = 10 + (rand() % 30);
    new->layer = rand() % 2;
    list_add(&new->list, &sparkle_list);
}

static void
add_cat(unsigned int x, unsigned int y) {
    cat_instance* new;

    new = ec_malloc(sizeof(cat_instance));
    new->loc.x = x;
    new->loc.y = y;
    list_add(&new->list, &cat_list);
}

static void
cleanup(void) {
    Mix_HaltMusic();
    Mix_FreeMusic(music);
    Mix_CloseAudio();
    SDL_Quit();
}

static void
clear_screen(void) {
    sparkle_instance *s;
    cat_instance *c;

    list_for_each_entry(c, &cat_list, list) {
        /* This is bad. These magic numbers are to make up for uneven image sizes */
        fillsquare(screen,
                   c->loc.x,
                   c->loc.y - (curr_frame < 2 ? 0 : 5),
                   image_set[curr_frame]->w + 6,
                   image_set[curr_frame]->h + 5,
                   bgcolor);
    }

    list_for_each_entry(s, &sparkle_list, list) {
        fillsquare(screen,
                   s->loc.x,
                   s->loc.y,
                   sparkle_img[s->frame]->w,
                   sparkle_img[s->frame]->h,
                   bgcolor);
    }

}

static void
draw_cats(unsigned int frame) {
    cat_instance* c;
    SDL_Rect pos;

    list_for_each_entry(c, &cat_list, list) {
        pos.x = c->loc.x;
        pos.y = c->loc.y;

        if(frame < 2)
            pos.y -= 5;
        SDL_BlitSurface( image_set[frame], NULL, screen, &pos );
    }
}

static void
draw_sparkles() {
    sparkle_instance* s;
    SDL_Rect pos;

    list_for_each_entry(s, &sparkle_list, list) {
        pos.x = s->loc.x;
        pos.y = s->loc.y;
        SDL_BlitSurface( sparkle_img[s->frame], NULL, screen, &pos );
    }
}

static void*
ec_malloc(unsigned int size) {
    void *ptr;
    ptr = malloc(size);
    if (!ptr)
        errout("In ec_malloc -- unable to allocate memory.");
    return ptr;
}

static void
errout (char *str) {
    if (str)
        puts(str);
    exit(-1);
}

static void
fillsquare(SDL_Surface* surf, int x, int y, int w, int h, Uint32 col) {
    int i, e;

    if (x + w < 0 || y + h < 0 || x > surf->w || y > surf->h)
        return;

    /* Sanitising of inputs. Make sure we're not drawing off of the surface */
    if (x + w > surf->w)
        w = surf->w - x;
    if (y + h > surf->h)
        h = surf->h - y;
    if (x < 0) {
        w += x;
        x = 0;
    }
    if (y < 0) {
        h += y;
        y = 0;
    }

    for (i = x; i < x + w; i++)
        for (e = y; e < y + h; e++)
            putpix(surf, i, e, col);
}

static void
handle_args(int argc, char **argv) {
    int i;

    /* This REALLY needs to be replaced with getopt */

    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-hw"))
            SURF_TYPE = SDL_HWSURFACE;
        else if (!strcmp(argv[i], "-sw"))
            SURF_TYPE = SDL_SWSURFACE;
        else if (!strcmp(argv[i], "-f") || !strcmp(argv[i], "--fullscreen"))
            fullscreen = 1;
        else if(!(strcmp(argv[i], "-nf") || !strcmp(argv[i], "--nofullscreen")))
            fullscreen = 0;
        else if(!strcmp(argv[i], "-nc") || !strcmp(argv[i], "--nocursor"))
            cursor = 0;
        else if(!strcmp(argv[i], "-sc") || !strcmp(argv[i], "--cursor") || !strcmp(argv[i], "--showcursor"))
            cursor = 1;
        else if(!strcmp(argv[i], "-ns") || !strcmp(argv[i], "--nosound"))
            sound = 0;
        else if((!strcmp(argv[i], "-v") || !strcmp(argv[i], "--volume")) && i < argc - 1) {
            int vol = atoi(argv[++i]);
            if(vol >= 0 && vol <= 128){
                sound_volume = vol;
            }
            else {
                puts("Arguments for Volume are not valid. Disabling sound.");
                sound = 0;
            }
        }
        else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) 
            usage(argv[0]);
        else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--catsize")) {
            if (++i < argc) {
                if(!strcmp(argv[i], "full"))
                    catsize = 1;
                else if(!strcmp(argv[i], "small"))
                    catsize = 0;
                else
                    printf("Unrecognised scaling option: %s - please select either 'full' or 'small' cat size.\n", argv[i]);
            }
        }
        else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--data-set")) {
            if (++i < argc) {
                if (RESOURCE_PATH)
                    free(RESOURCE_PATH);
                RESOURCE_PATH = strdup(argv[i]);
            }
        }
        else if((!strcmp(argv[i], "-r") && strcmp(argv[i], "--resolution")) && i < argc - 2) {
            int dims[2] = { atoi(argv[++i]), atoi(argv[++i]) };
            if (dims[0] >= 0 && dims[0] < 10000 && dims[1] >= 0 && dims[1] < 5000) {           // Borrowed from PixelUnsticker, changed the variable name
                SCREEN_WIDTH = dims[0];
                SCREEN_HEIGHT = dims[1];
            }
            else
                puts("Arguments do not appear to be valid screen sizes. Defaulting.");
        }
        else
            printf("Unrecognised option: %s\n", argv[i]);
    }

    if (!RESOURCE_PATH)
        RESOURCE_PATH = "default";
}

static void
handle_input(void) {
    while( SDL_PollEvent( &event ) ) {
        switch (event.type) {
            case SDL_KEYDOWN:
            case SDL_QUIT:
            case SDL_MOUSEMOTION:
                running = 0;
                break;
        }
    }
}

static void
init(void) {
    int i;

    srand( time(NULL) );

    SDL_Init( SDL_INIT_EVERYTHING );
    if (fullscreen)
        screen = SDL_SetVideoMode( 0, 0, SCREEN_BPP, SURF_TYPE | SDL_FULLSCREEN );
    else
        screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SURF_TYPE );
    if(!cursor)
        SDL_ShowCursor(0);

    load_resource_data();
    load_images();
    bgcolor = SDL_MapRGB(screen->format, 0x00, 0x33, 0x66);
    fillsquare(screen, 0, 0, screen->w, screen->h, bgcolor);

    if(sound) {
        Mix_OpenAudio( 44100, AUDIO_S16, 2, 256 );
        load_music();
        Mix_PlayMusic(music, 0);
        Mix_VolumeMusic(sound_volume);
    }

    /* Choose our image set */
    if (catsize == 1)
        image_set = stretch_cat;
    else
        image_set = cat_img;

/* Ugly */
#ifdef XINERAMA
    if (!(dpy = XOpenDisplay(NULL)))
        puts("Failed to open Xinerama display information.");
    else{
        if(catsize == 1)
            stretch_images();
        xinerama_add_cats();
        XCloseDisplay(dpy);
    }
#else
    if(catsize == 1)
        add_cat(0, (screen->h - image_set[0]->h) / 2);
    else {
        add_cat((screen->w - cat_img[0]->w) / 2, (screen->h - cat_img[0]->h) / 2);
    }
#endif /* Xinerama */

    /* clear initial input */
    while( SDL_PollEvent( &event ) ) {}

    /* Pre-populate with sparkles */
    for (i = 0; i < 200; i++)
        update_sparkles();
}

static void
load_images(void) {
    int i;
    char buffer[BUF_SZ];

    cat_img = ec_malloc(sizeof(SDL_Surface*) * ANIM_FRAMES_FG);
    sparkle_img = ec_malloc(sizeof(SDL_Surface*) * ANIM_FRAMES_BG);

    /* Loading logic */
    for (i = 0; i < ANIM_FRAMES_FG; ++i) {
        snprintf(buffer, BUF_SZ, "%s/%s/fg%02d.png", LOC_BASE_PATH, RESOURCE_PATH, i);
        cat_img[i] = load_image(buffer);
        if (!cat_img[i]) {
            snprintf(buffer, BUF_SZ, "%s/%s/fg%02d.png", OS_BASE_PATH, RESOURCE_PATH, i);
            cat_img[i] = load_image(buffer);
        }
    }
    for (i = 0; i < ANIM_FRAMES_BG; ++i) {
        snprintf(buffer, BUF_SZ, "%s/%s/bg%02d.png", LOC_BASE_PATH, RESOURCE_PATH, i);
        sparkle_img[i] = load_image(buffer);
        if (!sparkle_img[i]) {
            snprintf(buffer, BUF_SZ, "%s/%s/bg%02d.png", OS_BASE_PATH, RESOURCE_PATH, i);
            sparkle_img[i] = load_image(buffer);
        }
    }

    /* Check everything loaded properly */
    for (int i = 0; i < ANIM_FRAMES_FG; ++i)
        if (!cat_img[i])
            errout("Error loading foreground images.");

    for (int i = 0; i < ANIM_FRAMES_BG; ++i)
        if (!sparkle_img[i])
            errout("Error loading background images.");
}

static SDL_Surface*
load_image( const char* path ) {
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* optimizedImage = NULL;

    loadedImage = IMG_Load( path );
    if(loadedImage) {
        optimizedImage = SDL_DisplayFormatAlpha( loadedImage );
        SDL_FreeSurface( loadedImage );
    }
    return optimizedImage;
}

static void
load_music(void) {
    char buffer[BUF_SZ];

    snprintf(buffer, BUF_SZ, "%s/%s/music.ogg", LOC_BASE_PATH, RESOURCE_PATH);
    music = Mix_LoadMUS(buffer);
    if (!music) {
        snprintf(buffer, BUF_SZ, "%s/%s/music.ogg", OS_BASE_PATH, RESOURCE_PATH);
        music = Mix_LoadMUS(buffer);
    }
    if (!music)
        printf("Unable to load Ogg file: %s\n", Mix_GetError());
    else
        Mix_HookMusicFinished(restart_music);
}

static void
load_resource_data(void) {
    FILE *f;
    char buffer[BUF_SZ];

    snprintf(buffer, BUF_SZ, "%s/%s/data", LOC_BASE_PATH, RESOURCE_PATH);
    f = fopen(buffer, "r");
    if (!f) {
        snprintf(buffer, BUF_SZ, "%s/%s/data", OS_BASE_PATH, RESOURCE_PATH);
        f = fopen(buffer, "r");
    }
    if (!f)
        errout("Error opening resource data file");

    fgets(buffer, BUF_SZ, f);
    ANIM_FRAMES_FG = atoi(buffer);
    fgets(buffer, BUF_SZ, f);
    ANIM_FRAMES_BG = atoi(buffer);

    if (!ANIM_FRAMES_FG || !ANIM_FRAMES_BG)
        errout("Error reading resource data file.");
}

static void
putpix(SDL_Surface* surf, int x, int y, Uint32 col) {
    Uint32 *pix = (Uint32 *) surf->pixels;
    pix [ ( y * surf->w ) + x ] = col;
}

static void
restart_music(void) {
    Mix_PlayMusic(music, 0);
}

static void
run(void) {
    unsigned int last_draw, draw_time;

    while( running ) {
        last_draw = SDL_GetTicks();

        clear_screen();
        update_sparkles();
        draw_sparkles();
        draw_cats(curr_frame);

        handle_input();
        SDL_Flip(screen);

        /* Frame increment and looping */
        curr_frame++;
        if (curr_frame >= ANIM_FRAMES_FG)
            curr_frame = 0;

        draw_time = SDL_GetTicks() - last_draw;
        if (draw_time < (1000 / FRAMERATE))
            SDL_Delay((1000 / FRAMERATE) - draw_time);
    }
}

static void
stretch_images(void) {
    SDL_Rect stretchto;
    stretchto.w = 0;
    stretchto.h = 0;

    /*  Just use the x co-ordinate for scaling for now. This does, however,
        need to be changed to accomodate taller resolutions */
#ifdef XINERAMA
    int i, nn;
    XineramaScreenInfo* info = XineramaQueryScreens(dpy, &nn);

    for (i = 0; i < nn; ++i) {
        if(!stretchto.w || info[i].width < stretchto.w)
            stretchto.w = info[i].width;
    }

    XFree(info);
#endif /* XINERAMA */
    if (!stretchto.w)
        stretchto.w = screen->w;

    /* Handle a slight scaling down */
    stretchto.w *= 0.9;
    stretchto.h = stretchto.w * cat_img[0]->h / cat_img[0]->w;

    SDL_PixelFormat fmt = *(cat_img[0]->format);
    for (int i=0; i <= ANIM_FRAMES_FG; i++) {
        stretch_cat[i] = SDL_CreateRGBSurface(SURF_TYPE, stretchto.w,
            stretchto.h,SCREEN_BPP,fmt.Rmask,fmt.Gmask,fmt.Bmask,fmt.Amask);
        SDL_SoftStretch(cat_img[i],NULL,stretch_cat[i],NULL);
    }

}

static void
update_sparkles(void) {
    sparkle_instance *s;
    sparkle_instance *tmp;

    sparkle_spawn_counter += rand() % screen->h;
    while(sparkle_spawn_counter >= 1000) {
        add_sparkle();
        sparkle_spawn_counter -= 1000;
    }

    list_for_each_entry_safe(s, tmp, &sparkle_list, list) {
        s->loc.x -= s->speed;
        s->frame += s->frame_mov;

        if(s->frame + 1 >= ANIM_FRAMES_BG || s->frame < 1)
            s->frame_mov = 0 - s->frame_mov;

        if (s->loc.x < 0 - sparkle_img[0]->w) {
            list_del(&s->list);
            free(s);
        }
    }
}

static void
usage(char* exname) {
    printf("Usage: %s [OPTIONS]\n\
    -h,  --help                    This help message\n\
    -f,  --fullscreen              Enable fullscreen mode (default)\n\
    -nf, --nofullscreen            Disable fullscreen mode\n\
    -c,  --catsize                 Choose size of cat, options are full and \n\
                                   small. Small is default. \"Full\" not\n\
                                   officially supported.\n\
    -nc, --nocursor                Don't show the cursor (default)\n\
    -sc, --cursor, --showcursor    Show the cursor\n\
    -ns, --nosound                 Don't play sound\n\
    -v,  --volume                  Set Volume, if enabled, from 0 - 128\n\
    -r,  --resolution              Make next two arguments the screen \n\
                                   resolution to use (0 and 0 for full \n\
                                   resolution) (800x600 default)\n\
    -d, --data-set                 Use an alternate data set. Packaged with\n\
                                   this program by default are \"default\"\n\
                                   and \"freedom\" sets.\n\
    -hw, -sw                       Use hardware or software SDL rendering, \n\
                                   respectively. Hardware is default\n", exname);
    exit(0);
}

#ifdef XINERAMA
static void
xinerama_add_cats(void) {
    int i, nn;
    XineramaScreenInfo* info = XineramaQueryScreens(dpy, &nn);

    for (i = 0; i < nn; ++i)
        if(fullscreen)
            add_cat(info[i].x_org + ((info[i].width - image_set[0]->w) / 2),
                info[i].y_org + ((info[i].height - image_set[0]->h) / 2));
        else
            add_cat((SCREEN_WIDTH - image_set[0]->w) / 2, 
                (SCREEN_HEIGHT - image_set[0]->h) / 2);

    XFree(info);
}
#endif /* XINERAMA */

int main( int argc, char **argv ) {
    handle_args(argc, argv);
    init();
    run();
    cleanup();
    return 0;
}