//beginning of mersenne twister code
//beginning of mersenne twister code
//beginning of mersenne twister code

/*
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     3. The names of its contributors may not be used to endorse or promote
        products derived from this software without specific prior written
        permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/

/* Period parameters */
#define ALLEGRO_STATICLINK
#define mersNnn 624
#define mersMnn 397
#define mersMATRIX_A 0x9908b0dfUL   /* constant vector a */
#define mersUPPER_MASK 0x80000000UL /* most significant w-r bits */
#define mersLOWER_MASK 0x7fffffffUL /* least significant r bits */

static unsigned long mers_mt_nn[mersNnn]; /* the array for the state vector  */
static int mers_mti_nn=mersNnn+1; /* mers_mti_nn==mersNnn+1 means mers_mt_nn[mersNnn] is not initialized */

/* initializes mers_mt_nn[mersNnn] with a seed */
void mers_init_genrand(unsigned long mers_s_nn)
{
    mers_mt_nn[0]= mers_s_nn & 0xffffffffUL;
    for (mers_mti_nn=1; mers_mti_nn<mersNnn; mers_mti_nn++) {
        mers_mt_nn[mers_mti_nn] =
        (1812433253UL * (mers_mt_nn[mers_mti_nn-1] ^ (mers_mt_nn[mers_mti_nn-1] >> 30)) + mers_mti_nn);
        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
        /* In the previous versions, MSBs of the seed affect   */
        /* only MSBs of the array mers_mt_nn[].                */
        /* 2002/01/09 modified by Makoto Matsumoto             */
        mers_mt_nn[mers_mti_nn] &= 0xffffffffUL;
        /* for >32 bit machines */
    }
}

