Пример #1
0
/* 
 * Search through the file f for the magic string. If found, return
 * the offset stored in the patch area, otherwise abort the program.
 */
long search( FILE * f )
{
   int c, i;

   i = 0;
   while ( ( c = getc( f ) ) > -1 )
   {
      if ( ( unsigned char ) c != jzipmagic[i] )
      {                         
         if ( ( unsigned char ) c == jzipmagic[0] ) 
            i = 1;
         else
            i = 0;
      }
      else if ( ++i == MAGIC_END )
      {
         /* Found magic string. */
         long offset;

         /* Next byte must be zero. */
         if ( getc( f ) != 0 )
         {
            fprintf( stderr, "Error: standalone flag != 0\n" );
            abort_program( 1 );
         }
         offset = getc( f );
         offset += 256L * getc( f );
         offset += 65536L * getc( f );
         return offset;
      }
   }
   fprintf( stderr, "Couldn't find magic string." );
   abort_program( 1 );
}
Пример #2
0
void create_executable( char *story, char *jzip )
{
   FILE *in, *out;
   long p, length, pos;
   char fn[NAME_LENGTH + 4];
   char *ext;
   int ok;

   strcpy( in_name, "" );
   strcpy( out_name, "" );

   if ( strlen( story ) > NAME_LENGTH || strlen( jzip ) > NAME_LENGTH )
   {
      fprintf( stderr, "Filename too long.\n" );
      abort_program( 1 );
   }
   strcpy( fn, story );
   ext = strrchr( fn, '.' );
   if ( ext )
      *ext = '\0';
   strcat( fn, ".exe" );

   printf( "Creating standalone story %s\n", fn );
   out = open_file( fn, FALSE );

   printf( "Copying JZip interpreter (%s).\n", jzip );
   in = open_file( jzip, TRUE );

   copy_and_search( in, out, &length, &pos );
   fclose( in );
   if ( pos == 0 )
   {
      fprintf( stderr, "Error: couldn't find magic string.\n" );
      fprintf( stderr, "Check that you have the right version of JZip.\n" );
      abort_program( 1 );
   }

   printf( "Copying story file %s.\n", story );
   in = open_file( story, TRUE );
   copy( in, out );
   fclose( in );

   printf( "Patching interpreter.\n" );
   patch( out, pos, length );
   fclose( out );

   printf( "Done!\n" );
}
Пример #3
0
void QuadSurfaces::render()
{
  //Update quad index buffer
  clock_t t1,t2;

  //Prepare the Index buffer
  if (!indexvbo)
    glGenBuffers(1, &indexvbo);

  //Always set data size again in case changed
  assert(elements);
  glGenBuffers(1, &indexvbo);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexvbo);
  GL_Error_Check;
  if (glIsBuffer(indexvbo))
  {
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, elements * sizeof(GLuint), NULL, GL_DYNAMIC_DRAW);
    //glBufferData(GL_ELEMENT_ARRAY_BUFFER, elements * sizeof(GLuint), NULL, GL_STATIC_DRAW);
    debug_print("  %d byte IBO created for %d indices\n", elements * sizeof(GLuint), elements);
  }
  else
    abort_program("IBO creation failed!\n");
  GL_Error_Check;

  elements = 0;
  int offset = 0;
  int voffset = 0;
  for (unsigned int index = 0; index < geom.size(); index++)
  {
    t1=clock();

    std::vector<Vec3d> normals(geom[index]->count);
    std::vector<GLuint> indices;

    //Quad indices
    int quads = (geom[index]->width-1) * (geom[index]->height-1);
    indices.resize(quads*4);
    debug_print("%d x %d grid, quads %d, offset %d\n", geom[index]->width, geom[index]->height, quads, elements);
    calcGridNormals(index, normals);
    calcGridIndices(index, indices, voffset);
    //Vertex index offset
    voffset += geom[index]->count;
    //Index offset
    elements += quads*4;
    //Read new data and continue
    //geom[index]->indices.clear();
    geom[index]->normals.clear();
    //geom[index]->indices.read(indices.size(), &indices[0]);
    geom[index]->normals.read(normals.size(), normals[0].ref());

    t1 = clock();
    int bytes = indices.size()*sizeof(GLuint);
    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, bytes, &indices[0]);
    t2 = clock();
    debug_print("  %.4lf seconds to upload %d quad indices (%d - %d)\n", (t2-t1)/(double)CLOCKS_PER_SEC, indices.size(), offset, bytes);
    t1 = clock();
    offset += bytes;
    GL_Error_Check;
  }
}
Пример #4
0
FILE *open_file( char *name, int input )
{
   char *mode;
   FILE *f;

   if ( input )
   {
      strncpy( in_name, name, NAME_LENGTH );
      /* If name is too long, in_name won't be null terminated: fix this,
       * just in case */
      in_name[NAME_LENGTH] = 0;
      mode = READ_MODE;
   }
   else
   {
      strncpy( out_name, name, NAME_LENGTH );
      out_name[NAME_LENGTH] = 0;
      mode = WRITE_MODE;
   }
   f = fopen( name, mode );
   if ( !f )
   {
      fprintf( stderr, "Error opening file %s\n", name );
      abort_program( 1 );
   }
   return f;
}
Пример #5
0
int main(const int argc, const char* argv[])
{
	printf("<< %s >>\n", TITLE);

	//GLU initialize
	{
		initGLUT(argc, argv);
		createGLUTWindow();
	}

	//GLEW initialize
	{
		const GLenum result = initGLEW();
		if (result != GLEW_OK){ abort_program(); return EXIT_FAILURE; }
	}
	{
		printGLEWInfo();
		const bool result = checkGLEWFunctions();
		if (!result){ abort_program(); return EXIT_FAILURE; }
	}

	//Shader initialize
	const GLuint vertex_shader_handle = createAndLoadVertexShaderAll();
	if (!vertex_shader_handle){ abort_program(); return EXIT_FAILURE; }
	const GLuint fragment_shader_handle = createAndLoadFragmentShaderAll();
	if (!fragment_shader_handle){ abort_program(); return EXIT_FAILURE; }
	const GLuint program_handle = createAndLinkShaderProgram(vertex_shader_handle, fragment_shader_handle);
	g_program_handle = program_handle;

	printActiveAttribInfo(program_handle);
	printActiveUniformInfo(program_handle);
	
	//GLM test
	testGLM();

	//Main loop
	setupGLUTFunctions();
	mainloopGLUT();

	return EXIT_SUCCESS;
}
Пример #6
0
void extract_zcode( char *filename )
{
   FILE *in, *out;
   long offset;
   char fn[NAME_LENGTH + 4];
   char *ext;
   int z_version;

   strcpy( in_name, "" );
   strcpy( out_name, "" );

   if ( strlen( filename ) > NAME_LENGTH )
   {
      fprintf( stderr, "Filename too long.\n" );
      abort_program( 1 );
   }

   in = open_file( filename, TRUE );
   offset = search( in );

   fseek( in, offset, SEEK_SET );
   z_version = fgetc( in );
   if ( z_version < 1 || z_version > 8 )
   {
      fprintf( stderr, "Unsupported Z code version: %d\n", z_version );
      abort_program( 1 );
   }
   strcpy( fn, filename );
   ext = strrchr( fn, '.' );
   if ( ext == 0 )
      ext = fn + strlen( fn );
   sprintf( ext, ".z%d", z_version );

   printf( "Extracting Z code to story file %s\n", fn );
   out = open_file( fn, FALSE );

   fputc( z_version, out );
   copy( in, out );
   fclose( in );
   fclose( out );
}
Пример #7
0
// Create a new SDL window
SDLViewer::SDLViewer() : OpenGLViewer(), screen(NULL)
{
  const SDL_VideoInfo *pSDLVideoInfo;
  putenv(strdup("SDL_VIDEO_WINDOW_POS=center"));
  // Initialise SDL Video subsystem
  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) < 0 )
    abort_program("Unable to initialize SDL: %s", SDL_GetError());

  pSDLVideoInfo = SDL_GetVideoInfo();

  if( !pSDLVideoInfo )
  {
    SDL_Quit();
    abort_program("SDL_GetVideoInfo() failed. SDL Error: %s", SDL_GetError());
  }

  timer_id = 0;

  // NOTE: still want Ctrl-C to work, undo the SDL redirections
#ifndef _WIN32
  signal(SIGINT, SIG_DFL);
  signal(SIGQUIT, SIG_DFL);
#endif

  // Keyboard setup
  SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
//#ifndef PDF_CAPTURE
  SDL_EnableUNICODE(1);   //Enable unicode character translation
//Above prevents adobe 3d capture from detecting print screen key?
//#endif

  // Save fullscreen width/height
  savewidth = pSDLVideoInfo->current_w;
  saveheight = pSDLVideoInfo->current_h;

  resized = false;
  screen = NULL;

  debug_print("SDL viewer created\n");
}
Пример #8
0
void SDLViewer::createWindow(int width, int height)
{
  int SDL_Flags;
  if (fullscreen)
    //SDL_Flags = SDL_OPENGL | SDL_FULLSCREEN;
    SDL_Flags = SDL_OPENGL | SDL_NOFRAME;
  else
    SDL_Flags = SDL_OPENGL | SDL_RESIZABLE;

  // set opengl attributes
  SDL_GL_SetAttribute(SDL_GL_RED_SIZE,        8);
  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,      8);
  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,       8);
  SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,      8);
  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,      16);
  SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,    0);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,    1);
  if (stereo) SDL_GL_SetAttribute(SDL_GL_STEREO, 1);
  // Enable 4xsample Antialiasing
  SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