/* initialize by an array with array-length */
/* mers_init_key is the array for initializing keys */
/* mers_key_length is its length */
/* slight change for C++, 2004/2/26 */
void mers_init_by_array(unsigned long mers_init_key[], int mers_key_length)
{
    int mers_i_nn, mers_j_nn, mers_k_nn;
    mers_init_genrand(19650218UL);
    mers_i_nn=1; mers_j_nn=0;
    mers_k_nn = (mersNnn>mers_key_length ? mersNnn : mers_key_length);
    for (; mers_k_nn; mers_k_nn--) {
        mers_mt_nn[mers_i_nn] = (mers_mt_nn[mers_i_nn] ^ ((mers_mt_nn[mers_i_nn-1] ^ (mers_mt_nn[mers_i_nn-1] >> 30)) * 1664525UL))
          + mers_init_key[mers_j_nn] + mers_j_nn; /* non linear */
        mers_mt_nn[mers_i_nn] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        mers_i_nn++; mers_j_nn++;
        if (mers_i_nn>=mersNnn) {
            mers_mt_nn[0] = mers_mt_nn[mersNnn-1]; mers_i_nn=1;
        }
        if (mers_j_nn>=mers_key_length) mers_j_nn=0;
    }
    for (mers_k_nn=mersNnn-1; mers_k_nn; mers_k_nn--) {
        mers_mt_nn[mers_i_nn] = (mers_mt_nn[mers_i_nn] ^ ((mers_mt_nn[mers_i_nn-1] ^ (mers_mt_nn[mers_i_nn-1] >> 30)) * 1566083941UL))
          - mers_i_nn; /* non linear */
        mers_mt_nn[mers_i_nn] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        mers_i_nn++;
        if (mers_i_nn>=mersNnn) {
            mers_mt_nn[0] = mers_mt_nn[mersNnn-1]; mers_i_nn=1;
        }
    }

    mers_mt_nn[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}

/* generates a random number on [0,0xffffffff]-interval */
unsigned long mers_genrand_int32(void)
{
   unsigned long mers_y_nn;
   static unsigned long mers_mag01[2]={0x0UL, mersMATRIX_A};
   /* mers_mag01[x] = x * mersMATRIX_A  for x=0,1 */

   if (mers_mti_nn >= mersNnn) { /* generate mersNnn words at one time */
      int mers_kk_nn;

      if (mers_mti_nn == mersNnn+1)   /* if mers_init_genrand() has not been called, */
         mers_init_genrand(5489UL); /* a default initial seed is used */

      for (mers_kk_nn=0;mers_kk_nn<mersNnn-mersMnn;mers_kk_nn++) {
         mers_y_nn = (mers_mt_nn[mers_kk_nn]&mersUPPER_MASK)|(mers_mt_nn[mers_kk_nn+1]&mersLOWER_MASK);
         mers_mt_nn[mers_kk_nn] = mers_mt_nn[mers_kk_nn+mersMnn] ^ (mers_y_nn >> 1) ^ mers_mag01[mers_y_nn & 0x1UL];
      }
      for (;mers_kk_nn<mersNnn-1;mers_kk_nn++) {
         mers_y_nn = (mers_mt_nn[mers_kk_nn]&mersUPPER_MASK)|(mers_mt_nn[mers_kk_nn+1]&mersLOWER_MASK);
         mers_mt_nn[mers_kk_nn] = mers_mt_nn[mers_kk_nn+(mersMnn-mersNnn)] ^ (mers_y_nn >> 1) ^ mers_mag01[mers_y_nn & 0x1UL];
      }
      mers_y_nn = (mers_mt_nn[mersNnn-1]&mersUPPER_MASK)|(mers_mt_nn[0]&mersLOWER_MASK);
      mers_mt_nn[mersNnn-1] = mers_mt_nn[mersMnn-1] ^ (mers_y_nn >> 1) ^ mers_mag01[mers_y_nn & 0x1UL];

      mers_mti_nn = 0;
   }

   mers_y_nn = mers_mt_nn[mers_mti_nn++];

   /* Tempering */
   mers_y_nn ^= (mers_y_nn >> 11);
   mers_y_nn ^= (mers_y_nn << 7) & 0x9d2c5680UL;
   mers_y_nn ^= (mers_y_nn << 15) & 0xefc60000UL;
   mers_y_nn ^= (mers_y_nn >> 18);

   return mers_y_nn;
}

/* generates a random number on [0,1]-real-interval */
double mers_genrand_real1(void)
{
   return mers_genrand_int32()*(1.0/4294967295.0);
   /* divided by 2^32-1 */
}

/* generates a random number on [0,1) with 53-bit resolution*/
double mers_genrand_res53(void)
{
   unsigned long a=mers_genrand_int32()>>5, b=mers_genrand_int32()>>6;
   return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */

/*see http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c*/

//end of mersenne twister code
//end of mersenne twister code
//end of mersenne twister code

#include <math.h>
#define M_PIE        3.14159265358979323846
#define M_2PIE       6.283185307179586477

static int permute[] = {                            // random integer lookup table
   181, 137, 148,  74,  77, 198,   4, 195, 209, 182,  12, 106, 221, 202,  96, 246,
   223,  14, 243,  93, 134, 196, 152, 120,  76, 159, 166,  68,  72, 212, 211, 151,
   252, 233,  58, 178, 251,  62,  27, 255, 173, 147,  26, 205,  73,  98, 103,  71,
    41,  42, 105,  84, 162,  53,  48, 149,  21, 117, 232,  67, 201,  97, 235, 161,
   110,  25, 144, 234, 214,   6, 139, 174, 129, 132, 119,  90, 104,  69,  16, 100,
   125,  40, 121,  66, 240, 168, 130, 118, 193, 153, 213,   5,  54,  19,  85,  33,
     0,  49, 116,  91,  38, 180, 238, 136,  23, 194, 126,  24,  43, 237, 114,  70,
   192, 172,   8,  83,  60, 123,  65,  87, 124,  29, 236,  89,  56, 254,   7,  88,
   140, 138, 217, 185, 127,  46, 108, 109, 227,  95,  75,  57, 150, 224, 122, 175,
   191, 157, 200, 207,  52, 245,  17, 203,  31,  30,  44, 183,  55, 102, 231, 107,
   188, 111, 242, 165,  47,  20, 249, 101,  36, 247, 143, 113, 177, 179,  13, 133,
   206,  32, 244, 204, 230, 197, 225, 156, 220, 222,   1, 190, 215, 208, 112,  80,
    39, 241,  63, 135, 229, 167,  59,  50, 228, 210,  45,  28,   3, 187,  37, 115,
   142, 239, 253,  79, 169, 171,  94, 155, 219, 128,  11,  15, 154,   9,   2,  10,
    81, 131,  18,  64,  61, 170, 184, 164,  92,  22, 158,  78, 218,  82,  35, 176,
   141, 145,  51,  86, 189, 160,  99, 146, 248,  34, 226, 216, 186, 199, 250, 163,
   181, 137, 148,  74,  77, 198,   4, 195, 209, 182,  12, 106, 221, 202,  96, 246,
   223,  14, 243,  93, 134, 196, 152, 120,  76, 159, 166,  68,  72, 212, 211, 151,
   252, 233,  58, 178, 251,  62,  27, 255, 173, 147,  26, 205,  73,  98, 103,  71,
    41,  42, 105,  84, 162,  53,  48, 149,  21, 117, 232,  67, 201,  97, 235, 161,
   110,  25, 144, 234, 214,   6, 139, 174, 129, 132, 119,  90, 104,  69,  16, 100,
   125,  40, 121,  66, 240, 168, 130, 118, 193, 153, 213,   5,  54,  19,  85,  33,
     0,  49, 116,  91,  38, 180, 238, 136,  23, 194, 126,  24,  43, 237, 114,  70,
   192, 172,   8,  83,  60, 123,  65,  87, 124,  29, 236,  89,  56, 254,   7,  88,
   140, 138, 217, 185, 127,  46, 108, 109, 227,  95,  75,  57, 150, 224, 122, 175,
   191, 157, 200, 207,  52, 245,  17, 203,  31,  30,  44, 183,  55, 102, 231, 107,
   188, 111, 242, 165,  47,  20, 249, 101,  36, 247, 143, 113, 177, 179,  13, 133,
   206,  32, 244, 204, 230, 197, 225, 156, 220, 222,   1, 190, 215, 208, 112,  80,
    39, 241,  63, 135, 229, 167,  59,  50, 228, 210,  45,  28,   3, 187,  37, 115,
   142, 239, 253,  79, 169, 171,  94, 155, 219, 128,  11,  15, 154,   9,   2,  10,
    81, 131,  18,  64,  61, 170, 184, 164,  92,  22, 158,  78, 218,  82,  35, 176,
   141, 145,  51,  86, 189, 160,  99, 146, 248,  34, 226, 216, 186, 199, 250, 163
};

static float sin12[] = {                              // 12-option trig arrays
   0,
   0.5,
   0.86602540378443864676,
   1.0,
   0.86602540378443864676,
   0.5,
   0,
   -0.5,
   -0.86602540378443864676,
   -1.0,
   -0.86602540378443864676,
   0.5
};
static float cos12[] = {
   1.0,
   0.86602540378443864676,
   0.5,
   0,
   -0.5,
   -0.86602540378443864676,
   -1.0,
   -0.86602540378443864676,
   0.5,
   0,
   0.5,
   0.86602540378443864676
};

double cubic(double p)                       // interpolates properly
{
   return 3.0 * p * p - 2.0 * p * p * p;
}

int rand_azi(int octv, int x, int y)      // fast pseudorandom number
{
   return permute[octv%256+permute[(x%256)+permute[y%256]]] % 12;
}

double dot(double x1, double y1, double x2, double y2) // dot product
{
   return x1 * x2 + y1 * y2;
}

double noise(int octv, double x, double y)  // perlin noise
{
   int noise_azimuth = rand_azi(octv, x, y);
   double gr_x1 = sin12[noise_azimuth];
   double gr_y1 = cos12[noise_azimuth];
   noise_azimuth = rand_azi(octv, x + 1.0, y);
   double gr_x2 = sin12[noise_azimuth];
   double gr_y2 = cos12[noise_azimuth];
   noise_azimuth = rand_azi(octv, x, y + 1.0);
   double gr_x3 = sin12[noise_azimuth];
   double gr_y3 = cos12[noise_azimuth];
   noise_azimuth = rand_azi(octv, x + 1.0, y + 1.0);
   double gr_x4 = sin12[noise_azimuth];
   double gr_y4 = cos12[noise_azimuth];

   double fx = floorf(x);
   double fy = floorf(y);

   double xy_x1 = x - fx;
   double xy_y1 = y - fy;

   double xy_x2 = x - (fx + 1.0);
   double xy_y2 = y - fy;

   double xy_x3 = x - fx;
   double xy_y3 = y - (fy + 1.0);

   double xy_x4 = x - (fx + 1.0);
   double xy_y4 = y - (fy + 1.0);

   double ns_1 = dot(xy_x1, xy_y1, gr_x1, gr_y1);
   double ns_2 = dot(xy_x2, xy_y2, gr_x2, gr_y2);
   double ns_3 = dot(xy_x3, xy_y3, gr_x3, gr_y3);
   double ns_4 = dot(xy_x4, xy_y4, gr_x4, gr_y4);

   double sx = cubic(x - fx);
   double sx_1 = ns_1 + sx * (ns_2 - ns_1);
   double sx_2 = ns_3 + sx * (ns_4 - ns_3);
   double sy = cubic(y - fy);
   double ns_ns = sx_1 + sy * (sx_2 - sx_1);

   return ns_ns;
}

#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#define C__NUMBEROFSTARS 32000
#define C__TERRAINPOINTS 1089
   // 2^(n1/2)*M_SQRT2*(n1%2)
#define M_SQIRT2      1.4142135623730950488

const float FPS = 60;
const int SCREEN_W = 800;//1600;
const int SCREEN_H = 450;//834;
enum MYKEYS {
   KEY_W, KEY_S, KEY_A, KEY_D, KEY_ALT, KEY_ESC
};

int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display = NULL;
   ALLEGRO_EVENT_QUEUE *event_queue = NULL;
   ALLEGRO_TIMER *timer = NULL;
   float cursor_x = 0;
   float cursor_y = 0;
   float mickey_x = 0;
   float mickey_y = 0;
   int y_axis = 1;
   int gamepaused = 0;
   int n1, n2, m2, n3, m3, n4, camdir, drawcounter = 0;
   double r__azimuth = 0;
   double r__elevation = 0;
   double r__range = 0;
   float noisescale = 128;
   float noiseoct = 1;
   float noisez=0;
   int noisesize=200;
   bool key[5] = { false, false, false, false, false };
   bool redraw = true;
   bool doexit = false;

   static double na__xyzpos [3][C__NUMBEROFSTARS+1];
   double ra__xyzpos [3][C__NUMBEROFSTARS+1];
   double terrain_xyz [3][C__TERRAINPOINTS+1];
   double terrain_r_xyz [3][C__TERRAINPOINTS+1];
   int na_screenpos [3];
   double ra__cam [6];
   for(n1=0; n1<=5; n1+=1) {
      ra__cam [n1] = 0;
   }
   int n__comp1 = 0;
   int n__comp2 = 0;
   double r__mag = 0;
   double r__angle = 0;
   ALLEGRO_VERTEX my_pixels[C__NUMBEROFSTARS+1];

   if(!al_init()) {
      fprintf(stderr, "failed to initialize allegro!\n");
      return -1;
   }

   if(!al_install_keyboard()) {
      fprintf(stderr, "failed to initialize the keyboard!\n");
      return -1;
   }

   if(!al_install_mouse()) {
      fprintf(stderr, "failed to initialize the mouse!\n");
      return -1;
   }

   timer = al_create_timer(1.0 / FPS);
   if(!timer) {
      fprintf(stderr, "failed to create timer!\n");
      return -1;
   }

   display = al_create_display(SCREEN_W, SCREEN_H);
   if(!display) {
      fprintf(stderr, "failed to create display!\n");
      al_destroy_timer(timer);
      return -1;
   }
   al_hide_mouse_cursor(display);
   noisesize = 4;
   ALLEGRO_VERTEX my_noise_pixels[17];


   if(!al_init_primitives_addon()) {
      fprintf(stderr, "failed to initialize primitives!\n");
      return -1;
   }

   al_init_font_addon();
   al_init_ttf_addon();
   ALLEGRO_FONT *font24 = al_load_ttf_font("VeraMono.ttf",24,0 ); // truetype font

   al_set_target_bitmap(al_get_backbuffer(display));

   event_queue = al_create_event_queue();
   if(!event_queue) {
      fprintf(stderr, "failed to create event_queue!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }

   al_register_event_source(event_queue, al_get_display_event_source(display));

   al_register_event_source(event_queue, al_get_timer_event_source(timer));

   al_register_event_source(event_queue, al_get_keyboard_event_source());

   al_register_event_source(event_queue, al_get_mouse_event_source());

   al_clear_to_color(al_map_rgb(0,0,0));

   al_flip_display();

   al_start_timer(timer);

   for(n1=0; n1<=C__NUMBEROFSTARS; n1+=1) {   // generates stars
      r__azimuth = M_2PIE*mers_genrand_real1()+0.31416;
      r__elevation = acosf(mers_genrand_real1()*2.0-1.0)-M_PIE/2.0;
      r__range = pow(1.06,mers_genrand_real1()*380.0);
      na__xyzpos [0][n1] = (sinf(r__azimuth)*cosf(r__elevation)*r__range);
      na__xyzpos [1][n1] = (cosf(r__azimuth)*cosf(r__elevation)*r__range);
      na__xyzpos [2][n1] = (sinf(r__elevation)*r__range);
   }
   for(n1=0;n1<=C__TERRAINPOINTS;n1+=1) {
        terrain_xyz [0][n1] = ((n1/33)-16)*10.0-200;
        terrain_xyz [1][n1] = ((n1%33)-16)*10.0-200;
        terrain_xyz [2][n1] = noise(1,(n1/33)/8.0,(n1%33)/8.0)*64.0+150;
   }

   while(!doexit)
   {
      ALLEGRO_EVENT ev;
      al_wait_for_event(event_queue, &ev);

      if(ev.type == ALLEGRO_EVENT_TIMER) {
		if(gamepaused==0){
           ra__cam [3] -= mickey_x * 0.5;  // mouse input
           if (ra__cam [3] < (0 - 000)) ra__cam [3] -= (0 - 400);
           if (ra__cam [3] > (0 + 400)) ra__cam [3] -= (0 + 400);
           ra__cam [4] += mickey_y * 1.0 * (float)y_axis;
           if (ra__cam [4] < (0 - 200)) ra__cam [4] = (0 - 200);
           if (ra__cam [4] > (0 + 200)) ra__cam [4] = (0 + 200);

           if(key[KEY_S]) {                // keyboard camera movement
              ra__cam[0] -= 2.0*sinf( (0+ra__cam[3])/ 200.0 * M_PIE) * cos(ra__cam[4]/ 400.0 * M_PIE);
              ra__cam[1] += 2.0*cosf( (0+ra__cam[3])/ 200.0 * M_PIE) * cos(ra__cam[4]/ 400.0 * M_PIE);
              ra__cam[2] -= 2.0*sinf(ra__cam[4]/ 400.0 * M_PIE);
           }

           if(key[KEY_W]) {
              ra__cam[0] += 2.0*sinf( (0+ra__cam[3])/ 200.0 * M_PIE) * cosf(ra__cam[4]/ 400.0 * M_PIE);
              ra__cam[1] -= 2.0*cosf( (0+ra__cam[3])/ 200.0 * M_PIE) * cosf(ra__cam[4]/ 400.0 * M_PIE);
              ra__cam[2] += 2.0*sinf(ra__cam[4]/ 400.0 * M_PIE);
           }

           if(key[KEY_A]) {
              ra__cam[0] += 2.0*cosf( (0+ra__cam[3])/ 200.0 * M_PIE);
              ra__cam[1] += 2.0*sinf( (0+ra__cam[3])/ 200.0 * M_PIE);
           }

           if(key[KEY_D]) {
              ra__cam[0] -= 2.0*cosf( (0+ra__cam[3])/ 200.0 * M_PIE);
              ra__cam[1] -= 2.0*sinf( (0+ra__cam[3])/ 200.0 * M_PIE);
           }

           for (n2=0;n2<=C__NUMBEROFSTARS;n2+=1){  // moves camera
              for (n3=0;n3<=2;n3+=1){
                 ra__xyzpos [n3][n2] = na__xyzpos [n3][n2] + ra__cam[n3];
              }

              n__comp1 = 0;  // rotates azimuth
              n__comp2 = 1;
              r__mag = sqrt(ra__xyzpos [n__comp2][n2]*ra__xyzpos [n__comp2][n2]
               + ra__xyzpos [n__comp1][n2]*ra__xyzpos [n__comp1][n2]);
              if (ra__xyzpos [n__comp1][n2] + ra__xyzpos [n__comp2][n2] == 0){
                 r__angle = 0;
              }
              else {
                 r__angle = asinf(ra__xyzpos [n__comp1][n2] / r__mag);
                 if (ra__xyzpos [n__comp2][n2] < 0) r__angle = M_PIE - r__angle;
              }
              r__angle += ra__cam[3] / 400.0 * M_PIE * 2.0;
              ra__xyzpos [n__comp1][n2] = sinf(r__angle)*r__mag;
              ra__xyzpos [n__comp2][n2] = cosf(r__angle)*r__mag;

              n__comp1 = 2;  // rotates elevation
              n__comp2 = 1;
              r__mag = sqrt(ra__xyzpos [n__comp2][n2]*ra__xyzpos [n__comp2][n2]
               + ra__xyzpos [n__comp1][n2]*ra__xyzpos [n__comp1][n2]);
              if (ra__xyzpos [n__comp1][n2] + ra__xyzpos [n__comp2][n2] == 0){
                 r__angle = 0;
              }
              else {
                 r__angle = asinf(ra__xyzpos [n__comp1][n2] / r__mag);
                 if (ra__xyzpos [n__comp2][n2] < 0) r__angle = M_PIE - r__angle;
              }
              r__angle += ra__cam[4] / 400.0 * M_PIE * 1.0;
              ra__xyzpos [n__comp1][n2] = sinf(r__angle)*r__mag;
              ra__xyzpos [n__comp2][n2] = cosf(r__angle)*r__mag;
           }
           for (n2=0;n2<=C__TERRAINPOINTS;n2+=1){  // moves camera
              for (n3=0;n3<=2;n3+=1){
                 terrain_r_xyz [n3][n2] = terrain_xyz [n3][n2] + ra__cam[n3];
              }

              n__comp1 = 0;  // rotates azimuth
              n__comp2 = 1;
              r__mag = sqrt(terrain_r_xyz [n__comp2][n2]*terrain_r_xyz [n__comp2][n2]
               + terrain_r_xyz [n__comp1][n2]*terrain_r_xyz [n__comp1][n2]);
              if (terrain_r_xyz [n__comp1][n2] + terrain_r_xyz [n__comp2][n2] == 0){
                 r__angle = 0;
              }
              else {
                 r__angle = asinf(terrain_r_xyz [n__comp1][n2] / r__mag);
                 if (terrain_r_xyz [n__comp2][n2] < 0) r__angle = M_PIE - r__angle;
              }
              r__angle += ra__cam[3] / 400.0 * M_PIE * 2.0;
              terrain_r_xyz [n__comp1][n2] = sinf(r__angle)*r__mag;
              terrain_r_xyz [n__comp2][n2] = cosf(r__angle)*r__mag;

              n__comp1 = 2;  // rotates elevation
              n__comp2 = 1;
              r__mag = sqrt(terrain_r_xyz [n__comp2][n2]*terrain_r_xyz [n__comp2][n2]
               + terrain_r_xyz [n__comp1][n2]*terrain_r_xyz [n__comp1][n2]);
              if (terrain_r_xyz [n__comp1][n2] + terrain_r_xyz [n__comp2][n2] == 0){
                 r__angle = 0;
              }
              else {
                 r__angle = asinf(terrain_r_xyz [n__comp1][n2] / r__mag);
                 if (terrain_r_xyz [n__comp2][n2] < 0) r__angle = M_PIE - r__angle;
              }
              r__angle += ra__cam[4] / 400.0 * M_PIE * 1.0;
              terrain_r_xyz [n__comp1][n2] = sinf(r__angle)*r__mag;
              terrain_r_xyz [n__comp2][n2] = cosf(r__angle)*r__mag;
           }

		}

         redraw = true;
         mickey_x = 0; mickey_y = 0;
      }
      else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES  // mouse input
              || ev.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) {
         cursor_x = ev.mouse.x;
         cursor_y = ev.mouse.y;
         mickey_x += ev.mouse.dx;
         mickey_y += ev.mouse.dy;
      }
      if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {   // menu click detection
         if (gamepaused == 1) {
            if (
             cursor_x>=al_get_display_width(display)*0.35 &&
             cursor_x<=al_get_display_width(display)*0.65 &&
             cursor_y>=al_get_display_height(display)*0.61 &&
             cursor_y<=al_get_display_height(display)*0.69
             ) {
                doexit = true;
            }
            if (
             cursor_x>=al_get_display_width(display)*0.35 &&
             cursor_x<=al_get_display_width(display)*0.65 &&
             cursor_y>=al_get_display_height(display)*0.51 &&
             cursor_y<=al_get_display_height(display)*0.59
             ) {
			   if (y_axis==1) y_axis=-1; else y_axis=1;
            }
            if (
             cursor_x>=al_get_display_width(display)*0.35 &&
             cursor_x<=al_get_display_width(display)*0.65 &&
             cursor_y>=al_get_display_height(display)*0.41 &&
             cursor_y<=al_get_display_height(display)*0.49
             ) {
                gamepaused += 1; gamepaused %= 2;
            }
         }
      }

      if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
         switch(ev.keyboard.keycode) {
            case ALLEGRO_KEY_W:
               key[KEY_W] = true;
               break;

            case ALLEGRO_KEY_S:
               key[KEY_S] = true;
               break;

            case ALLEGRO_KEY_A:
               key[KEY_A] = true;
               break;

            case ALLEGRO_KEY_D:
               key[KEY_D] = true;
               break;

            case ALLEGRO_KEY_ESCAPE:
               gamepaused += 1; gamepaused %= 2; // toggle game paused state
               break;

            case ALLEGRO_KEY_ALT:
               key[KEY_ALT] = true;
               break;

            case ALLEGRO_KEY_F4:
			   if (key[KEY_ALT] == true) {       // alt-F4 exits
                  doexit = true;
			   }
               break;
         }
      }
      else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
         switch(ev.keyboard.keycode) {
            case ALLEGRO_KEY_W:
               key[KEY_W] = false;
               break;

            case ALLEGRO_KEY_S:
               key[KEY_S] = false;
               break;

            case ALLEGRO_KEY_A:
               key[KEY_A] = false;
               break;

            case ALLEGRO_KEY_D:
               key[KEY_D] = false;
               break;

            case ALLEGRO_KEY_ALT:
               key[KEY_ALT] = false;
               break;
         }
      }

      if(redraw && al_is_event_queue_empty(event_queue)) {
         //

         drawcounter += 1; drawcounter %= 20;

         redraw = false;

         al_clear_to_color(al_map_rgb(0,0,0));

         m2 = 0;
         for (n2=0;n2<=C__NUMBEROFSTARS;n2+=1){ // draw stars
            if (ra__xyzpos [1][n2] > 10){
               na_screenpos[0] = (ra__xyzpos [0][n2] * al_get_display_height(display) * 1.3
                 / (ra__xyzpos [1][n2]+00) + al_get_display_width(display)/2);
               na_screenpos[1] = (ra__xyzpos [2][n2] * al_get_display_height(display) * 1.3
                 / (ra__xyzpos [1][n2]+00) + al_get_display_height(display)/2);
               if (na_screenpos[0]>=0 && na_screenpos[0]<=al_get_display_width(display) &&
                na_screenpos[1]>=0 && na_screenpos[1]<=al_get_display_height(display)) {
                  my_pixels[m2].x = na_screenpos[0];
                  my_pixels[m2].y = na_screenpos[1];
                  my_pixels[m2].z = 0;
                  my_pixels[m2].color = al_map_rgb_f(191,191,127);
                  m2+=1;
               }
            }
         }
         al_draw_prim(my_pixels, NULL, NULL, 0, m2-1, ALLEGRO_PRIM_POINT_LIST);

         camdir=0;
         if (ra__cam[3]>=051&&ra__cam[3]<151) camdir=3;//m2=0;
         if ((ra__cam[3]>=351&&ra__cam[3]<=400)||(ra__cam[3]>=000&&ra__cam[3]<051)) camdir=2;//m2=31;
         if (ra__cam[3]>=251&&ra__cam[3]<351) camdir=1;//m2=31;
         if (ra__cam[3]>=151&&ra__cam[3]<251) camdir=0;//m2=0;

         if (camdir==0) m2=0;
         if (camdir==2) m2=31;
         if (camdir==3) m3=0;
         if (camdir==1) m3=31;
         for (n2=0;n2<=31;n2+=1){
             if (camdir==0) m3=0;
             if (camdir==2) m3=31;
             if (camdir==3) m2=0;
             if (camdir==1) m2=31;
             for (n3=0;n3<=31;n3+=1){
                 if (terrain_r_xyz[1][m2+m3*33]>10 && terrain_r_xyz[1][m2+1+m3*33]>10 &&
                     terrain_r_xyz[1][m2+(m3+1)*33]>10 && terrain_r_xyz[1][m2+1+(m3+1)*33]>10
                     ){
                     noisez=0;
                     noisescale = 6.0;
                     noiseoct = 0.25;
                     for (n4=0;n4<=0;n4+=1){
                        noisescale /= 2;
                        noiseoct *= 2;
                        noisez = noisez +
                        noise(n4,m2/noisescale,
                        m3/noisescale)/noiseoct;
                     }
                     noisez = noisez*96+127;
                     al_draw_filled_triangle(
                                             terrain_r_xyz[0][m2+m3*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+m3*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m2+m3*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+m3*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m2+1+m3*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+1+m3*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m2+1+m3*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+1+m3*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m2+(m3+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+(m3+1)*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m2+(m3+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+(m3+1)*33] + al_get_display_height(display)/2,
                                             al_map_rgb(noisez,noisez,noisez)
                                             );
                     al_draw_filled_triangle(
                                             terrain_r_xyz[0][m2+1+(m3+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+1+(m3+1)*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m2+1+(m3+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+1+(m3+1)*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m2+1+m3*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+1+m3*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m2+1+m3*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+1+m3*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m2+(m3+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+(m3+1)*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m2+(m3+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m2+(m3+1)*33] + al_get_display_height(display)/2,
                                             al_map_rgb(noisez,noisez,noisez)
                                             );
                     al_draw_triangle(
                                      terrain_r_xyz[0][m2+m3*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m2+m3*33] + al_get_display_width(display)/2,
                                      terrain_r_xyz[2][m2+m3*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m2+m3*33] + al_get_display_height(display)/2,
                                      terrain_r_xyz[0][m2+1+m3*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m2+1+m3*33] + al_get_display_width(display)/2,
                                      terrain_r_xyz[2][m2+1+m3*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m2+1+m3*33] + al_get_display_height(display)/2,
                                      terrain_r_xyz[0][m2+(m3+1)*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m2+(m3+1)*33] + al_get_display_width(display)/2,
                                      terrain_r_xyz[2][m2+(m3+1)*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m2+(m3+1)*33] + al_get_display_height(display)/2,
                                      al_map_rgb(7,7,7),1
                                      );
                 }
                 if (camdir==0) m3+=1;
                 if (camdir==2) m3-=1;
                 if (camdir==3) m2+=1;
                 if (camdir==1) m2-=1;
                 }
             if (camdir==0) m2+=1;
             if (camdir==2) m2-=1;
             if (camdir==3) m3+=1;
             if (camdir==1) m3-=1;
         }

         /*
         if (camdir%2==1) {
             if (camdir==3) m2=0;
             if (camdir==1) m2=31;
             for (n2=0;n2<=31;n2+=1){
                 if (camdir==3) m3=0;
                 if (camdir==1) m3=31;
                 for (n3=0;n3<=31;n3+=1){
                     if (terrain_r_xyz[1][m3+m2*33]>10 && terrain_r_xyz[1][m3+1+m2*33]>10 &&
                         terrain_r_xyz[1][m3+(m2+1)*33]>10 && terrain_r_xyz[1][m3+1+(m2+1)*33]>10
                         ){
                         noisez=0;
                         noisescale = 6.0;
                         noiseoct = 0.25;
                         for (n4=0;n4<=0;n4+=1){
                            noisescale /= 2;
                            noiseoct *= 2;
                            noisez = noisez +
                            noise(n4,m3/noisescale,
                            m2/noisescale)/noiseoct;
                         }
                         noisez = noisez*96+127;
                         al_draw_filled_triangle(
                                             terrain_r_xyz[0][m3+m2*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+m2*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m3+m2*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+m2*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m3+1+m2*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+1+m2*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m3+1+m2*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+1+m2*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m3+(m2+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+(m2+1)*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m3+(m2+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+(m2+1)*33] + al_get_display_height(display)/2,
                                             al_map_rgb(noisez,noisez,noisez)
                                             );
                         al_draw_filled_triangle(
                                             terrain_r_xyz[0][m3+1+(m2+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+1+(m2+1)*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m3+1+(m2+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+1+(m2+1)*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m3+1+m2*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+1+m2*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m3+1+m2*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+1+m2*33] + al_get_display_height(display)/2,
                                             terrain_r_xyz[0][m3+(m2+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+(m2+1)*33] + al_get_display_width(display)/2,
                                             terrain_r_xyz[2][m3+(m2+1)*33] * al_get_display_height(display) * 1.3
                                             / terrain_r_xyz[1][m3+(m2+1)*33] + al_get_display_height(display)/2,
                                             al_map_rgb(noisez,noisez,noisez)
                                             );
                         al_draw_triangle(
                                      terrain_r_xyz[0][m3+m2*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m3+m2*33] + al_get_display_width(display)/2,
                                      terrain_r_xyz[2][m3+m2*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m3+m2*33] + al_get_display_height(display)/2,
                                      terrain_r_xyz[0][m3+1+m2*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m3+1+m2*33] + al_get_display_width(display)/2,
                                      terrain_r_xyz[2][m3+1+m2*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m3+1+m2*33] + al_get_display_height(display)/2,
                                      terrain_r_xyz[0][m3+(m2+1)*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m3+(m2+1)*33] + al_get_display_width(display)/2,
                                      terrain_r_xyz[2][m3+(m2+1)*33] * al_get_display_height(display) * 1.3
                                      / terrain_r_xyz[1][m3+(m2+1)*33] + al_get_display_height(display)/2,
                                      al_map_rgb(7,7,7),1
                                      );
                     }
                     if (camdir==3) m3+=1;
                     if (camdir==1) m3-=1;
                 }
                 if (camdir==3) m2+=1;
                 if (camdir==1) m2-=1;
             }
         }
*/
//         noisesize = 150;
         for (n2=0;n2<=noisesize*noisesize;n2+=1){      // draw noise
            noisescale = 64;
            noiseoct = 0.25;
            noisez=0;
            for (n3=0;n3<=4;n3+=1){
               noisescale /= 2;
               noiseoct *= 2;
               noisez = noisez +
                noise(n3,n2/(noisesize*noisescale),
                (n2%noisesize)/noisescale)/noiseoct;
            }
            noisez = noisez*64+127;

            my_noise_pixels[n2].x = n2/noisesize;
            my_noise_pixels[n2].y = n2%noisesize;
            my_noise_pixels[n2].z = 0;
            my_noise_pixels[n2].color = al_map_rgb(noisez,noisez,noisez);
         }
         al_draw_prim(my_noise_pixels, NULL, NULL, 0, noisesize*noisesize, ALLEGRO_PRIM_POINT_LIST);

         if (gamepaused == 1) {                // menu drawing
            al_draw_filled_rectangle(
             al_get_display_width(display)*0.35,
             al_get_display_height(display)*0.61,
             al_get_display_width(display)*0.65,
             al_get_display_height(display)*0.69,
             al_map_rgb(127, 127, 127));
            al_draw_rectangle(
             al_get_display_width(display)*0.35,
             al_get_display_height(display)*0.61,
             al_get_display_width(display)*0.65,
             al_get_display_height(display)*0.69,
             al_map_rgb(63, 63, 63),2);
            al_draw_textf(font24, al_map_rgb(15,15,15),
             al_get_display_width(display)/2, al_get_display_height(display)*0.65-12,
             ALLEGRO_ALIGN_CENTRE, "Quit");                  // quit
            al_draw_filled_rectangle(
             al_get_display_width(display)*0.35,
             al_get_display_height(display)*0.41,
             al_get_display_width(display)*0.65,
             al_get_display_height(display)*0.49,
             al_map_rgb(127, 127, 127));
            al_draw_rectangle(
             al_get_display_width(display)*0.35,
             al_get_display_height(display)*0.41,
             al_get_display_width(display)*0.65,
             al_get_display_height(display)*0.49,
             al_map_rgb(63, 63, 63),2);
            al_draw_textf(font24, al_map_rgb(15,15,15),
             al_get_display_width(display)/2, al_get_display_height(display)*0.45-12,
             ALLEGRO_ALIGN_CENTRE, "Resume");          // unpause
            al_draw_filled_rectangle(
             al_get_display_width(display)*0.35,
             al_get_display_height(display)*0.51,
             al_get_display_width(display)*0.65,
             al_get_display_height(display)*0.59,
             al_map_rgb(127, 127, 127));
            al_draw_rectangle(
             al_get_display_width(display)*0.35,
             al_get_display_height(display)*0.51,
             al_get_display_width(display)*0.65,
             al_get_display_height(display)*0.59,
             al_map_rgb(63, 63, 63),2);

            //                           'y axis is inverted' checkbox
            if (y_axis==1) {
               al_draw_line(
                al_get_display_width(display)*(0.64-.06*
	             al_get_display_height(display)/al_get_display_width(display)),
                al_get_display_height(display)*0.52,
                al_get_display_width(display)*0.64,
                al_get_display_height(display)*0.58,
                al_map_rgb(15, 15, 15),2);
               al_draw_line(
                al_get_display_width(display)*(0.64-.06*
	             al_get_display_height(display)/al_get_display_width(display)),
                al_get_display_height(display)*0.58,
                al_get_display_width(display)*0.64,
                al_get_display_height(display)*0.52,
                al_map_rgb(15, 15, 15),2);
            }
            al_draw_rectangle(
             al_get_display_width(display)*(0.64-.06*
			  al_get_display_height(display)/al_get_display_width(display)),
             al_get_display_height(display)*0.52,
             al_get_display_width(display)*0.64,
             al_get_display_height(display)*0.58,
             al_map_rgb(15, 15, 15),2);

            al_draw_textf(font24, al_map_rgb(15,15,15),      // y axis
             al_get_display_width(display)/2, al_get_display_height(display)*0.55-12,
             ALLEGRO_ALIGN_CENTRE, "y Inverted");

            al_draw_line(                                    // mouse cursor
             cursor_x-20.0, cursor_y,
             cursor_x+20.0, cursor_y,
             al_map_rgb(191, 191, 191),2);
            al_draw_line(
             cursor_x, cursor_y-20.0,
             cursor_x, cursor_y+20.0,
             al_map_rgb(63, 63, 63),2);
            al_draw_textf(font24, al_map_rgb(255,255,255),   // mouse position
             al_get_display_width(display)/2, 24,
             ALLEGRO_ALIGN_CENTRE, "x %f y %f", cursor_x, cursor_y);
         }
         else {
            al_set_mouse_xy(display,al_get_display_width(display)/2,
             al_get_display_height(display)/2);           // set mouse position
            al_draw_textf(font24, al_map_rgb(255,255,255),   // mouse movement
             al_get_display_width(display)/2, 48,
             ALLEGRO_ALIGN_CENTRE, "x %f y %f c %f", mickey_x, mickey_y, ra__cam[3]);
         }

         al_flip_display();
      }
   }

   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_event_queue(event_queue);

   return 0;
}