#ifdef _WIN32
  //GL context lost on resize in windows
  if (screen != NULL) close();
#endif

  // Create our rendering surface
  screen = SDL_SetVideoMode( width, height, 32, SDL_Flags);
  if (!screen)
  {
    // Try without stereo
    debug_print("Stereo hardware not available\n");
    SDL_GL_SetAttribute(SDL_GL_STEREO, 0);
    screen = SDL_SetVideoMode( width, height, 32, SDL_Flags );
    if (!screen)
    {
      SDL_Quit();
      abort_program("Call to SDL_SetVideoMode() failed! - SDL_Error: %s", SDL_GetError());
    }
  }
}
Пример #9
0
/*
 * Patch the output file so it will read Z code from the correct position.
 */
void patch( FILE * f, long pos, long value )
{
   int i;

   fflush( f );
   if ( fseek( f, pos, SEEK_SET ) )
   {
      fprintf( stderr, "Seek error on file %s\n", out_name );
      fclose( f );
      abort_program( 1 );
   }
   /* Set STANDALONE_FLAG to FALSE */
   fputc( FALSE, f );
   /* Write the length of the JZip interpreter to the file as a
    * little-endian, 24-bit number. */
   for ( i = 0; i < 3; ++i )
   {
      fputc( ( int ) ( value & 0xff ), f );
      value >>= 8;
   }
}
Пример #10
0
/*
 * Copy the input file to the output file.
 */
void copy( FILE * in, FILE * out )
{
   unsigned bytes_read;
   long total = 0;

   do
   {
      bytes_read = fread( buf, 1, BUFSIZE, in );
      if ( bytes_read > 0 )
         if ( fwrite( buf, 1, bytes_read, out ) != bytes_read )
         {
            fprintf( stderr, "Write error on file %s\n", out_name );
            fclose( in );
            fclose( out );
            abort_program( 1 );
         }
      total += bytes_read;
   }
   while ( bytes_read > 0 );

   if ( total == 0 )
      fprintf( stderr, "Nothing read from file %s - probably an error.\n", in_name );
}
Пример #11
0
/**
 * manages the running of the program, initialises data structures, loads
 * data and handles the processing of options. The bulk of this function
 * should simply be calling other functions to get the job done.
 **/
int main(int argc, char **argv)
{	
	/* Represents the data structures to manage the system */
    struct ppd_system system;
	struct menu_item menu[NUM_MENU_ITEMS];
	char input[NUM_MENU_INPUT], *error;
	int option,	i;
	BOOLEAN exit = FALSE;
	
    /* Validate command line arguments */
	if ( argc != NUM_ARGS)
	{
		printf("Usage: ./playme <stock> <coins>\n\n");
		return EXIT_FAILURE;
	}
	
	else
	{
		if(argv[ITEM_FILE_INDEX] == 0)
		{
			printf("stock_file failed!\n");
			printf("Please make sure to input file name correctly.\n\n");
			return EXIT_FAILURE;
		}
		
		if(argv[COIN_FILE_INDEX] == 0)
		{
			printf("coins_file failed!\n");
			printf("Please make sure to input file name correctly.\n\n");
			return EXIT_FAILURE;
		}
	}
	
    /* Init the system */
	if(system_init(&system) != TRUE)
	{
		printf("System failed to initialise!\n");
		system_free(&system);
		return EXIT_FAILURE;	
	}

    /* Load data */
	if(load_data(&system, argv[COIN_FILE_INDEX], argv[ITEM_FILE_INDEX]) != TRUE)
	{
		printf("Failed to load data!\n");
		system_free(&system);
		return EXIT_FAILURE;
	}

    /* Test if everything has been initialised correctly */
	#if 0
	if(!display_items(&system) || !display_coins(&system))
		abort_program(&system);
	#endif
	
    /* Initialise the menu system */
	init_menu(menu);
	
	while(!exit)
	{
		/* Loop, asking for options from the menu */
		for(i = 0; i < NUM_MENU_ITEMS; i++)
		{
			if(i == SELECT_DEFAULT)
				printf("\n\n== Default Selections ==\n========================\n");
		
			else if(i == SELECT_ADMIN)
				printf("\n== Admin Selections ==\n========================\n");
		
			printf("%d. %s\n", i + 1, menu[i].name);
		}
		
		while(!exit) {
			printf("\nPlease select what you would like to do: ");
			
			/* Get user input and assign to variable */
			i = get_user_input(input, NUM_MENU_INPUT);
			
			/* Check for return to menu */
			if(i == RTM)
			{
				printf("You have no where to return to!\n");
				continue;
			}
			
			/* Check for invalid input */
			if(i == FAILURE)
			{
				printf("Your text was too long!\n");
				continue;
			}
			
			/* Convert given input to int and assign to option */
			option = (int) strtol(input, &error, 0) - 1;
			
			/* Check if converted string inside menu range */
			if(option >= 0 && option <= NUM_MENU_ITEMS)
				exit = TRUE;
			
			/* For all other values, echo output outside of range */
			else
				printf("Input outside of range!\n");
		}
		
		/* Reset exit BOOLEAN for part 2 */
		exit = FALSE;
		
		/* Run each option selected */
		if(menu[option].function(&system) != TRUE)
			printf("Option '%s' failed to complete!\n", menu[option].name);
	}
    return EXIT_SUCCESS;
}
Пример #12
0
/*
 * Copy the file in to the file out. Set length to the length in bytes
 * of the input file, and set magic_pos to the offset of the first
 * occurrence of MAGIC_STRING. 
 */
void copy_and_search( FILE * in, FILE * out, long *length, long *magic_pos )
{
   int c, magic_idx;            
   size_t buf_idx, buf_end;     
   long pos;

   pos = 0;
   buf_idx = buf_end = 0;
   magic_idx = 0;
   *magic_pos = 0;

   for ( ;; )
   {                            
      if ( buf_idx >= buf_end )
      {
         /* Reached end of input buffer; read in a new chunk */
         buf_end = fread( buf, 1, BUFSIZE, in );
         if ( buf_end < 1 )
         {
            /* Reached end of input file. 
             * pos is now the number of bytes read. */
            *length = pos;
            return;
         }
         if ( fwrite( buf, 1, buf_end, out ) != buf_end )
         {
            fprintf( stderr, "Write error on file %s\n", out_name );
            fclose( in );
            fclose( out );
            abort_program( 1 );
         }
         buf_idx = 0;
      }

      c = buf[buf_idx++];       /* Get current character */
      ++pos;                    /* Offset of next byte */

      /* The following search algorithm utilizes the fact that the
       * first character of the magic string is unique. */
      if ( ( unsigned char ) c != jzipmagic[magic_idx] ) 
         if ( ( unsigned char ) c == jzipmagic[0] ) 
            magic_idx = 1;
         else
            magic_idx = 0;
      else if ( ++magic_idx == MAGIC_END )
      {
         /* Matched the entire magic string */
         if ( *magic_pos > 0 )
         {
            /* If this condition occurs, the magic string isn't unique,
             * with potentially bad consequences. Re-compile with a
             * different magic string. */
            fprintf( stderr, "Found more than one instance of the magic string.\n" );
            fclose( in );
            fclose( out );
            abort_program( 1 );
         }
         *magic_pos = pos;
      }
   }
}
Пример #13
0
void Lines::update()
{
  //Skip update if count hasn't changed
  //To force update, set geometry->reload = true
  if (reload) elements = 0;
  if (elements > 0 && (linetotal == (unsigned int)elements || total == 0)) return;

  tris->clear();
  tris->setView(view);

  //Count 2d lines
  linetotal = 0;
  for (unsigned int i=0; i<geom.size(); i++)
  { //Force true as default here, global default is false for "flat"
    if (all2d || (geom[i]->draw->properties.getBool("flat", true) && !geom[i]->draw->properties["tubes"]))
      linetotal += geom[i]->count;
  }

  //Copy data to Vertex Buffer Object
  // VBO - copy normals/colours/positions to buffer object
  unsigned char *p, *ptr;
  ptr = p = NULL;
  int datasize = sizeof(float) * 3 + sizeof(Colour);   //Vertex(3), and 32-bit colour
  int bsize = linetotal * datasize;
  if (linetotal > 0)
  {
    //Initialise vertex buffer
    if (!vbo) glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    if (glIsBuffer(vbo))
    {
      glBufferData(GL_ARRAY_BUFFER, bsize, NULL, GL_STATIC_DRAW);
      debug_print("  %d byte VBO created for LINES, holds %d vertices\n", bsize, bsize/datasize);
      ptr = p = (unsigned char*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
      GL_Error_Check;
    }
    if (!p) abort_program("VBO setup failed");
  }

  clock_t t1,t2,tt;
  tt=clock();
  counts.clear();
  counts.resize(geom.size());
  any3d = false;
  for (unsigned int i=0; i<geom.size(); i++)
  {
    t1=tt=clock();
    Properties& props = geom[i]->draw->properties;

    //Calibrate colour maps on range for this object
    geom[i]->colourCalibrate();
    float limit = props["limit"];
    bool linked = props["link"];

    if (all2d || (props.getBool("flat", true) && !props["tubes"]))
    {
      int hasColours = geom[i]->colourCount();
      int colrange = hasColours ? geom[i]->count / hasColours : 1;
      if (colrange < 1) colrange = 1;
      debug_print("Using 1 colour per %d vertices (%d : %d)\n", colrange, geom[i]->count, hasColours);

      Colour colour;
      for (unsigned int v=0; v < geom[i]->count; v++)
      {
        if (!internal && geom[i]->filter(i)) continue;

        //Check length limit if applied (used for periodic boundary conditions)
        //NOTE: will not work with linked lines, require separated segments
        if (!linked && v%2 == 0 && v < geom[i]->count-1 && limit > 0.f)
        {
          Vec3d line;
          vectorSubtract(line, geom[i]->vertices[v+1], geom[i]->vertices[v]);
          if (line.magnitude() > limit) 
          {
            //Skip next two vertices
            v++;
            continue;
          }
        }

        //Have colour values but not enough for per-vertex, spread over range (eg: per segment)
        int cidx = v / colrange;
        if (cidx >= hasColours) cidx = hasColours - 1;
        geom[i]->getColour(colour, cidx);
        //if (cidx%100 ==0) printf("COLOUR %d => %d,%d,%d\n", cidx, colour.r, colour.g, colour.b);
        //Write vertex data to vbo
        assert((int)(ptr-p) < bsize);
        //Copies vertex bytes
        memcpy(ptr, &geom[i]->vertices[v][0], sizeof(float) * 3);
        ptr += sizeof(float) * 3;
        //Copies colour bytes
        memcpy(ptr, &colour, sizeof(Colour));
        ptr += sizeof(Colour);

        //Count of vertices actually plotted
        counts[i]++;
      }
      t2 = clock();
      debug_print("  %.4lf seconds to reload %d vertices\n", (t2-t1)/(double)CLOCKS_PER_SEC, counts[i]);
      t1 = clock();
      elements += counts[i];
    }
    else
    {
      any3d = true; //Flag 3d tubes drawn

      //Create a new data store for output geometry
      tris->add(geom[i]->draw);

      //3d lines - using triangle sub-renderer
      geom[i]->draw->properties.data["lit"] = true; //Override lit
      //Draw as 3d cylinder sections
      int quality = 4 * (int)props["glyphs"];
      float scaling = props["scalelines"];
      //Don't apply object scaling to internal lines objects
      if (!internal) scaling *= (float)props["scaling"];
      float radius = scaling*0.1;
      float* oldpos = NULL;
      Colour colour;
      for (unsigned int v=0; v < geom[i]->count; v++)
      {
        if (v%2 == 0 && !linked) oldpos = NULL;
        float* pos = geom[i]->vertices[v];
        if (oldpos)
        {
          tris->drawTrajectory(geom[i]->draw, oldpos, pos, radius, radius, -1, view->scale, limit, quality);
          //Per line colours (can do this as long as sub-renderer always outputs same tri count)
          geom[i]->getColour(colour, v);
          tris->read(geom[i]->draw, 1, lucRGBAData, &colour.value);
        }
        oldpos = pos;
      }

      //Adjust bounding box
      tris->compareMinMax(geom[i]->min, geom[i]->max);
    }
  }

  if (linetotal > 0)
  {
    glUnmapBuffer(GL_ARRAY_BUFFER);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
  }
  GL_Error_Check;

  t1 = clock();
  debug_print("Plotted %d lines in %.4lf seconds\n", linetotal, (t1-tt)/(double)CLOCKS_PER_SEC);

  tris->update();
}