示例#1
0
void Display::init(Game* iGame)
{
  mGame = iGame;

  // Text colors
  // Black
  mColorText = makecol(0,0,0);
  mStatusText = G_TEXT_STATUS_START;

  // Set color depth
  int tmpCd = desktop_color_depth();
  if (tmpCd < 15) tmpCd = 32;
  set_color_depth(tmpCd);

  // Display
  set_window_title(G_TITLE);
  set_gfx_mode(GFX_AUTODETECT_WINDOWED, G_SCREEN_WIDTH, G_SCREEN_HEIGHT,0,0);
  // De-activate normal mouse, it will be displayed manually
  show_mouse(NULL);

  // Create buffer for double buffering display update
  mBuffer = create_bitmap(G_SCREEN_WIDTH, G_SCREEN_HEIGHT);  

  // Load bitmaps
  BITMAP* tmpBmp = NULL;
  Sprite* tmpSprite = NULL;
  // Background
  tmpBmp = load_bitmap(G_IMG_BACKGROUND, NULL);
  tmpSprite = new Sprite();
  tmpSprite->setBitmap(tmpBmp, 0, 0, tmpBmp->w, tmpBmp->h);
  mSprites.push_back(tmpSprite);

  // -------------------------------------------------
  // BUTTONS
  // -------------------------------------------------
	BITMAP* tmpOnBmp = NULL;
  BITMAP* tmpOffBmp = NULL;
  ls_button* tmpButton = NULL;
  ls_square* tmpButtonSquare = NULL;
  ls_wall* tmpButtonWall = NULL;

  // SQUARE BUTTONS
	tmpOnBmp = load_bitmap(G_IMG_SQ_ON, NULL);
  tmpOffBmp = load_bitmap(G_IMG_SQ_OFF, NULL);
  int tmpBorderAdjustX = (G_SCREEN_WIDTH - (G_SQUARE_SIZE * G_SQUARE_COUNT_COLUMNS) - (G_WALL_SIZE * (G_SQUARE_COUNT_COLUMNS - 1)))/2;
  int tmpBorderAdjustY = G_BASE_Y_ADJUST + (G_SCREEN_HEIGHT - (G_SQUARE_SIZE * G_SQUARE_COUNT_ROWS) - (G_WALL_SIZE * (G_SQUARE_COUNT_ROWS - 1)))/2;
  for (int i = 0; i < G_SQUARE_COUNT_ROWS; i++) {
    for (int j = 0; j < G_SQUARE_COUNT_COLUMNS; j++) {
      tmpButtonSquare = new ls_square();
      createButton(tmpButtonSquare, tmpOnBmp, tmpOffBmp, tmpBorderAdjustX + j*(G_SQUARE_SIZE+G_WALL_SIZE), tmpBorderAdjustY + i*(G_SQUARE_SIZE+G_WALL_SIZE));
      mSquareButtons.push_back(tmpButtonSquare);
    }
  }
  destroy_bitmap(tmpOnBmp);
  destroy_bitmap(tmpOffBmp);

  // WALL BUTTONS
  // Vertical (Walls separating an UP and DOWN square)
  tmpOnBmp = load_bitmap(G_IMG_WALL_V_ON, NULL);
  tmpOffBmp = load_bitmap(G_IMG_WALL_V_OFF, NULL);  
  for (int i = 0; i < G_SQUARE_COUNT_ROWS; i++) {
    for (int j = 0; j < G_SQUARE_COUNT_COLUMNS-1; j++) {
      tmpButtonWall = new ls_wall();
      createButton(tmpButtonWall, tmpOnBmp, tmpOffBmp, tmpBorderAdjustX + j*(G_SQUARE_SIZE+G_WALL_SIZE) + G_SQUARE_SIZE, tmpBorderAdjustY + i*(G_SQUARE_SIZE+G_WALL_SIZE));
      mWallHoriButtons.push_back(tmpButtonWall);
      
    }
  }
  destroy_bitmap(tmpOnBmp);
  destroy_bitmap(tmpOffBmp);
  // Horizontal (Walls separating a LEFT and RIGHT square)
  tmpOnBmp = load_bitmap(G_IMG_WALL_H_ON, NULL);
  tmpOffBmp = load_bitmap(G_IMG_WALL_H_OFF, NULL);  
  for (int i = 0; i < G_SQUARE_COUNT_ROWS-1; i++) {
    for (int j = 0; j < G_SQUARE_COUNT_COLUMNS; j++) {
      tmpButtonWall = new ls_wall();
      createButton(tmpButtonWall, tmpOnBmp, tmpOffBmp, tmpBorderAdjustX + j*(G_SQUARE_SIZE+G_WALL_SIZE), tmpBorderAdjustY + i*(G_SQUARE_SIZE+G_WALL_SIZE) + G_SQUARE_SIZE);
      mWallVertButtons.push_back(tmpButtonWall);
    }
  }
  destroy_bitmap(tmpOnBmp);
  destroy_bitmap(tmpOffBmp);

  // NORMAL BUTTONS
  // Solve
	tmpOnBmp = load_bitmap(G_IMG_SOLVE_ON, NULL);
  tmpOffBmp = load_bitmap(G_IMG_SOLVE_OFF, NULL);
  tmpButton = new ls_button();
  createButton(tmpButton, tmpOnBmp, tmpOffBmp, G_SOLVE_BTN_X, G_SOLVE_BTN_Y);
  tmpButton->set_tag(eSOLVE_BTN);
  mButtons.push_back(tmpButton);
  destroy_bitmap(tmpOnBmp);
  destroy_bitmap(tmpOffBmp);
  // Solve Complete
	tmpOnBmp = load_bitmap(G_IMG_SOLVE_C_ON, NULL);
  tmpOffBmp = load_bitmap(G_IMG_SOLVE_C_OFF, NULL);
  tmpButton = new ls_button();
  createButton(tmpButton, tmpOnBmp, tmpOffBmp, G_SOLVE_C_BTN_X, G_SOLVE_C_BTN_Y);
  tmpButton->set_tag(eSOLVE_C_BTN);
  mButtons.push_back(tmpButton);
  destroy_bitmap(tmpOnBmp);
  destroy_bitmap(tmpOffBmp);
  // Clear
	tmpOnBmp = load_bitmap(G_IMG_CLEAR_ON, NULL);
  tmpOffBmp = load_bitmap(G_IMG_CLEAR_OFF, NULL);
  tmpButton = new ls_button();
  createButton(tmpButton, tmpOnBmp, tmpOffBmp, G_CLEAR_BTN_X, G_CLEAR_BTN_Y);
  tmpButton->set_tag(eCLEAR_BTN);
  mButtons.push_back(tmpButton);
  destroy_bitmap(tmpOnBmp);
  destroy_bitmap(tmpOffBmp);

}
示例#2
0
static void
comparestat_set_title(compstat_t *cs)
{
	set_window_title(cs->win, "Compare two capture files");
}
示例#3
0
static void
smbstat_set_title(smbstat_t *ss)
{
	set_window_title(ss->win, "SMB Service Response Time statistics");
}
示例#4
0
static void
gtpstat_set_title(gtpstat_t *gtp)
{
	set_window_title(gtp->win, "GTP Control Plane  Response Time statistics");
}
示例#5
0
GtkWidget *
create_editor_window(const char *tag)
{
    GtkWidget *window;
    GtkWidget *vbox;
    GtkWidget *hbox;
    GtkWidget *label;
    GtkWidget *combo;
    GtkWidget *separator;
    GtkWidget *frame;
    GtkWidget *table;
    GtkWidget *scale;

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    set_window_title(window, tag, "Patch Edit");
    g_signal_connect (G_OBJECT(window), "destroy",
                      G_CALLBACK (gtk_main_quit), NULL);
    g_signal_connect (G_OBJECT (window), "delete-event",
                      G_CALLBACK (on_delete_event_wrapper),
                      (gpointer)gtk_widget_hide);

    vbox = gtk_vbox_new(FALSE, 0);
    gtk_container_add (GTK_CONTAINER (window), vbox);
    gtk_container_set_border_width (GTK_CONTAINER (vbox), 6);

    editor_status_label = gtk_label_new (" ");
    gtk_container_add (GTK_CONTAINER (vbox), editor_status_label);
    gtk_misc_set_alignment (GTK_MISC (editor_status_label), 0, 0.5);

    hbox = gtk_hbox_new (FALSE, 0);
    gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
    gtk_container_set_border_width (GTK_CONTAINER (hbox), 0);

    label = gtk_label_new ("Patch Name");
    gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 2);
    gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);

    editor_name_entry = gtk_entry_new_with_max_length(10);
    gtk_box_pack_start (GTK_BOX (hbox), editor_name_entry, FALSE, FALSE, 2);
    g_signal_connect(G_OBJECT(editor_name_entry), "changed",
                     G_CALLBACK(patch_edit_on_name_entry_changed), NULL);

    /* -FIX- comment (reuse Performance Name?)
     * GtkWidget *comment_label = gtk_label_new ("Comment");
     * gtk_box_pack_start (GTK_BOX (hbox), comment_label, FALSE, FALSE, 2);
     * gtk_misc_set_alignment (GTK_MISC (comment_label), 0, 0.5);

     * GtkWidget *comment_entry = gtk_entry_new_with_max_length(60);
     * gtk_box_pack_start (GTK_BOX (hbox), comment_entry, TRUE, TRUE, 2);
     */

    /* separator */
    separator = gtk_hseparator_new ();
    gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 2);

    gtk_widget_show_all(vbox);

    /* editor widgets */
    create_widgy_editor(tag);
    gtk_box_pack_start (GTK_BOX (vbox), widgy_widget, TRUE, FALSE, 2);
    gtk_widget_show(widgy_widget);

    create_retro_editor(tag);
    gtk_box_pack_start (GTK_BOX (vbox), retro_widget, TRUE, FALSE, 2);

    /* separator */
    separator = gtk_hseparator_new ();
    gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 2);
    gtk_widget_show(separator);

    /* edit action widgets */
    hbox = gtk_hbox_new (FALSE, 0);
    gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
    gtk_container_set_border_width (GTK_CONTAINER (hbox), 0);

    label = gtk_label_new ("Editor Mode");
    gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 2);

    combo = gtk_combo_box_new_text();
    gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Widgy");
    gtk_combo_box_append_text(GTK_COMBO_BOX(combo), "Retro");
    gtk_combo_box_set_active(GTK_COMBO_BOX(combo), 0);
    gtk_box_pack_start (GTK_BOX (hbox), combo, FALSE, FALSE, 2);
    g_signal_connect(G_OBJECT(combo), "changed",
                     G_CALLBACK(patch_edit_on_mode_change), NULL);

    /* -FIX- add: [compare to original?] [swap A/B?] [close?] */

    label = gtk_label_new (NULL);
    gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, FALSE, 0);

    editor_discard_button = gtk_button_new_with_label ("Discard Changes");
    gtk_box_pack_start (GTK_BOX (hbox), editor_discard_button, FALSE, FALSE, 2);
    gtk_signal_connect (GTK_OBJECT (editor_discard_button), "clicked",
                        GTK_SIGNAL_FUNC (on_editor_discard_button_press),
                        NULL);

    editor_save_button = gtk_button_new_with_label ("Save Changes into Patch Bank");
    gtk_box_pack_start (GTK_BOX (hbox), editor_save_button, FALSE, FALSE, 2);
    gtk_signal_connect (GTK_OBJECT (editor_save_button), "clicked",
                        GTK_SIGNAL_FUNC (on_editor_save_button_press),
                        NULL);

    gtk_widget_show_all(hbox);

    /* test note widgets */
    frame = gtk_frame_new ("Test Note");
    gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);

    table = gtk_table_new (3, 3, FALSE);
    gtk_container_add (GTK_CONTAINER (frame), table);
    gtk_container_set_border_width (GTK_CONTAINER (table), 2);
    gtk_table_set_row_spacings (GTK_TABLE (table), 1);
    gtk_table_set_col_spacings (GTK_TABLE (table), 5);

    label = gtk_label_new ("key");
    gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1,
                      (GtkAttachOptions) (GTK_FILL),
                      (GtkAttachOptions) (0), 0, 0);
    gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);

    scale = gtk_hscale_new (GTK_ADJUSTMENT (test_note_key_adj));
    gtk_table_attach (GTK_TABLE (table), scale, 1, 2, 0, 1,
                      (GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
                      (GtkAttachOptions) (0), 0, 0);
    gtk_scale_set_value_pos (GTK_SCALE (scale), GTK_POS_RIGHT);
    gtk_scale_set_digits (GTK_SCALE (scale), 0);
    gtk_range_set_update_policy (GTK_RANGE (scale), GTK_UPDATE_DELAYED);

    label = gtk_label_new ("velocity");
    gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2,
                      (GtkAttachOptions) (GTK_FILL),
                      (GtkAttachOptions) (0), 0, 0);
    gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);

    scale = gtk_hscale_new (GTK_ADJUSTMENT (test_note_velocity_adj));
    gtk_table_attach (GTK_TABLE (table), scale, 1, 2, 1, 2,
                      (GtkAttachOptions) (GTK_FILL),
                      (GtkAttachOptions) (0), 0, 0);
    gtk_scale_set_value_pos (GTK_SCALE (scale), GTK_POS_RIGHT);
    gtk_scale_set_digits (GTK_SCALE (scale), 0);
    gtk_range_set_update_policy (GTK_RANGE (scale), GTK_UPDATE_DELAYED);

    editor_test_note_button = gtk_button_new_with_label (" Send Test Note");
    gtk_table_attach (GTK_TABLE (table), editor_test_note_button, 2, 3, 0, 2,
                      (GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
                      (GtkAttachOptions) (0), 4, 0);
    gtk_button_set_focus_on_click(GTK_BUTTON(editor_test_note_button), FALSE);
    g_signal_connect (G_OBJECT (editor_test_note_button), "pressed",
                      G_CALLBACK (on_test_note_button_press), (gpointer)1);
    g_signal_connect (G_OBJECT (editor_test_note_button), "released",
                      G_CALLBACK (on_test_note_button_press), (gpointer)0);

    gtk_widget_show_all (frame);

    editor_window = window;

    return editor_window;
}
示例#6
0
INT_PTR CALLBACK
AudioDlgProc (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg) {
      case WM_COMMAND:
        switch (LOWORD(wParam)) {
          case IDC_AUDIO_TEST:
              test_sound();
              break;
          case IDC_AUDIOOUT_DEVICE:
              if(HIWORD(wParam) == CBN_SELCHANGE){
                  set_reg_device(hDlg, IDC_AUDIOOUT_DEVICE, reg_out_nameW);
                  SendMessageW(GetParent(hDlg), PSM_CHANGED, 0, 0);
              }
              break;
          case IDC_VOICEOUT_DEVICE:
              if(HIWORD(wParam) == CBN_SELCHANGE){
                  set_reg_device(hDlg, IDC_VOICEOUT_DEVICE, reg_vout_nameW);
                  SendMessageW(GetParent(hDlg), PSM_CHANGED, 0, 0);
              }
              break;
          case IDC_AUDIOIN_DEVICE:
              if(HIWORD(wParam) == CBN_SELCHANGE){
                  set_reg_device(hDlg, IDC_AUDIOIN_DEVICE, reg_in_nameW);
                  SendMessageW(GetParent(hDlg), PSM_CHANGED, 0, 0);
              }
              break;
          case IDC_VOICEIN_DEVICE:
              if(HIWORD(wParam) == CBN_SELCHANGE){
                  set_reg_device(hDlg, IDC_VOICEIN_DEVICE, reg_vin_nameW);
                  SendMessageW(GetParent(hDlg), PSM_CHANGED, 0, 0);
              }
              break;
          case IDC_SPEAKERCONFIG_DEVICE:
              if(HIWORD(wParam) == CBN_SELCHANGE){
                  UINT idx;

                  idx = SendDlgItemMessageW(hDlg, IDC_SPEAKERCONFIG_DEVICE, CB_GETCURSEL, 0, 0);

                  if(idx < num_render_devs){
                      SendDlgItemMessageW(hDlg, IDC_SPEAKERCONFIG_SPEAKERS, CB_SETCURSEL, render_devs[idx].speaker_config, 0);
                  }
              }
              break;
          case IDC_SPEAKERCONFIG_SPEAKERS:
              if(HIWORD(wParam) == CBN_SELCHANGE){
                  UINT dev, idx;

                  idx = SendDlgItemMessageW(hDlg, IDC_SPEAKERCONFIG_SPEAKERS, CB_GETCURSEL, 0, 0);
                  dev = SendDlgItemMessageW(hDlg, IDC_SPEAKERCONFIG_DEVICE, CB_GETCURSEL, 0, 0);

                  if(dev < num_render_devs){
                      render_devs[dev].speaker_config = idx;
                      SendMessageW(GetParent(hDlg), PSM_CHANGED, 0, 0);
                  }
              }
              break;
        }
        break;

      case WM_SHOWWINDOW:
        set_window_title(hDlg);
        break;

      case WM_NOTIFY:
        switch(((LPNMHDR)lParam)->code) {
            case PSN_KILLACTIVE:
              SetWindowLongPtrW(hDlg, DWLP_MSGRESULT, FALSE);
              break;
            case PSN_APPLY:
              apply_speaker_configs();
              apply();
              SetWindowLongPtrW(hDlg, DWLP_MSGRESULT, PSNRET_NOERROR);
              break;
            case PSN_SETACTIVE:
              break;
        }
        break;
      case WM_INITDIALOG:
        initAudioDlg(hDlg);
        break;
  }

  return FALSE;
}
示例#7
0
/***
  Function : install()
  Returns  : TRUE on succes, FALSE on failure
  Purpose  : Will install game variables, sets up the entire game.
***/
bool install()
{
    // Each time we run the game, we clear out the logbook
    FILE *fp;
    fp = fopen("log.txt", "wt");

    if (fp)
    {
        fprintf(fp, "Counter-Strike 2D Logbook\n");
        fprintf(fp, "-------------------------\n\n"); // print head of logbook
        fclose(fp);
    }

    logbook("--------------");
    logbook("Initialization");
    logbook("--------------");

    // init game
    map.init();
    game.init();
    steam.init();

    logbook("Creating entity types.");
    game.install_entities();

    // Logbook notification
    logbook("\n-------");
    logbook("Allegro");
    logbook("-------");


    // ALLEGRO - INIT
    if (allegro_init() != 0)
        return false;

    logbook(allegro_id);
    yield_timeslice();
    logbook("yield_timeslice()");

    int r = install_timer();
    if (r > -1) logbook("install_timer()");
    else
    {
        logbook("FAILED");
        return false;
    }

    alfont_init();
    logbook("alfont_init()");
    install_keyboard();
    logbook("install_keyboard()");
    install_mouse();
    logbook("install_mouse()");

    logbook("setting up timer functions / locking functions & memory");
    /* set up the interrupt routines... */
    LOCK_VARIABLE(RUNNING_TIMER_tenth);
    LOCK_VARIABLE(RUNNING_TIMER_fps);
    LOCK_FUNCTION(timer_tenth);
    LOCK_FUNCTION(fps_proc);

    install_int(timer_tenth, 10);
    install_int(fps_proc, 1000);

    logbook("Timers installed");

    frame_count = fps = 0;


    // set window title
    char title[80];
    sprintf(title, "Counter-Strike 2D");

    // Set window title
    set_window_title(title);
    char window_title[256];
    sprintf(window_title, "Window title set: [%s]", title);
    logbook(window_title);

    set_color_depth(16);      // run in 16 bit mode
    if (game.windowed)
    {
        int r = set_gfx_mode(GFX_AUTODETECT_WINDOWED, game.screen_x, game.screen_y, game.screen_x, game.screen_y);
        if (r > -1)
        {
            // Succes
        }
        else
        {
            // GFX_DIRECTX_ACCEL / GFX_AUTODETECT
            r = set_gfx_mode(GFX_DIRECTX_ACCEL, game.screen_x, game.screen_y, game.screen_x, game.screen_y);
            if (r > -1)
            {
                game.windowed = false;
                logbook("Could not enter windowed-mode; settings.d3 adjusted");
            }
            else
            {
                logbook("ERROR - !");
                return false;
            }
        }
    }
    else
    {
        int r = set_gfx_mode(GFX_AUTODETECT, game.screen_x, game.screen_y, game.screen_x, game.screen_y);

        // succes
        if (r > -1)
        {

        }
        else
        {
            logbook("ERROR - !!");
            return false;
        }

    }


    text_mode(0);

    logbook("Loading font data");
    // loading font

    game_font = alfont_load_font("gfx\\font\\tahoma.ttf");

    if (game_font != NULL)
    {
        alfont_set_font_size(game_font, 20); // set size
    }
    else
        allegro_message("Error loading tahoma.ttf!");

    // CS Font
    cs_font = alfont_load_font("gfx\\font\\cs.ttf");

    if (cs_font != NULL)
    {
        alfont_set_font_size(cs_font, 20); // set size
    }
    else
        allegro_message("Error loading cs.ttf");

    alfont_text_mode(-1);

    if (set_display_switch_mode(SWITCH_BACKGROUND) < 0)
    {
        set_display_switch_mode(SWITCH_PAUSE);
        logbook("Display 'switch and pause' mode set");
    }
    else
        logbook("Display 'switch to background' mode set");

    // sound
    logbook("Initializing sound");
    int s = install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL);

    /***
     Bitmap Creation
     ***/

    bmp_screen = create_bitmap(game.screen_x, game.screen_y);

    if (bmp_screen == NULL)
    {
        logbook("ERROR: Could not create bitmap: bmp_screen");
        return false;
    }
    else
        logbook("Bitmap created: bmp_screen");

    bmp_collide = create_bitmap(game.screen_x, game.screen_y);

    if (bmp_collide == NULL)
    {
        logbook("ERROR: Could not create bitmap: bmp_collide");
        return false;
    }
    else
        logbook("Bitmap created: bmp_collide");

    /*** End of Bitmap Creation ***/

    // load datafiles
    graphics = load_datafile("graphics.dat");
    if (graphics == NULL)
    {
        logbook("ERROR: Could not load datafile: graphics.dat");
        return false;
    }
    else
        logbook("Datafile loaded: graphics.dat");

    // Shadows
    shadows = load_datafile("shadows.dat");
    if (shadows == NULL)
    {
        logbook("ERROR: Could not load datafile: shadows.dat");
        return false;
    }
    else
        logbook("Datafile loaded: shadows.dat");

    // HUD
    hud = load_datafile("hud.dat");
    if (hud == NULL)
    {
        logbook("ERROR: Could not load datafile: hud.dat");
        return false;
    }
    else
        logbook("Datafile loaded: hud.dat");

    //set_color_conversion(COLORCONV_NONE);
    set_color_conversion(COLORCONV_MOST);
    logbook("Color conversion method set");

    // setup mouse speed
    set_mouse_speed(2,2);

    logbook("Mouse speed set");

    logbook("");
    logbook("----");
    logbook("GAME ");
    logbook("----");

    game.LOAD_TexturesFromDataFile("data//de_aztec.dat");
//  DATA_Init();

    // randomize timer
    srand( (unsigned)time( NULL ) );

    //srand(time(NULL));

    // normal sounds are loud, the music is lower (its background music, so it should not be disturbing)
    set_volume(255, 200);

    set_trans_blender(128, 128, 128, 128);

    logbook("");
    logbook("--------------");
    logbook("BATTLE CONTROL");
    logbook("--------------");
    logbook("\n3...2...1... GO!\n");
    return true;
}
示例#8
0
int eof_add_silence_recode_mp3(char * oggfn, unsigned long ms)
{
	char sys_command[1024] = {0};
	char backupfn[1024] = {0};
	char wavfn[1024] = {0};
	char soggfn[1024] = {0};
	char mp3fn[1024] = {0};
	SAMPLE * decoded = NULL;
	SAMPLE * combined = NULL;
	int bits;
	int stereo;
	int freq;
	unsigned long samples;
	int channels;
	unsigned long ctr,index;

 	eof_log("eof_add_silence_recode_mp3() entered", 1);

	if(!oggfn || (ms == 0) || eof_silence_loaded)
	{
		return 21;	//Return error:  Invalid parameters
	}
	set_window_title("Adjusting Silence...");

	/* back up original file */
	(void) snprintf(backupfn, sizeof(backupfn) - 1, "%s.backup", oggfn);
	if(!exists(backupfn))
	{
		(void) eof_copy_file(oggfn, backupfn);
	}

	/* decode MP3 */
	(void) replace_filename(wavfn, eof_song_path, "decode.wav", 1024);
	(void) replace_filename(mp3fn, eof_song_path, "original.mp3", 1024);
	(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "lame --decode \"%s\" \"%s\"", mp3fn, wavfn);
	(void) eof_system(sys_command);

	/* insert silence */
	decoded = load_sample(wavfn);
	if(!decoded)
	{
		allegro_message("Error opening file.\nMake sure there are no Unicode or extended ASCII characters in this chart's file path.");
		return 22;	//Return failure:  Could not load decoded MP3 file
	}
	bits = decoded->bits;
	stereo = decoded->stereo;
	freq = decoded->freq;
	samples = (decoded->freq * ms) / 1000;	//Calculate this manually instead of using msec_to_samples() because that function assumes the sample rate matches the current chart audio, and this may not be the case with the original MP3 file the user provided
	channels = stereo ? 2 : 1;
	combined = create_sample(bits,stereo,freq,samples+decoded->len);	//Create a sample array long enough for the silence and the OGG file
	if(combined == NULL)
	{
		destroy_sample(decoded);
		return 23;	//Return failure:  Could not create a sample array for the combined audio
	}
	/* Add the PCM data for the silence */
	if(bits == 8)
	{	//Create 8 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = 0x80;
		}
	}
	else
	{	//Create 16 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = 0x8000;
		}
	}
	/* Add the decoded OGG PCM data*/
	if(bits == 8)
	{	//Copy 8 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = ((unsigned char *)(decoded->data))[ctr];
		}
	}
	else
	{	//Copy 16 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = ((unsigned short *)(decoded->data))[ctr];
		}
	}

	/* save combined WAV */
	(void) replace_filename(wavfn, eof_song_path, "encode.wav", 1024);
	if(!save_wav(wavfn, combined))
	{
		destroy_sample(decoded);	//This is no longer needed
		destroy_sample(combined);	//This is no longer needed
		return 24;	//Return failure:  Could not create the combined audio WAV file
	}

	/* destroy samples */
	destroy_sample(decoded);	//This is no longer needed
	destroy_sample(combined);	//This is no longer needed

	/* encode the audio */
	printf("%s\n%s\n", eof_song_path, wavfn);
	(void) replace_filename(soggfn, eof_song_path, "encode.ogg", 1024);
	#ifdef ALLEGRO_WINDOWS
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -b %d \"%s\"", soggfn, alogg_get_bitrate_ogg(eof_music_track) / 1000, wavfn);
	#else
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -b %d \"%s\"", soggfn, alogg_get_bitrate_ogg(eof_music_track) / 1000, wavfn);
	#endif

	(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
	eof_log(eof_log_string, 1);
	if(eof_system(sys_command))
	{	//If oggenc failed, retry again by specifying a quality level (specifying bitrate can fail in some circumstances)
		eof_log("\t\toggenc failed.  Retrying by specifying a quality level instead of a target bitrate", 1);
		#ifdef ALLEGRO_WINDOWS
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#else
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#endif
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
		eof_log(eof_log_string, 1);
		if(eof_system(sys_command))
		{	//If oggenc failed again
			char tempfname[30] = {0};
			char redirect[35] = {0};

			if(eof_validate_temp_folder())
			{	//Ensure the correct working directory and presence of the temporary folder
				eof_log("\tCould not validate working directory and temp folder", 1);
				return 25;	//Return failure:  Could not validate cwd and temp folder
			}

			(void) snprintf(tempfname, sizeof(tempfname) - 1, "%soggenc.log", eof_temp_path_s);
			(void) snprintf(redirect, sizeof(redirect) - 1, " 2> %s", tempfname);
			(void) ustrzcat(sys_command, (int) sizeof(sys_command) - 1, redirect);	//Append a redirection to the command to capture the output of oggenc
			if(eof_system(sys_command))
			{	//Run one last time to catch the error output
				(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tOggenc failed.  Please see %s for any errors it gave.", tempfname);
				eof_log(eof_log_string, 1);
				eof_fix_window_title();
				return 26;	//Return failure:  Could not encode combined audio
			}
		}
	}

	/* replace the current OGG file with the new file */
	(void) eof_copy_file(soggfn, oggfn);	//Copy encode.ogg to the filename of the original OGG

	/* clean up */
	(void) replace_filename(wavfn, eof_song_path, "decode.wav", 1024);
	(void) delete_file(wavfn);		//Delete decode.wav
	(void) replace_filename(wavfn, eof_song_path, "encode.wav", 1024);
	(void) delete_file(wavfn);		//Delete encode.wav
	(void) delete_file(soggfn);	//Delete encode.ogg
	if(eof_load_ogg(oggfn, 0))
	{	//If the combined audio was loaded
		eof_fix_waveform_graph();
		eof_fix_spectrogram();
		eof_fix_window_title();
		eof_chart_length = eof_music_length;
		return 0;	//Return success
	}
	eof_fix_window_title();

	return 27;	//Return error:  Could not load new audio
}
示例#9
0
void Alleg4Display::setTitleBar(const std::string& title)
{
  set_window_title(title.c_str());
}
示例#10
0
int eof_add_silence(char * oggfn, unsigned long ms)
{
	char sys_command[1024] = {0};
	char backupfn[1024] = {0};	//The file path of the backup of the target audio file
	char wavfn[1024] = {0};		//The file path of the silent WAV file created
	char soggfn[1024] = {0};	//The file path of the silent OGG file created
	char oggcfn[1024] = {0};	//The file path to the oggCat utility
	char old_wd[1024] = {0};	//Store working directory before changing it so we can get back
	char *rel_oggfn;			//Relative file path to the target audio file
	char *rel_backupfn;			//Relative file path to the backup of the target audio file
	SAMPLE * silence_sample;
	int retval;

	if(!oggfn || (ms == 0) || eof_silence_loaded)
	{
		return 1;	//Return error:  Invalid parameters
	}

 	eof_log("eof_add_silence() entered", 1);

	set_window_title("Adjusting Silence...");

	/* back up original file */
	(void) snprintf(backupfn, sizeof(backupfn) - 1, "%s.backup", oggfn);
	if(!exists(backupfn))
	{
		(void) eof_copy_file(oggfn, backupfn);
	}
	(void) delete_file(oggfn);

	silence_sample = create_silence_sample(ms);
	if(!silence_sample)
	{
		eof_fix_window_title();
		return 2;	//Return error:  Couldn't create silent audio
	}
	(void) replace_filename(wavfn, eof_song_path, "silence.wav", 1024);
	(void) save_wav(wavfn, silence_sample);
	destroy_sample(silence_sample);
	(void) replace_filename(soggfn, eof_song_path, "silence.ogg", 1024);
	#ifdef ALLEGRO_WINDOWS
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -b %d \"%s\"", soggfn, alogg_get_bitrate_ogg(eof_music_track) / 1000, wavfn);
	#else
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -b %d \"%s\"", soggfn, alogg_get_bitrate_ogg(eof_music_track) / 1000, wavfn);
	#endif
	if(eof_system(sys_command))
	{
		eof_fix_window_title();
		return 3;	//Return error:  Could not encode silent audio
	}

	/* stitch the original file to the silence file */
	if(!getcwd(old_wd, 1024))
	{	//If the current working directory could not be obtained
		eof_fix_window_title();
		return 4;	//Return error:  Could not obtain current working directory
	}

	(void) eof_chdir(eof_song_path);	//Change directory to the project's folder, since oggCat does not support paths that have any Unicode/extended ASCII, relative paths will be given
	#ifdef ALLEGRO_WINDOWS
		get_executable_name(oggcfn, 1024);
		(void) replace_filename(oggcfn, oggcfn, "oggCat.exe", 1024);	//Build the full path to oggCat
	#else
		ustrzcpy(oggcfn, 1024, "oggCat");
	#endif
	rel_oggfn = get_filename(oggfn);		//Get the relative path to the target OGG file
	rel_backupfn = get_filename(backupfn);	//Get the relative path to the backup of the target OGG file
	//Call oggCat while the current working directory is the project folder.  This way, if the project folder's path contains any Unicode or extended ASCII, oggCat won't fail
	#ifdef ALLEGRO_WINDOWS
		//For some reason, the Windows build needs extra quotation marks to enclose the entire command if the command begins with a full executable path in quote marks
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "\"\"%s\" \"%s\" \"silence.ogg\" \"%s\"\"", oggcfn, rel_oggfn, rel_backupfn);
	#else
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "\"%s\" \"%s\" \"silence.ogg\" \"%s\"", oggcfn, rel_oggfn, rel_backupfn);	//Use oggCat to overwrite the target OGG file with the silent audio concatenated with the backup of the target OGG file
	#endif
	retval = eof_system(sys_command);

	/* change back to the program folder */
	if(eof_chdir(old_wd))
	{
		allegro_message("Could not change directory to EOF's program folder!\n%s", backupfn);
		return 5;	//Return error:  Could not set working directory
	}

	if(retval)
	{	//If the command failed
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tError issuing command \"%s\" from path \"%s\"", sys_command, eof_song_path);
		eof_log(eof_log_string, 1);
		(void) eof_copy_file(backupfn, oggfn);	//Restore the original OGG file
		eof_fix_window_title();
		return 6;	//Return error:  oggCat failed
	}

	/* clean up */
	(void) delete_file(wavfn);	//Delete silence.wav
	(void) delete_file(soggfn);	//Delete silence.ogg
	if(eof_load_ogg(oggfn, 0))
	{	//If the combined audio was loaded
		eof_fix_waveform_graph();
		eof_fix_spectrogram();
		eof_fix_window_title();
		eof_chart_length = eof_music_length;
		return 0;	//Return success
	}
	eof_fix_window_title();

	//If this part of the function is reached, the OGG failed to load
	if(exists(oggfn))
		return 7;	//Return error:  Could not load new audio, but audio file exists

	return 8;	//Return error:  Could not load new audio, file does not exist
}
示例#11
0
int eof_add_silence_recode(char * oggfn, unsigned long ms)
{
	char sys_command[1024] = {0};
	char backupfn[1024] = {0};
	char wavfn[1024] = {0};
	char soggfn[1024] = {0};
	ALOGG_OGG *oggfile = NULL;
	SAMPLE *decoded = NULL, *combined = NULL;
	int bits;
	int stereo;
	int freq;
	unsigned long samples;
	int channels;
	unsigned long ctr,index;
	void * oggbuffer = NULL;
	int bitrate;

 	eof_log("eof_add_silence_recode() entered", 1);

	if(!oggfn || (ms == 0) || eof_silence_loaded)
	{
		return 41;	//Return failure:  Invalid parameters
	}
	set_window_title("Adjusting Silence...");

	/* back up original file */
	(void) snprintf(backupfn, sizeof(backupfn) - 1, "%s.backup", oggfn);
	if(!exists(backupfn))
	{
		(void) eof_copy_file(oggfn, backupfn);
	}

	/* Decode the OGG file into memory */
	//Load OGG file into memory
	oggbuffer = eof_buffer_file(oggfn, 0);	//Decode the OGG from buffer instead of from file because the latter cannot support special characters in the file path due to limitations with fopen()
	if(!oggbuffer)
	{
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tError reading OGG:  \"%s\"", strerror(errno));	//Get the Operating System's reason for the failure
		eof_log(eof_log_string, 1);
		return 42;	//Return failure:  Could not buffer chart audio into memory
	}
	oggfile=alogg_create_ogg_from_buffer(oggbuffer, (int)file_size_ex(oggfn));
	if(oggfile == NULL)
	{
		eof_log("ALOGG failed to open input audio file", 1);
		free(oggbuffer);
		return 43;	//Return failure:  Could not process buffered chart audio
	}

	//Decode OGG into memory
	decoded=alogg_create_sample_from_ogg(oggfile);
	if(decoded == NULL)
	{
		alogg_destroy_ogg(oggfile);
		free(oggbuffer);
		return 44;	//Return failure:  Could not decode chart audio to memory
	}

	/* Create a SAMPLE array large enough for the leading silence and the decoded OGG */
	bits = alogg_get_wave_bits_ogg(oggfile);
	stereo = alogg_get_wave_is_stereo_ogg(oggfile);
	freq = alogg_get_wave_freq_ogg(oggfile);
	alogg_destroy_ogg(oggfile);	//This is no longer needed
	oggfile = NULL;
	samples = msec_to_samples(ms);
	channels = stereo ? 2 : 1;
	combined = create_sample(bits,stereo,freq,samples+decoded->len);	//Create a sample array long enough for the silence and the OGG file
	if(combined == NULL)
	{
		destroy_sample(decoded);
		return 45;	//Return failure:  Could not create a sample array for the combined audio
	}

	/* Add the PCM data for the silence */
	if(bits == 8)
	{	//Create 8 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = 0x80;
		}
	}
	else
	{	//Create 16 bit PCM data
		for(ctr=0,index=0;ctr < samples * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = 0x8000;
		}
	}

	/* Add the decoded OGG PCM data*/
	if(bits == 8)
	{	//Copy 8 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned char *)(combined->data))[index++] = ((unsigned char *)(decoded->data))[ctr];
		}
	}
	else
	{	//Copy 16 bit PCM data
		for(ctr=0;ctr < decoded->len * channels;ctr++)
		{
			((unsigned short *)(combined->data))[index++] = ((unsigned short *)(decoded->data))[ctr];
		}
	}

	/* encode the audio */
	destroy_sample(decoded);	//This is no longer needed
	free(oggbuffer);
	(void) replace_filename(wavfn, eof_song_path, "encode.wav", 1024);
	(void) save_wav(wavfn, combined);
	destroy_sample(combined);	//This is no longer needed
	(void) replace_filename(soggfn, eof_song_path, "encode.ogg", 1024);
	bitrate = alogg_get_bitrate_ogg(eof_music_track) / 1000;
	if(!bitrate)
	{	//A user found that in an audio file with a really high sample rate (ie. 96KHz), alogg_get_bitrate_ogg() may return zero instead of an expected value
		bitrate = 256;	//In case this happens, use a bitrate of 256Kbps, which should be good enough for a very high quality file
	}
	#ifdef ALLEGRO_WINDOWS
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -b %d \"%s\"", soggfn, bitrate, wavfn);
	#else
		(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -b %d \"%s\"", soggfn, bitrate, wavfn);
	#endif

	(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
	eof_log(eof_log_string, 1);
	if(eof_system(sys_command))
	{	//If oggenc failed, retry again by specifying a quality level (specifying bitrate can fail in some circumstances)
		eof_log("\t\toggenc failed.  Retrying by specifying a quality level instead of a target bitrate", 1);
		#ifdef ALLEGRO_WINDOWS
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc2 -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#else
			(void) uszprintf(sys_command, (int) sizeof(sys_command) - 1, "oggenc -o \"%s\" -q 9 \"%s\"", soggfn, wavfn);
		#endif
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tCalling oggenc as follows:  %s", sys_command);
		eof_log(eof_log_string, 1);
		if(eof_system(sys_command))
		{	//If oggenc failed again
			char tempfname[30] = {0};
			char redirect[35] = {0};

			if(eof_validate_temp_folder())
			{	//Ensure the correct working directory and presence of the temporary folder
				eof_log("\tCould not validate working directory and temp folder", 1);
				return 46;	//Return failure:  Could not validate cwd and temp folder
			}

			(void) snprintf(tempfname, sizeof(tempfname) - 1, "%soggenc.log", eof_temp_path_s);
			(void) snprintf(redirect, sizeof(redirect) - 1, " 2> %s", tempfname);
			(void) ustrzcat(sys_command, (int) sizeof(sys_command) - 1, redirect);	//Append a redirection to the command to capture the output of oggenc
			if(eof_system(sys_command))
			{	//Run one last time to catch the error output
				(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "\tOggenc failed.  Please see %s for any errors it gave.", tempfname);
				eof_log(eof_log_string, 1);
				eof_fix_window_title();
				return 47;	//Return failure:  Could not encode combined audio
			}
		}
	}

	/* replace the current OGG file with the new file */
	(void) eof_copy_file(soggfn, oggfn);	//Copy encode.ogg to the filename of the original OGG

	/* clean up */
	(void) delete_file(soggfn);	//Delete encode.ogg
	(void) delete_file(wavfn);		//Delete encode.wav
	if(eof_load_ogg(oggfn, 0))
	{	//If the combined audio was loaded
		eof_fix_waveform_graph();
		eof_fix_spectrogram();
		eof_fix_window_title();
		eof_chart_length = eof_music_length;
		return 0;	//Return success
	}
	eof_fix_window_title();

	return 48;	//Return error:  Could not load new audio
}
示例#12
0
struct wavestruct *eof_create_waveform(char *oggfilename, unsigned long slicelength)
{
	ALOGG_OGG *oggstruct = NULL;
	SAMPLE *audio = NULL;
	void * oggbuffer = NULL;
	struct wavestruct *waveform = NULL;
	static struct wavestruct emptywaveform;	//all variables in this auto initialize to value 0
	char done = 0;	//-1 on unsuccessful completion, 1 on successful completion
	unsigned long slicenum = 0;

 	eof_log("\tGenerating waveform", 1);
 	eof_log("eof_create_waveform() entered", 1);

	set_window_title("Generating Waveform Graph...");

	if((oggfilename == NULL) || !slicelength)
	{
		eof_log("Waveform: Invalid parameters", 1);
		return NULL;
	}

//Load OGG file into memory
	oggbuffer = eof_buffer_file(oggfilename, 0);
	if(!oggbuffer)
	{
		(void) snprintf(eof_log_string, sizeof(eof_log_string) - 1, "Waveform: Failed to open input audio file: %s",strerror(errno));
		eof_log(eof_log_string, 1);
		return NULL;
	}
	oggstruct = alogg_create_ogg_from_buffer(oggbuffer, (int)file_size_ex(oggfilename));
	if(oggstruct == NULL)
	{
		eof_log("Waveform: ALOGG failed to open input audio file", 1);
		free(oggbuffer);
		return NULL;
	}

//Decode OGG into memory
	audio = alogg_create_sample_from_ogg(oggstruct);
	if(audio == NULL)
	{
		eof_log("Waveform: ALOGG failed to decode input audio file", 1);
		done = -1;
	}
	else if((audio->bits != 8) && (audio->bits != 16))	//This logic currently only supports 8 and 16 bit audio
	{
		eof_log("Waveform: Invalid sample size", 1);
		done = -1;
	}
	else
	{
//Initialize waveform structure
		waveform = (struct wavestruct *)malloc(sizeof(struct wavestruct));
		if(waveform == NULL)
		{
			eof_log("Waveform: Unable to allocate memory for the waveform structure", 1);
			done = -1;
		}
		else
		{
			*waveform = emptywaveform;					//Set all variables to value zero
			waveform->slicelength = slicelength;
			if(alogg_get_wave_is_stereo_ogg(oggstruct))	//If this audio file has two audio channels
				waveform->is_stereo = 1;
			else
				waveform->is_stereo = 0;

			if(audio->bits == 8)
				waveform->zeroamp = 128;	//128 represents amplitude 0 for unsigned 8 bit audio samples
			else
				waveform->zeroamp = 32768;	//32768 represents amplitude 0 for unsigned 16 bit audio samples

			waveform->oggfilename = (char *)malloc(strlen(oggfilename)+1);
			if(waveform->oggfilename == NULL)
			{
				eof_log("Waveform: Unable to allocate memory for the audio filename string", 1);
				done = -1;
			}
			else
			{
				waveform->slicesize = audio->freq * slicelength / 1000;	//Find the number of samples in each slice
				if((audio->freq * slicelength) % 1000)					//If there was any remainder
					waveform->slicesize++;								//Increment the size of the slice

				waveform->numslices = (double)audio->len / ((double)audio->freq * (double)slicelength / 1000.0);	//Find the number of slices to process
				if(audio->len % waveform->numslices)		//If there's any remainder
					waveform->numslices++;					//Increment the number of slices

				strcpy(waveform->oggfilename,oggfilename);
				waveform->left.slices = (struct waveformslice *)malloc(sizeof(struct waveformslice) * waveform->numslices);
				if(waveform->left.slices == NULL)
				{
					eof_log("Waveform: Unable to allocate memory for the left channel waveform data", 1);
					done = -1;
				}
				else if(waveform->is_stereo)	//If this OGG is stereo
				{				//Allocate memory for the right channel waveform data
					waveform->right.slices = (struct waveformslice *)malloc(sizeof(struct waveformslice) * waveform->numslices);
					if(waveform->right.slices == NULL)
					{
						eof_log("Waveform: Unable to allocate memory for the right channel waveform data", 1);
						done = -1;
					}
				}
			}
		}
	}

	while(!done)
	{
		done = eof_process_next_waveform_slice(waveform, audio, slicenum++);
	}

//Cleanup
	if(oggstruct != NULL)
		alogg_destroy_ogg(oggstruct);
	if(audio != NULL)
		destroy_sample(audio);
	if(oggbuffer)
		free(oggbuffer);
	if(done == -1)	//Unsuccessful completion
	{
		if(waveform)
		{
			if(waveform->oggfilename)
				free(waveform->oggfilename);
			free(waveform);
		}
		allegro_message("Failed to generate waveform.  See log for details");
		return NULL;	//Return error
	}

	//Cache the difference between each channel's zero amplitude and its maximum amplitude for optimized rendering
	if(waveform->left.maxamp > waveform->zeroamp)
		waveform->left.maxampoffset = waveform->left.maxamp - waveform->zeroamp;
	else
		waveform->left.maxampoffset = waveform->zeroamp - waveform->left.maxamp;
	if(waveform->is_stereo)
	{	//If there is right channel waveform data
		if(waveform->right.maxamp > waveform->zeroamp)
			waveform->right.maxampoffset = waveform->right.maxamp - waveform->zeroamp;
		else
			waveform->right.maxampoffset = waveform->zeroamp - waveform->right.maxamp;
	}

	eof_log("\tWaveform generated", 1);
	return waveform;	//Return waveform data
}
示例#13
0
文件: main.c 项目: KUNICA/MoneyMan
int main(int argc, char *argv[]) {
	int i;
	char **menutext;

	/* Allocate space for menu texts and write them there */

	menutext = malloc(5*sizeof(*menutext));
	for(i=0;i<5;i++)
		menutext[i] = malloc(64*sizeof(**menutext));

	sprintf(menutext[0],"Play speed mode");
	sprintf(menutext[1],"Play time mode");
	sprintf(menutext[2],"Players: 1");
	sprintf(menutext[3],"Settings");
	sprintf(menutext[4],"Quit");

	/* Init allegro and stuff I need */
	allegro_init();
	install_keyboard();
	/* install_mouse(); */

	/* Init gfx mode */
	set_color_depth(24);
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, 800,600,0,0);
	set_window_title("Anton Pirogov's MoneyMan v1.0");

	/* Init logic tick timer */
	install_timer();
	LOCK_VARIABLE(speed_counter);
	LOCK_FUNCTION(increment_speed_counter);
	install_int_ex(increment_speed_counter, BPS_TO_TIMER(60));
	/* Lock coin movement timer */
	LOCK_VARIABLE(coinmove_counter);
	LOCK_FUNCTION(increment_coinmove_counter);

	set_close_button_callback( close_button_handler ); /* Close with X */

	/* Set colors */
	titlecol=makecol(255,192,0);
	infocol=makecol(255,128,192);
	menucol=makecol(0,0,255);
	menuselcol=makecol(171,171,255);
	backcolor=makecol(245, 245, 220); /* beige */
	scoretitcol=makecol(0,128,128);
	scorenamcol=makecol(128,64,255);
	scorescrcol=makecol(255,128,255);

	/* Load font */
	myfont = load_font("gfx/Komikaboogie18px.tga",NULL,NULL);

	/* Show main menu */
	read_scores();
	generic_menu(menutext,5,mainmenu_event,backcolor,menucol,menuselcol,fontpxsize,0,0,renderscores);

	/* Finish clean up */
	for (i=0;i<4;i++)
		free(menutext[i]);
	free(menutext);
	allegro_exit();
	return 0;
}
示例#14
0
 void setTitleBar(const std::string& title) override {
   set_window_title(title.c_str());
 }
示例#15
0
// Sets up game (bitmaps, sounds, ect.)
void setup(bool first) {
  //Assigns variables
  x = 0;
  y = 0;
  gridimage = 0;

  //Refreshes game board
  for(int i = 0; i < 4; i++) {
    for(int t = 0; t < 4; t++) {
      gridarray[i][t] = 0;
    }
  }

  if(first) {
    // Allegro Stuff
    allegro_init();
    alpng_init();
    install_keyboard();
    install_mouse();
    install_sound(DIGI_AUTODETECT,MIDI_AUTODETECT,".");
    set_window_title("A.D.S. Games - Tic Tac Toe");

    // Graphics
    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, 300, 300, 0, 0);

    // Init variables
    gameRunning = true;
    turn = 0;
    selector = 0;
    soundfx = true;
    difficulty = 1;
    gameScreen = 1;

    // Sets button images
    one_player.set_images("images/buttons/one_player.png", "images/buttons/one_player_hover.png");
    two_player.set_images("images/buttons/two_player.png", "images/buttons/two_player_hover.png");
    quit.set_images("images/buttons/quit.png", "images/buttons/quit_hover.png");
    menu.set_images("images/buttons/menu.png", "images/buttons/menu_hover.png");
    sound.set_images("images/buttons/sound_on.png", "images/buttons/sound_on_hover.png");
    difficulty_b.set_images("images/buttons/medium.png", "images/buttons/medium_hover.png");

    // Assigns bitmaps
    buffer = create_bitmap(300, 300);
    grid = load_bitmap("images/grid.png", NULL);
    img_x = load_bitmap("images/x.png", NULL);
    img_o = load_bitmap("images/o.png", NULL);
    blank = load_bitmap("images/none.png", NULL);
    xwin = load_bitmap("images/xwin.png", NULL);
    owin = load_bitmap("images/owin.png", NULL);
    catsgame = load_bitmap("images/catsgame.png", NULL);
    main_menu = load_bitmap("images/main_menu.png", NULL);

    cursor[0] = load_bitmap("images/cursor.png", NULL);
    cursor[1] = load_bitmap("images/cursor_x.png", NULL);
    cursor[2] = load_bitmap("images/cursor_o.png", NULL);

    selected[0] = load_bitmap("images/selected.png", NULL);
    selected[1] = load_bitmap("images/selected2.png", NULL);
    selected[2] = load_bitmap("images/selected3.png", NULL);
    selected[3] = load_bitmap("images/selected4.png", NULL);

    // Assigns Sounds
    win = load_sample("sfx/win.wav");
    lose = load_sample("sfx/lose.wav");
    cat = load_sample("sfx/catsgame.wav");
    place = load_sample("sfx/place.wav");

    // Seeds random number generator
    srand (time(NULL));

    // Sets button positions
    one_player.set_position(50, 70);
    two_player.set_position(50, 130);
    quit.set_position(50, 190);
    menu.set_position(0, 270);
    sound.set_position(110, 250);
    difficulty_b.set_position(150, 250);
  }
}
示例#16
0
文件: main.cpp 项目: Lucki/Lix
int main(int argc, char* argv[])
{
    MainArgs margs = parse_main_arguments(argc, argv);

    if (margs.print_version_and_exit) {
        std::cout << Help::version_to_string(Globals::version) << std::endl;
        return 0;
    }
    else if (margs.print_help_and_exit) {
        print_usage();
        return 0;
    }

    // From here, load either the game or the interactive replay checker.
    // This will depend on existing dirs later on.

    setenv_allegro_modules();
    allegro_init();
    unsetenv_allegro_modules();

    Help::timer_start();

    ::loadpng_init();

    Globals::initialize();
    User::initialize();
    Log::initialize();
    LixEn::initialize();

    // Check whether the Globals decided we're in one of the accepted
    // working directories, so all files are found. Otherwise, exit with error.
    if (! Help::dir_exists(gloB->dir_data_bitmap)) {
        allegro_message("%s", gloB->error_wrong_working_dir.c_str());
        Log::deinitialize();
        Globals::deinitialize();
        return -1;
    }

    gloB->load();
    if (margs.input_user_name) {
        gloB->user_name = "";
    }
    useR->load();

    // Graphics are needed both by interactive and noninteractive mode
    ::set_color_depth(16);

    if (margs.replays_to_verify.empty()) {
        // interactive mode, i.e., no replay checking mode

        install_keyboard();
        hardware.set_mouse_accel_on_windows(useR->mouse_acceleration);
        install_mouse();
        if (! margs.suppress_sound_driver && gloB->sound_load_driver)
            Sound::initialize();

        if (margs.resolution_or_fullscreen_suggested_via_args)
            set_screen_mode(margs.fullscreen, margs.graphics_driver,
                            margs.screen_xl,  margs.screen_yl);
        else
            set_screen_mode(! useR->screen_windowed,
                            margs.graphics_driver, 0, 0);

        // BUG: in Windows, setting the window title with non-ASCII UTF-8
        // string does not seem to work (Allegro bug?)--non-ASCII characters
        // turn into ^.  Workaround by forcing use of English string here.
        //
        // (should main_name_of_the_game even be allowed for translation?)
        set_window_title(Language::main_name_of_game_English);

        if (useR->language == Language::NONE
         || useR->language >= Language::MAX) {
            // This is for the "initial use" case where there is no
            // user profile and therefore no language set.
            //
            // It is preferrable in that case to load the custom language
            // if it exists, so that we display the "loading..." texts (inside
            // load_all_bitmaps() below) text in the language the user probably
            // wants (the custom one if it exists, otherwise English)
            static_cast<void>(Language::try_load_custom_language(false));
        }

        load_all_bitmaps(GraLib::LOAD_WITH_RECOLOR_LIX);
        Network::initialize();

        // Main loop. See other/lmain.cpp for this.
        LMain* l_main = new LMain;
        l_main->main_loop();
        delete l_main;

        // Clean up
        useR->save();
        gloB->save();

        destroy_all_bitmaps();

        Network::deinitialize();
        Sound::deinitialize();
    }

    else {
        // noninteractive mode that checks replays
        Help::interactive_mode = false;
        Verifier(margs.replays_to_verify, margs.convert_and_overwrite
            ? Verifier::yes
            : Verifier::no);
    }

    Log::deinitialize();
    Globals::deinitialize();

    // don't call allegro_exit(), doing that causes the program
    // to not terminate in rare cases
    return 0;
}
示例#17
0
static void
ldapstat_set_title(ldapstat_t *ldap)
{
	set_window_title(ldap->win, "LDAP Service Response Time statistics");
}
示例#18
0
static void
afpstat_set_title(afpstat_t *ss)
{
	set_window_title(ss->win, "AFP Service Response Time statistics");
}
示例#19
0
bool
header_editor_frame_c::open_file(wxFileName file_name) {
    if (!kax_analyzer_c::probe(wxMB(file_name.GetFullPath()))) {
        wxMessageBox(Z("The file you tried to open is not a Matroska file."), Z("Wrong file selected"), wxOK | wxCENTER | wxICON_ERROR);
        return false;
    }

    m_e_segment_info.clear();
    m_e_tracks.clear();

    m_analyzer = wx_kax_analyzer_cptr(new wx_kax_analyzer_c(this, wxMB(file_name.GetFullPath())));

    if (!m_analyzer->process(kax_analyzer_c::parse_mode_fast)) {
        wxMessageBox(Z("This file could not be opened or parsed."), Z("File parsing failed"), wxOK | wxCENTER | wxICON_ERROR);
        m_analyzer.clear();

        return false;
    }

    m_file_name = file_name;
    m_file_name.GetTimes(NULL, &m_file_mtime, NULL);

    set_window_title();

    m_ignore_tree_selection_changes = true;

    enable_menu_entries();

    m_bs_main->Hide(m_tc_tree);

    size_t i;
    for (i = 0; m_pages.size() > i; ++i)
        if (m_pages[i]->IsShown())
            m_pages[i]->Hide();

    m_tc_tree->DeleteChildren(m_root_id);
    m_bs_page->Clear();
    m_pages.clear();
    m_top_level_pages.clear();

    for (i = 0; m_analyzer->m_data.size() > i; ++i) {
        kax_analyzer_data_c *data = m_analyzer->m_data[i].get_object();
        if (data->m_id == KaxInfo::ClassInfos.GlobalId) {
            handle_segment_info(data);
            break;
        }
    }

    for (i = 0; m_analyzer->m_data.size() > i; ++i) {
        kax_analyzer_data_c *data = m_analyzer->m_data[i].get_object();
        if (data->m_id == KaxTracks::ClassInfos.GlobalId) {
            handle_tracks(data);
            break;
        }
    }

    m_analyzer->close_file();

    m_bs_main->Show(m_tc_tree);
    m_bs_main->Layout();

    last_open_dir                   = file_name.GetPath();

    m_ignore_tree_selection_changes = false;

    return true;
}
示例#20
0
static void
diameterstat_set_title(diameterstat_t *diameter)
{
	set_window_title(diameter->win, "Diameter Service Response Time statistics");
}
示例#21
0
void detection_thread<T>::execute() {
  try {
    bool	display        = false;
#ifdef __GUI__
    display = conf.exists_true("display")
        && conf.exists_true("display_threads");
    bool	mindisplay     = conf.exists_true("minimal_display");
    bool       save_video     = conf.exists_true("save_video");
    bool	display_states = conf.exists_true("display_states");
    uint       wid	       = 0;	// window id
    uint       wid_states     = 0;	// window id
#endif
    uint	display_sleep  = conf.try_get_uint("display_sleep", 0);
    //      if (!display && save_video) {
    //        // we still want to output images but not show them
    //        display = true;
    // #ifdef __GUI__
    //        set_gui_silent();
    // #endif
    //      }
    // load network and weights in a forward-only parameter
    parameter<T> theparam;
    theparam.set_forward_only();
    idx<ubyte> classes(1,1);
    //try { // try loading classes names but do not stop upon failure
    load_matrix<ubyte>(classes, conf.get_cstring("classes"));
    // } catch(std::string &err) {
    //   merr << "warning: " << err;
    //   merr << std::endl;
    // }
    std::vector<std::string> sclasses = ubyteidx_to_stringvector(classes);
    answer_module<T> *ans = create_answer<T,T,T>(conf, classes.dim(0));
    uint noutputs = ans->get_nfeatures();
    intg thick = -1;
    module_1_1<T> *net = create_network<T>(theparam, conf, thick, noutputs,
                                           "arch", this->_id);
    // loading weights
    if (conf.exists("weights")) { // manual weights
      // concatenate weights if multiple ones
      std::vector<std::string> w =
          string_to_stringvector(conf.get_string("weights"));
      mout << "Loading weights from: " << w << std::endl;
      theparam.load_x(w);
      // permute weights by blocks
      if (conf.exists("weights_permutation")) {
        std::string sblocks = conf.get_string("weights_blocks");
        std::string spermut = conf.get_string("weights_permutation");
        std::vector<intg> blocks = string_to_intgvector(sblocks.c_str());
        std::vector<uint> permut = string_to_uintvector(spermut.c_str());
        theparam.permute_x(blocks, permut);
      }
    } else {
      if (conf.exists_true("manual_load")) { // manual load
        eblwarn("\"weights\" variable not defined, loading manually "
                << "if manual_load defined");
        manually_load_network(*((layers<T>*)net), conf);
      } else { // random weights
        int seed = dynamic_init_drand();
        eblwarn("No weights to load, randomizing weights with seed " << seed);
        forget_param_linear fgp(1, 0.5, seed);
        net->forget(fgp);
      }
    }
    DEBUGMEM_PRETTY("before detection");
    // detector
    detector<T> detect(*net, sclasses, ans, NULL, NULL, mout, merr);
    init_detector(detect, conf, outdir, silent);
    // keep pointer to detector
    pdetect = &detect;
    bootstrapping<T> boot(conf);

    // when a bbox file is given, ignore the processing, load the pre-computed
    // bboxes and feed them to the nms (non-maximum suppression).
    bboxes boxes(bbox_all, NULL, mout, merr);
    boxes.print_saving_type(); // inform user how we save boxes
    bool precomputed_boxes = false;
    if (conf.exists("bbox_file")) {
      precomputed_boxes = true;
      std::string bbfile = conf.get_string("bbox_file");
      boxes.load_eblearn(bbfile);
    }
    bool bmask_class = false;
    if (conf.exists("mask_class"))
      bmask_class = detect.set_mask_class(conf.get_cstring("mask_class"));

    std::string viddir = outdir;
    viddir += "video/";
    mkdir_full(viddir);
    // gui
#ifdef __GUI__
    uint display_wmax = conf.try_get_uint("display_max_width", 3000);
    T display_min = (T) conf.try_get_double("display_min", -1.7);
    T display_max = (T) conf.try_get_double("display_max", 1.7);
    T display_in_max = (T) conf.try_get_double("display_in_max", 255);
    T display_in_min = (T) conf.try_get_double("display_in_min", 0);
    float display_transp = conf.try_get_float("display_bb_transparency", 0);
    uint qstep1 = conf.try_get_uint("qstep1", 0);
    uint qheight1 = conf.try_get_uint("qheight1", 0);
    uint qwidth1 = conf.try_get_uint("qwidth1", 0);
    uint qstep2 = conf.try_get_uint("qstep2", 0);
    uint qheight2 = conf.try_get_uint("qheight2", 0);
    uint qwidth2 = conf.try_get_uint("qwidth2", 0);
    module_1_1_gui	netgui;
    wid_states  = display_states ? new_window("network states"):0;
    night_mode();
    std::string title = "EBLearn detector: ";
    title += _name;
    if (display) {
      wid = new_window(title.c_str());
      mout << "displaying in window " << wid << std::endl;
      night_mode();
    }
    float zoom = conf.try_get_float("display_zoom", 1);
    bool bbox_show_conf = !conf.exists_false("bbox_show_conf");
    bool bbox_show_class = !conf.exists_false("bbox_show_class");
    detector_gui<T>
        dgui(conf.try_get_uint("show_extracted", 0),
             conf.exists_bool("queue1"), qstep1, qheight1,
             qwidth1, conf.exists_bool("queue2"), qstep2, qheight2, qwidth2,
             bbox_show_class, bbox_show_conf);
    if (bmask_class)
      dgui.set_mask_class(conf.get_cstring("mask_class"),
                          (T) conf.try_get_double("mask_threshold", 0));
#endif
    // timing variables
    timer tpass, toverall;
    long ms;
    // loop
    toverall.start();
    // we're ready
    bavailable = true;
    while(!this->_stop) {
      // wait until a new image is made available
      while (!in_updated && !_stop) {
        millisleep(1);
      }
      tpass.restart();
      if (_stop) break ;
      // we got a new frame, reset new frame flag
      in_updated = false; // no need to lock mutex
      // check if this frame should be skipped
      if (boot.skip_frame(frame_name)) {
        skip_frame();
        continue ;
      } else if (!frame_loaded) {
        uframe = load_image<ubyte>(frame_fullname);
        mout << "loaded image " << frame_fullname << std::endl;
      }
      if (!silent) mout << "processing " << frame_name << std::endl;
      // check frame is correctly allocated, if not, allocate.
      if (frame.order() != uframe.order())
        frame = idx<T>(uframe.get_idxdim());
      else if (frame.get_idxdim() != uframe.get_idxdim())
        frame.resize(uframe.get_idxdim());
      // copy frame
      idx_copy(uframe, frame);
      // run detector
      if (!display) { // fprop without display
        if (precomputed_boxes) {
          try {
            bboxes *bb = boxes.get_group(frame_name);
            idxdim d = boxes.get_group_dims(frame_name);
            d.insert_dim(0, 1);
            bboxes pruned;
            detect.init(d);
            detect.fprop_nms(*bb, pruned);
            copy_bboxes(pruned); // make a copy of bounding boxes
            // resize frame so that caller knows the size of the frame
            idxdim framedim = frame.get_idxdim();
            if (d.dim(1) == -1 || d.dim(2) == -1)
              eblerror("pre-computed boxes must contain full image size, "
                       << "but found: " << d);
            framedim.setdim(0, d.dim(1));
            framedim.setdim(1, d.dim(2));
            frame.resize(framedim);
          } catch(eblexception &e) {
#ifdef __NOEXCEPTIONS__
            merr << "exception" << std::endl;
#else
            merr << e << std::endl;
#endif
          }
        } else {
          try {
            mout << "starting processing of frame " << frame_name << std::endl;
            bboxes &bb = detect.fprop(frame, frame_name.c_str(), frame_id);
            copy_bboxes(bb); // make a copy of bounding boxes
          } catch(ebl::eblexception &e) { // detection failed
#ifdef __NOEXCEPTIONS__
            eblwarn("detection failed");
#else
            eblwarn("detection failed: " << e);
#endif
            clear_bboxes();
          }
        }
      }
#ifdef __GUI__
      else { // fprop and display
        if (precomputed_boxes) eblerror("not implemented for nms only (TODO)");
        disable_window_updates();
        select_window(wid);
        clear_window();
        std::string title = _name;
        title << ": " << frame_name;
        set_window_title(title.c_str());
        //	 clear_resize_window();
        try {
          if (mindisplay) {
            bboxes &bb =
                dgui.display(detect, frame, frame_name.c_str(), frame_id,
                             0, 0, zoom, display_min, display_max,
                             wid, _name.c_str(), display_transp);
            copy_bboxes(bb); // make a copy of bounding boxes
          } else {
            // extract & display boxes
            bboxes &bb =
                dgui.display_inputs_outputs(detect, frame, frame_name.c_str(),
                                            frame_id, 0, 0, zoom,
                                            display_min, display_max, wid,
                                            _name.c_str(),
                                            display_in_min, display_in_max,
                                            display_transp, display_wmax);
            // make a copy of bounding boxes
            copy_bboxes(bb);
          }
        } catch(ebl::eblexception &e) { // detection failed
          eblwarn("detection failed: " << e);
          clear_bboxes();
        }
        enable_window_updates();
      }
      if (display_states) {
        dgui.display_current(detect, frame, wid_states, NULL, zoom);
        select_window(wid);
      }
      if (save_video && display) {
        std::string fname = viddir;
        fname += frame_name;
        save_window(fname.c_str());
        if (!silent) mout << "saved " << fname << std::endl;
      }
#endif
      if (!silent)
        mout << "processing done for frame " << frame_name << std::endl;
      // bootstrapping
      if (conf.exists_true("bootstrapping")) {
        boot.fprop(detect, frame_name);
        // add multiple scales if positives and scales are defined
        if (conf.exists("gt_scales") && boot.extract_positives()) {
          std::vector<double> scales =
              string_to_doublevector(conf.get_cstring("gt_scales"));
          for (uint s = 0; s < scales.size(); ++s) {
            double f = scales[s];
            // downsample input by f
            detect.set_resolution(f);
            detect.init(frame.get_idxdim(), frame_name.c_str());
            detect.fprop(frame, frame_name.c_str(), frame_id);
            boot.fprop(detect, frame_name, false, f);
          }
          detect.set_scaling_original();
          detect.init(frame.get_idxdim(), frame_name.c_str());
        }
        copy_bootstrapping(boot.get_all(), boot.get_bball());
#ifdef __GUI__
        // display groundtruth
        if (conf.exists_true("display_bootstrapping"))
          dgui.display_groundtruth(detect, frame, boot.get_gtall(),
                                   boot.get_gtclean(), boot.get_gtrest(),
                                   boot.get_bbpos(), boot.get_bbneg(),
                                   boot.get_pos(), boot.get_neg(), 0, 0, zoom,
                                   display_min, display_max);
#endif
      }
      total_saved = detect.get_total_saved();
      ms = tpass.elapsed_milliseconds();
      if (!silent) {
        mout << bbs.pretty_short(detect.get_labels());
        mout << "processing=" << ms << " ms ("
             << tpass.elapsed() << ")" << std::endl;
      }
      DEBUGMEM_PRETTY("after detection");
      // switch 'updated' flag on to warn we just added new data
      set_out_updated();
      // display sleep
      if (display_sleep > 0) {
        mout << "sleeping for " << display_sleep << "ms." << std::endl;
        millisleep(display_sleep);
      }
      if (conf.exists("save_max") &&
          detect.get_total_saved() > conf.get_uint("save_max"))
        break ; // limit number of detection saves
    }
    mout << "detection finished. Execution time: " << toverall.elapsed()<<std::endl;
    // free variables
    if (net) delete net;
    if (ans) delete ans;
  } eblcatcherror();
}
示例#22
0
int init_screen(screen_t* my_screen, int width, int height, char* images_folder){
	int i;
	char str[5][256];
	BITMAP	*buff0;
	BITMAP	*buff1;
	BITMAP	*buff2;
	BITMAP	*buff3;
	BITMAP	*buff4;

	my_screen-> w = width;
	my_screen-> h = height;
	my_screen-> images_folder= images_folder;
	my_screen-> bg_col = makecol(0,0,0);
	my_screen-> status = MENU;
	my_screen->scene = 0 ;
	allegro_init();
	printf("allegro initialized\n");
	set_window_title("Car Race");
	set_color_depth(16);
	set_gfx_mode(GFX_AUTODETECT_WINDOWED, my_screen->w, my_screen->h, 0, 0);
	install_keyboard();
	strcpy(str[0], images_folder);
	strcpy(str[1], images_folder);
	strcpy(str[2], images_folder);
	strcpy(str[3], images_folder);
	strcpy(str[4], images_folder);
	strcat(str[0], "dash_texture.tga");
	strcat(str[1], "speedmeter.tga");
	strcat(str[2], "needle.tga");
	strcat(str[3], "reddash.tga");
	strcat(str[4], "needle.tga");

	/*init map */
	init_screen_map(my_screen);

	/*init user interface*/
	init_screen_ui(my_screen);
	buff0 = load_bitmap(str[0], NULL);
	if(!buff0)
		printf("problems loading texture bmp!\n");
	stretch_blit(buff0, my_screen->ui.if_bmp, 0, 0, buff0->w - 1, buff0->h - 1, 0, 0, UI_W - 1, UI_H -1);
	destroy_bitmap(buff0);
	buff1 = load_bitmap(str[1], NULL);
	if(!buff1)
		printf("problems loading speedmeter bmp!\n");
	stretch_blit(buff1, my_screen->ui.speedmeter, 0, 0, buff1->w, buff1->h , 0, 0, my_screen->ui.speedmeter->w , my_screen->ui.speedmeter->h);
	destroy_bitmap(buff1);
	buff2 = load_bitmap(str[2], NULL);
	if(!buff2)
		printf("problems loading needle bmp!\n");
	stretch_blit(buff2, my_screen->ui.needle, 0, 0, buff2->w, buff2->h, 0, 0, my_screen->ui.needle->w, my_screen->ui.needle->h);
	destroy_bitmap(buff2);
	buff3 = load_bitmap(str[3], NULL);
	if(!buff3)
		printf("problems loading speedmeter bmp!\n");
	stretch_blit(buff3, my_screen->ui.redspeedmeter, 0, 0, buff3->w, buff3->h , 0, 0, my_screen->ui.redspeedmeter->w , my_screen->ui.redspeedmeter->h);
	destroy_bitmap(buff3);
	buff4 = load_bitmap(str[4], NULL);
	if(!buff4)
		printf("problems loading little needle bmp!\n");
	stretch_blit(buff4, my_screen->ui.little_needle, 0, 0, buff4->w, buff4->h, 0, 0, my_screen->ui.little_needle->w, my_screen->ui.little_needle->h);
	destroy_bitmap(buff4);

	/*init thread data*/
	init_screen_td(my_screen);

	/*Generate Cars*/
	new_car(&my_screen->vw.player, PLAYER_ID, my_screen->images_folder);
	for(i=0; i<CPUCARS; i++)
		new_car(&my_screen->vw.cpu[i], i, my_screen->images_folder);

	blit(my_screen->map.background, screen, 0, 0, 0, 0, my_screen->map.w - 1, my_screen->map.h - 1);
	blit(my_screen->td.td_bmp, screen, 0, 0, MAP_W, 0, my_screen->td.w - 1, my_screen->td.h - 1);
	printf("screen initialized\n");
	return 0;
}
示例#23
0
文件: audio.c 项目: mikekap/wine
INT_PTR CALLBACK
AudioDlgProc (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg) {
      case WM_COMMAND:
	switch (LOWORD(wParam)) {
          case IDC_AUDIO_CONFIGURE:
	     configureAudioDriver(hDlg);
	     break;
          case IDC_AUDIO_TEST:
	     if(!PlaySound(MAKEINTRESOURCE(IDW_TESTSOUND), NULL, SND_RESOURCE | SND_SYNC))
                MessageBox(NULL, "Audio test failed!", "Error", MB_OK | MB_ICONERROR);
             break;
          case IDC_AUDIO_CONTROL_PANEL:
	     MessageBox(NULL, "Launching audio control panel not implemented yet!", "Fixme", MB_OK | MB_ICONERROR);
             break;
          case IDC_DSOUND_HW_ACCEL:
	    if (HIWORD(wParam) == CBN_SELCHANGE) {
	      int selected_dsound_accel;
              int i, j = 0;

	      SendMessage(GetParent(hDlg), PSM_CHANGED, 0, 0);
	      selected_dsound_accel = SendDlgItemMessage(hDlg, IDC_DSOUND_HW_ACCEL, CB_GETCURSEL, 0, 0);
              for (i = 0; DSound_HW_Accels[i].settingStr; ++i)
              {
                if (DSound_HW_Accels[i].visible)
                {
                  if (j == selected_dsound_accel)
                  {
                    set_reg_key(config_key, keypath("DirectSound"), "HardwareAcceleration",
                      DSound_HW_Accels[i].settingStr);
                    break;
                  }
                  j++;
                }
              }
	    }
	    break;
          case IDC_DSOUND_RATES:
	    if (HIWORD(wParam) == CBN_SELCHANGE) {
	      int selected_dsound_rate;
	      SendMessage(GetParent(hDlg), PSM_CHANGED, 0, 0);
	      selected_dsound_rate = SendDlgItemMessage(hDlg, IDC_DSOUND_RATES, CB_GETCURSEL, 0, 0);
	      set_reg_key(config_key, keypath("DirectSound"), "DefaultSampleRate", DSound_Rates[selected_dsound_rate]);
	    }
	    break;
          case IDC_DSOUND_BITS:
	    if (HIWORD(wParam) == CBN_SELCHANGE) {
	      int selected_dsound_bits;
	      SendMessage(GetParent(hDlg), PSM_CHANGED, 0, 0);
	      selected_dsound_bits = SendDlgItemMessage(hDlg, IDC_DSOUND_BITS, CB_GETCURSEL, 0, 0);
	      set_reg_key(config_key, keypath("DirectSound"), "DefaultBitsPerSample", DSound_Bits[selected_dsound_bits]);
	    }
	    break;
	}
	break;

      case WM_SHOWWINDOW:
        set_window_title(hDlg);
        break;

      case WM_NOTIFY:
	switch(((LPNMHDR)lParam)->code) {
	    case PSN_KILLACTIVE:
	      SetWindowLongPtr(hDlg, DWLP_MSGRESULT, FALSE);
	      break;
	    case PSN_APPLY:
	      set_reg_key(config_key, "Drivers", "Audio", curAudioDriver);
              apply();
	      SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_NOERROR);
	      break;
	    case PSN_SETACTIVE:
	      break;
            case NM_CLICK:
              if (((LPNMHDR)lParam)->idFrom == IDC_AUDIO_TREE)
              {
                  TVHITTESTINFO ht;
                  DWORD dwPos = GetMessagePos();
                  HWND tree = ((LPNMHDR)lParam)->hwndFrom;
                  ZeroMemory(&ht, sizeof(ht));
                  ht.pt.x = (short)LOWORD(dwPos);
                  ht.pt.y = (short)HIWORD(dwPos);
                  MapWindowPoints(HWND_DESKTOP, tree, &ht.pt, 1);
                  SendMessageW( tree, TVM_HITTEST, 0, (LPARAM)&ht );
                  if (TVHT_ONITEMSTATEICON & ht.flags)
                  {
                      TVITEM tvItem;
                      int index;
                      ZeroMemory(&tvItem, sizeof(tvItem));
                      tvItem.hItem = ht.hItem;
                      SendMessageW( tree, TVM_GETITEMW, 0, (LPARAM) &tvItem );

                      index = TreeView_GetItemState(tree, ht.hItem, TVIS_STATEIMAGEMASK);
                      if (index == INDEXTOSTATEIMAGEMASK(1))
                      {
                          TreeView_SetItemState(tree, ht.hItem, INDEXTOSTATEIMAGEMASK(2), TVIS_STATEIMAGEMASK);
                          addDriver(loadedAudioDrv[tvItem.lParam & 0xff].szDriver);
                          SendMessage(GetParent(hDlg), PSM_CHANGED, (WPARAM) hDlg, 0); /* enable apply button */
                      }
                      else if (index == INDEXTOSTATEIMAGEMASK(2))
                      {
                          TreeView_SetItemState(tree, ht.hItem, INDEXTOSTATEIMAGEMASK(1), TVIS_STATEIMAGEMASK);
                          removeDriver(loadedAudioDrv[tvItem.lParam & 0xff].szDriver);
                          SendMessage(GetParent(hDlg), PSM_CHANGED, (WPARAM) hDlg, 0); /* enable apply button */
                      }
                  }
              }
              break;
            case NM_RCLICK:
              if (((LPNMHDR)lParam)->idFrom == IDC_AUDIO_TREE)
              {
                  TVHITTESTINFO ht;
                  DWORD dwPos = GetMessagePos();
                  HWND tree = ((LPNMHDR)lParam)->hwndFrom;
                  POINT pt;
                  ZeroMemory(&ht, sizeof(ht));
                  pt.x = (short)LOWORD(dwPos);
                  pt.y = (short)HIWORD(dwPos);
                  ht.pt = pt;
                  MapWindowPoints(HWND_DESKTOP, tree, &ht.pt, 1);
                  SendMessageW( tree, TVM_HITTEST, 0, (LPARAM)&ht );
                  if (TVHT_ONITEMLABEL & ht.flags)
                  {
                      TVITEM tvItem;
                      ZeroMemory(&tvItem, sizeof(tvItem));
                      tvItem.hItem = ht.hItem;
                      tvItem.mask = TVIF_PARAM;
                      tvItem.lParam = -1;
                      if (TreeView_GetItem(tree, &tvItem))
                      {
                          if (tvItem.lParam & DRIVER_MASK)
                          {
                              if (hPopupMenus)
                              {
                                  TrackPopupMenu(GetSubMenu(hPopupMenus, 0), TPM_RIGHTBUTTON, pt.x, pt.y, 0, tree, NULL);
                                  toConfigure = tvItem.lParam & ~DRIVER_MASK;
                              }
                          }
                          else if (tvItem.lParam & DEVICE_MASK)
                          {
                              /* FIXME TBD */
                          }

                      }
                  }
              }
	}
	break;

  case WM_INITDIALOG:
    initAudioDlg(hDlg);
    break;
  }

  return FALSE;
}
示例#24
0
int video_mode(int f, int w, int h)
{
    //senquack
    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);


    int stereo  = config_get_d(CONFIG_STEREO)      ? 1 : 0;
    int stencil = config_get_d(CONFIG_REFLECTION)  ? 1 : 0;
    int buffers = config_get_d(CONFIG_MULTISAMPLE) ? 1 : 0;
    int samples = config_get_d(CONFIG_MULTISAMPLE);
    int vsync   = config_get_d(CONFIG_VSYNC)       ? 1 : 0;
    int hmd     = config_get_d(CONFIG_HMD)         ? 1 : 0;
    int highdpi = config_get_d(CONFIG_HIGHDPI)     ? 1 : 0;

    int dpy = config_get_d(CONFIG_DISPLAY);

    int X = SDL_WINDOWPOS_CENTERED_DISPLAY(dpy);
    int Y = SDL_WINDOWPOS_CENTERED_DISPLAY(dpy);

    hmd_free();

    if (window)
    {
        SDL_GL_DeleteContext(context);
        SDL_DestroyWindow(window);
    }

    //senquack
//    SDL_GL_SetAttribute(SDL_GL_STEREO,             stereo);

    //senquack - disabled drawing shadows and reflections on GCW Zero, don't need a stencil buffer:
#ifdef GCWZERO
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,       0);
#endif

    //senquack - don't need or want these on GCW Zero:
#ifndef GCWZERO
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, buffers);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, samples);
#endif

    /* Require 16-bit double buffer with 16-bit depth buffer. */

   //senquack - GCW Zero port change
    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_BUFFER_SIZE,    32);
//    SDL_GL_SetAttribute(SDL_GL_RED_SIZE,     5);
//    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,   6);
//    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,    5);
//    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,    0);
//    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,    16);

    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,  16);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    //senquack
    SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

    /* Try to set the currently specified mode. */

    log_printf("Creating a window (%dx%d, %s)\n",
               w, h, (f ? "fullscreen" : "windowed"));

    //senquack DEBUG -  DO NOT RUN - loads GLES2.0 for some reason
//    SDL_VideoInit(NULL);

    window = SDL_CreateWindow("", X, Y, w, h,
                              SDL_WINDOW_OPENGL |
                              (highdpi ? SDL_WINDOW_ALLOW_HIGHDPI : 0) |
                              (f ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));

    if (window)
    {
        if ((context = SDL_GL_CreateContext(window)))
        {
            int buf, smp;

            SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &buf);
            SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &smp);

            /*
             * Work around SDL+WGL returning pixel formats below
             * minimum specifications instead of failing, thus
             * bypassing our fallback path. SDL tries to ensure that
             * WGL plays by the rules, but forgets about extended
             * context attributes such as multisample. See SDL
             * Bugzilla #77.
             */

            if (buf < buffers || smp < samples)
            {
                log_printf("GL context does not meet minimum specifications\n");
                SDL_GL_DeleteContext(context);
                context = NULL;
            }
        }
    }

    if (window && context)
    {
        set_window_title(TITLE);
        set_window_icon(ICON);

        /*
         * SDL_GetWindowSize can be unreliable when going fullscreen
         * on OSX (and possibly elsewhere). We should really be
         * waiting for a resize / size change event, but for now we're
         * doing this lazy thing instead.
         */

        if (f)
        {
            SDL_DisplayMode dm;

            if (SDL_GetDesktopDisplayMode(video_display(), &dm) == 0)
            {
                video.window_w = dm.w;
                video.window_h = dm.h;

//                //senquack
                dm.format = SDL_PIXELFORMAT_RGBA8888;
//    dm.format = SDL_PIXELFORMAT_RGB565;
                dm.w = 320;
                dm.h = 240;
                dm.refresh_rate = 60;
                dm.driverdata = 0;
                SDL_SetWindowDisplayMode(window, &dm);
                printf("setting new video dm..\n");
                SDL_GetCurrentDisplayMode(0, &dm);
                SDL_Log("Screen w: %d h: %d\n", dm.w, dm.h);
                SDL_Log("Screen bpp: %d\n", SDL_BITSPERPIXEL(dm.format));
                SDL_Log("Screen dm: ");
                SDL_Log("\n\n");
                SDL_Log("Vendor     : %s\n", glGetString(GL_VENDOR));
                SDL_Log("Renderer   : %s\n", glGetString(GL_RENDERER));
                SDL_Log("Version    : %s\n", glGetString(GL_VERSION));
                SDL_Log("Extensions : %s\n", glGetString(GL_EXTENSIONS));
                SDL_Log("\n");
                fflush(NULL);
            }
        }
        else
        {
            SDL_GetWindowSize(window, &video.window_w, &video.window_h);
        }

        if (highdpi)
        {
            SDL_GL_GetDrawableSize(window, &video.device_w, &video.device_h);
        }
        else
        {
            video.device_w = video.window_w;
            video.device_h = video.window_h;
        }

        video.device_scale = (float) video.device_h / (float) video.window_h;

        log_printf("Created a window (%u, %dx%d, %s)\n",
                   SDL_GetWindowID(window),
                   video.window_w, video.window_h,
                   (f ? "fullscreen" : "windowed"));

        config_set_d(CONFIG_DISPLAY,    video_display());
        config_set_d(CONFIG_FULLSCREEN, f);
        config_set_d(CONFIG_WIDTH,      video.window_w);
        config_set_d(CONFIG_HEIGHT,     video.window_h);

        SDL_GL_SetSwapInterval(vsync);

        if (!glext_init())
            return 0;

        glViewport(0, 0, video.device_w, video.device_h);
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

        glEnable(GL_NORMALIZE);
        glEnable(GL_CULL_FACE);
        glEnable(GL_DEPTH_TEST);
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_LIGHTING);
        glEnable(GL_BLEND);

#if !ENABLE_OPENGLES
        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL,
                      GL_SEPARATE_SPECULAR_COLOR);
#endif

        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glDepthFunc(GL_LEQUAL);

        /* If GL supports multisample, and SDL got a multisample buffer... */

        if (glext_check("ARB_multisample"))
        {
            SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &buffers);
            if (buffers) glEnable(GL_MULTISAMPLE);
        }

        /* Set up HMD display if requested. */

        if (hmd)
            hmd_init();

        /* Initialize screen snapshotting. */

        snapshot_init();

        video_show_cursor();

        /* Grab input immediately in HMD mode. */

        if (hmd_stat())
            SDL_SetWindowGrab(window, SDL_TRUE);

        return 1;
    }

    /* If the mode failed, try it without stereo. */

    else if (stereo)
    {
        config_set_d(CONFIG_STEREO, 0);
        return video_mode(f, w, h);
    }

    /* If the mode failed, try decreasing the level of multisampling. */

    else if (buffers)
    {
        config_set_d(CONFIG_MULTISAMPLE, samples / 2);
        return video_mode(f, w, h);
    }

    /* If that mode failed, try it without reflections. */

    else if (stencil)
    {
        config_set_d(CONFIG_REFLECTION, 0);
        return video_mode(f, w, h);
    }

    /* If THAT mode failed, punt. */

    return 0;
}
示例#25
0
int main(int argc, const char *const *argv) /* I'm const-crazy! */
{
	DUH *duh;          /* Encapsulates the music file. */
	AL_DUH_PLAYER *dp; /* Holds the current playback state. */

	/* Initialise Allegro */
	if (allegro_init())
		return EXIT_FAILURE;

	/* Check that we have one argument (plus the executable name). */
	if (argc != 2)
		usage(argv[0]);

	/* Tell Allegro where to find configuration data. This means you can
	 * put any settings for Allegro in dumb.ini. See Allegro's
	 * documentation for more information.
	 */
	set_config_file("dumb.ini");

	/* Initialise Allegro's keyboard input. */
	if (install_keyboard()) {
		allegro_message("Failed to initialise keyboard driver!\n");
		return EXIT_FAILURE;
	}

	/* This function call is appropriate for a program that will play one
	 * sample or one audio stream at a time. If you have sound effects
	 * too, you may want to increase the parameter. See Allegro's
	 * documentation for details on what the parameter means. Note that
	 * newer versions of Allegro act as if set_volume_per_voice() was
	 * called with parameter 1 initially, while older versions behave as
	 * if -1 was passed, so you should call the function if you want
	 * consistent behaviour.
	 */
	set_volume_per_voice(0);

	/* Initialise Allegro's sound output system. */
	if (install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL)) {
		allegro_message("Failed to initialise sound driver!\n%s\n", allegro_error);
		return EXIT_FAILURE;
	}

	/* dumb_exit() is a function defined by DUMB. This operation arranges
	 * for dumb_exit() to be called last thing before the program exits.
	 * dumb_exit() does a bit of cleaning up for you. atexit() is
	 * declared in stdlib.h.
	 */
	atexit(&dumb_exit);

	/* DUMB defines its own wrappers for file input. There is a struct
	 * called DUMBFILE that holds function pointers for the various file
	 * operations needed by DUMB. You can decide whether to use stdio
	 * FILE objects, Allegro's PACKFILEs or something else entirely. No
	 * wrapper is installed initially, so you must call this or
	 * dumb_register_stdfiles() or set up your own before trying to load
	 * modules by file name. (If you are using another method, such as
	 * loading an Allegro datafile with modules embedded in it, then DUMB
	 * never opens a file by file name so this doesn't apply.)
	 */
	dumb_register_packfiles();

	/* Load the module file into a DUH object. Quick and dirty: try the
	 * loader for each format until one succeeds. Note that 15-sample
	 * mods have no identifying features, so dumb_load_mod() may succeed
	 * on files that aren't mods at all. We therefore try that one last.
	 */
	duh = dumb_load_it(argv[1]);
	if (!duh) {
		duh = dumb_load_xm(argv[1]);
		if (!duh) {
			duh = dumb_load_s3m(argv[1]);
			if (!duh) {
				duh = dumb_load_mod(argv[1]);
				if (!duh) {
					allegro_message("Failed to load %s!\n", argv[1]);
					return EXIT_FAILURE;
				}
			}
		}
	}

	/* Read the quality values from the config file we told Allegro to
	 * use. You may want to hardcode these or provide a more elaborate
	 * interface via which the user can control them.
	 */
	dumb_resampling_quality = get_config_int("sound", "dumb_resampling_quality", 4);
	dumb_it_max_to_mix = get_config_int("sound", "dumb_it_max_to_mix", 128);

	/* If we're not in DOS, show a window and register our close hook
	 * function.
	 */
#	ifndef ALLEGRO_DOS
		{
			const char *fn = get_filename(argv[1]);
			gfx_half_width = strlen(fn);
			if (gfx_half_width < 22) gfx_half_width = 22;
			gfx_half_width = (gfx_half_width + 2) * 4;

			/* set_window_title() is not const-correct (yet). */
			set_window_title((char *)"DUMB Music Player");

			if (set_gfx_mode(GFX_DUMB_MODE, gfx_half_width*2, 80, 0, 0) == 0) {
				acquire_screen();
				textout_centre(screen, font, fn, gfx_half_width, 20, 14);
				textout_centre(screen, font, "Press any key to exit.", gfx_half_width, 52, 11);
				release_screen();
			} else
				gfx_half_width = 0;
		}

		/* Silly check to get around the fact that someone stupidly removed
		 * an old function from Allegro instead of deprecating it. The old
		 * function was put back a version later, but we may as well use the
		 * new one if it's there!
		 */
#		if ALLEGRO_VERSION*10000 + ALLEGRO_SUB_VERSION*100 + ALLEGRO_WIP_VERSION >= 40105
			set_close_button_callback(&closehook);
#		else
			set_window_close_hook(&closehook);
#		endif

#	endif

	/* We want to continue running if the user switches to another
	 * application.
	 */
	set_display_switch_mode(SWITCH_BACKGROUND);

	/* We have the music loaded, but it isn't playing yet. This starts it
	 * playing. We construct a second object, the AL_DUH_PLAYER, to
	 * represent the playing music. This means you can play the music
	 * twice at the same time should you want to!
	 *
	 * Specify the number of channels (2 for stereo), which 'signal' to
	 * play (always 0 for modules), the volume (1.0f for default), the
	 * buffer size (4096 generally works well) and the sampling frequency
	 * (ideally match the final output frequency Allegro is using). An
	 * Allegro audio stream will be started.
	 */
	dp = al_start_duh(duh, 2, 0, 1.0f,
		get_config_int("sound", "buffer_size", 4096),
		get_config_int("sound", "sound_freq", 44100));

	/* Register our callback functions so that they are called when the
	 * music loops or stops. See docs/howto.txt for more information.
	 * There is no threading issue: DUMB will only process playback
	 * in al_poll_duh(), which we call below.
	 */
	{
		DUH_SIGRENDERER *sr = al_duh_get_sigrenderer(dp);
		DUMB_IT_SIGRENDERER *itsr = duh_get_it_sigrenderer(sr);
		dumb_it_set_loop_callback(itsr, &loop_callback, NULL);
		dumb_it_set_xm_speed_zero_callback(itsr, &xm_speed_zero_callback, NULL);
	}

	/* Main loop. */
	for (;;) {
		/* Check for keys in the buffer. If we get one, discard it
		 * and exit the main loop.
		 */
		if (keypressed()) {
			readkey();
			break;
		}

		/* Poll the music. We exit the loop if al_poll_duh() has
		 * returned nonzero (music finished) or the window has been
		 * closed. al_poll_duh() might return nonzero if you have set
		 * up a callback that tells the music to stop.
		 */
		if (al_poll_duh(dp) || closed)
			break;

		/* Give other threads a look-in, or allow the processor to
		 * sleep for a bit. YIELD() is defined further up in this
		 * file.
		 */
		YIELD();
	}

	/* Remove the audio stream and deallocate the memory being used for
	 * the playback state. We set dp to NULL to emphasise that the object
	 * has gone.
	 */
	al_stop_duh(dp);
	dp = NULL;

	/* Free the DUH object containing the actual music data. */
	unload_duh(duh);
	duh = NULL;

	/* All done! */
	return EXIT_SUCCESS;
}
示例#26
0
static void
ncpstat_set_title(ncpstat_t *ss)
{
	set_window_title(ss->win, "NCP Service Response Time statistics");
}
示例#27
0
static void
fcstat_set_title(fcstat_t *fc)
{
	set_window_title(fc->win, "Fibre Channel Service Response Time statistics");
}
示例#28
0
int main()
{
    init();
    set_window_title("Team27, inc - Innocent Snake");
    srand((unsigned)time(NULL));

    //kondisi map awal
    int map[SIZE_Y][SIZE_X] = {-1,-1,-1,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,-1,-1,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,-1,-1, 0, 0, 0, 0,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1,-1,-1, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0,-1,-1,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-1,
                               -1,-1,-1,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1, 0, 0, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1
                              };

    int counter = 0;
    int posX, posY;
    int loaded = 0;
    int x_his, y_his;
    int i, j, moveX = 1, moveY = 0;

    BITMAP *buffer      = create_bitmap(SCREEN_W, SCREEN_H);
    BITMAP *path        = create_bitmap(OBJECT_SIZE, OBJECT_SIZE);
    BITMAP *wall        = load_bitmap("wall.bmp", NULL);
    BITMAP *head        = load_bitmap("head.bmp", NULL);
    BITMAP *snake_body  = load_bitmap("body.bmp", NULL);
    BITMAP *eat         = create_bitmap(OBJECT_SIZE, OBJECT_SIZE);
    BITMAP *bg_map      = create_bitmap(SCREEN_W, SCREEN_H);

    SNAKE  *snake       = NULL;
    SNAKE  *pointer     = NULL;

    clear_to_color(path, makecol(255, 255, 255)); //jalan berwarna putih
    clear_to_color(eat,  makecol(255, 255, 255)); //makanan backgroundnya putih
    circlefill(eat, OBJECT_SIZE/2, OBJECT_SIZE/2, OBJECT_SIZE/2 - 4, makecol(255, 0, 0)); //makanan berwarna merah

    //membuat map snake di bitmap
    for(i=0; i<SIZE_Y; i++)
    {
        for(j=0; j<SIZE_X; j++)
        {
            switch(map[i][j])
            {
            case PATH :
                draw_sprite(bg_map, path, j*OBJECT_SIZE, i*OBJECT_SIZE);
                break;
            case WALL :
                draw_sprite(bg_map, wall, j*OBJECT_SIZE, i*OBJECT_SIZE);
                break;
            }
        }
    }

    //inisialisasi awal posisi snake
    add_body(&snake, 3, 1, map);
    map[snake->y][snake->x] = HEAD;
    add_body(&snake, 2, 1, map);
    add_body(&snake, 1, 1, map);

    set_keyboard_rate(10, 10);

    while (!key[KEY_ESC])
    {
        //deteksi apakah sudah ada makanan di map
        if(loaded==0) {
            do {
                posX = rand()%(SIZE_X-1) + 1;
                posY = rand()%(SIZE_Y-1) + 1;
            } while(map[posY][posX] != PATH);
            map[posY][posX] = EAT;
            loaded = 1;
        }

        //deteksi keyboard yang ditekan dan mengubah arah gerak snake
        if(counter==5) {
            if(key[KEY_UP] && moveY==0)
            {
                moveX=0;
                moveY=-1;
                clear_keybuf();
            }
            else if(key[KEY_DOWN] && moveY==0)
            {
                moveX=0;
                moveY=1;
                clear_keybuf();
            }
            else if(key[KEY_LEFT] && moveX==0)
            {
                moveX=-1;
                moveY=0;
                clear_keybuf();
            }
            else if(key[KEY_RIGHT] && moveX==0)
            {
                moveX=1;
                moveY=0;
                clear_keybuf();
            }
            x_his = snake->x;
            y_his = snake->y;

            //kalau menabrak sesuatu maka keluar
            if(!move_snake(snake, moveX, moveY, map)) break;

            //jika bertemu makanan maka tambah badan
            if(map[posY][posX] != EAT)
            {
                add_body(&snake, x_his, y_his, map);
                loaded = 0;
            }
            counter=0;
        }
        counter++;

        //tempelkan semua obyek ke buffer
        draw_sprite(buffer, bg_map, 0, 0);
        draw_sprite(buffer, eat, posX*OBJECT_SIZE, posY*OBJECT_SIZE);
        for(pointer = snake; pointer != NULL; pointer = pointer->next)
        {
            switch(map[pointer->y][pointer->x])
            {
            case BODY :
                draw_sprite(buffer, snake_body, pointer->x*OBJECT_SIZE, pointer->y*OBJECT_SIZE);
                break;
            case HEAD :
                draw_sprite(buffer, head, pointer->x*OBJECT_SIZE, pointer->y*OBJECT_SIZE);
                break;
            }
        }

        //tampilkan buffer ke screen
        draw_sprite(screen, buffer, 0, 0);
        clear_bitmap(buffer);
        rest(10);
    }

    //destroy semua bitmap
    destroy_bitmap(head);
    destroy_bitmap(buffer);
    destroy_bitmap(path);
    destroy_bitmap(wall);
    destroy_bitmap(snake_body);
    destroy_bitmap(eat);

    deinit();
    return 0;
}
示例#29
0
int main(int argc, char *argv[])
{
	if (SDL_Init(SDL_INIT_VIDEO) != 0)
		return 1;

	//	Initialize the window.
	struct Window window;	
	if (initialize_window(&window) != 0)
		return 2;

	set_window_title(&window, "Stars and Moons");
	set_window_dimensions(&window, 50, 50, WINDOW_DEFAULT_WIDTH,
		WINDOW_DEFAULT_HEIGHT, WINDOW_DEFAULT_ASPECT_RATIO);

	//	Initializes with room for five images.
	//	TODO: Remove the hardcoded number.
	struct GraphicResources graphic_resources;
	if (initialize_graphic_resources(&graphic_resources, 5) != 0)
		return 3;

	int image_errors = 0;
	if ((image_errors = load_all_images(5, &graphic_resources, window.renderer)) != 0)
	{
		printf("Error loading %d image(s).\n", image_errors);
		return 4;		
	}

	//	Initialize game data.
	struct GameState game_state;
	if (initialize_game_state(&game_state, BOARD_ROWS, BOARD_COLS) != 0)
		return 5;

	set_game_player(&game_state, STAR);
	set_all_game_matrix_values(&game_state, GAME_STATE_SENTINEL);

	draw_window(&window, &game_state, &graphic_resources);

	int frames_counted = 0;

	int run_game = 1;
	while (run_game == 1)
	{
		++frames_counted;
		
		run_game = process_window_events(&window, &game_state, 
			&graphic_resources);
		draw_window(&window, &game_state, &graphic_resources);

		if (run_game == 2)
		{
			set_all_game_matrix_values(&game_state, GAME_STATE_SENTINEL);
			run_game = 1;

		}
	}	

	//	Calculate an estimate of the game's FPS.
	Uint32 time_since_start = SDL_GetTicks();
	int seconds = time_since_start / 1000;
	int fps = frames_counted / seconds;
	
	printf("Rendered %d frames in %lu seconds\n",
		frames_counted, time_since_start / 1000);
	printf("FPS = %d\n", fps);
	
	//	Free all the memories.
	destroy_game_state(&game_state);
	destroy_graphic_resources(&graphic_resources);
	destroy_window(&window);

	SDL_Quit();

    return 0;
}
示例#30
0
//Main codee
//
int main(void){

	int mapxoff, mapyoff;
	int oldpy, oldpx;
	int titleX, titleY;
	int facing = 0;
	int jump = JUMPIT;
	int n, VOLUME = 128, PAN = 128, PITCH = 1000;

	//general initialize
	allegro_init();

	install_timer();

	install_keyboard();

	set_color_depth(16);

	set_gfx_mode(MODE, WIDTH, HEIGHT, 0, 0);
	
	set_window_title(" . . .J.U.M.P.E.R. . .     :: Ryan Bridglal ::");


	
	//
	//sound init
	install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, "");

	//load title
	title = load_bitmap("title.bmp", NULL);
	
	//gameOver = load_bitmap("gameover.bmp", NULL);

	// load the player sprite
	temp = load_bitmap("player.bmp", NULL);
	for (n=0; n < 8; n++)
	player_image[n] = grabframe(temp, 50, 64, 0, 0, 8, n);
	destroy_bitmap(temp);


	// load the sound file
	music = load_sample("music.wav");
	
	//jumpSound = load_sample("jump.wav");

	// initialize the sprite
	player = new SPRITE;
	player->x = 80;
	player->y = 100;
	player->curframe = 0;
	player->framecount = 0;
	player->framedelay = 6;
	player->maxframe = 7;
	player->width = player_image[0]->w;
	player->height = player_image[0]->h;


	// load the map
	MapLoad("map.FMP");

	// create the double buffer
	buffer = create_bitmap(WIDTH, HEIGHT);
	clear(buffer);
	
	//always play background music
	play_sample(music, VOLUME, PAN, PITCH, FALSE);



	// main loop
	while(!key[KEY_ESC]) {
		
		oldpy = player->y;
		oldpx = player->x;


		//
		// PLAYER controls
		//
		//right keypress
		if (key[KEY_RIGHT]) {
			clear_to_color(title, makecol(80, 80, 248));
			facing = 1;
			player->x += 2;
			
			if (++player->framecount > player->framedelay) {
				player->framecount = 0;
				
				if (++player->curframe > player->maxframe)
					player->curframe = 1;
			}
		}
		
		
		//left keypress
		else if (key[KEY_LEFT]) {
			clear_to_color(title, makecol(80, 80, 248));
			facing = 0;
			player->x -= 2;
			
			if (++player->framecount > player->framedelay) {
				player->framecount = 0;
				
				if (++player->curframe > player->maxframe)
					player->curframe = 1;
			}
		}
		
		
		else player->curframe = 0;

		// handle jumping
		if (jump == JUMPIT){
		
			if (!collided(player->x + player->width/2, player->y + player->height + 5))
				jump = 0;

			if (key[KEY_SPACE]) 
				jump = 30;
			//play_sample(jumpSound, VOLUME, PAN, PITCH, FALSE);
			    
		}
		
		else {
		     	player->y -= jump/3;
		     	jump--;
		}

		if (jump < 0){
			
			if (collided(player->x + player->width/2, player->y + player->height)) {
				jump = JUMPIT;
				while (collided(player->x + player->width/2, player->y + player->height))
					player->y -= 2;
			}
		}
		
		
		///
		//collision detection
		// player collision detect with map
		if (!facing) {
		
			if (collided(player->x, player->y + player->height))
				player->x = oldpx;
		}
		
		else {
		
			if (collided(player->x + player->width, player->y + player->height))
				player->x = oldpx;
		}


		// update the map scroll position
		mapxoff = player->x + player->width/2 - WIDTH/2 + 10;
		mapyoff = player->y + player->height/2 - HEIGHT/2 + 10;

		// avoid moving beyond the map edge
		if (mapxoff < 0) 
			mapxoff = 0;
		
		if (mapxoff > (mapwidth * mapblockwidth - WIDTH))
			mapxoff = mapwidth * mapblockwidth - WIDTH;
		
		if (mapyoff < 0) 
			mapyoff = 0;
		
		if (mapyoff > (mapheight * mapblockheight - HEIGHT))
			mapyoff = mapheight * mapblockheight - HEIGHT;


		//
		//Draw things

		// draw the background tiles
		MapDrawBG(buffer, mapxoff, mapyoff, 0, 0, WIDTH - 1, HEIGHT - 1);

		// draw the foreground tiles
		MapDrawFG(buffer, mapxoff, mapyoff, 0, 0, WIDTH - 1, HEIGHT - 1, 0);

		// draw the player's sprite
		if (facing)
			draw_sprite(buffer, player_image[player->curframe], (player->x - mapxoff), (player->y - mapyoff));
		
		else
			draw_sprite_h_flip(buffer, player_image[player->curframe], (player->x - mapxoff), (player->y - mapyoff));


		//load title
		//draw_sprite(screen, title, 160, 20);
		 //draw_sprite(buffer, title[titleSprite->curframe], (title->titleX - mapxoff), (title->y - mapyoff));
		blit(title, screen, 0, 0, 0, 0, 640, 480);


		// blit the double buffer
		vsync();
		acquire_screen();
		blit(buffer, screen, 0, 0, 0, 0, WIDTH - 1, HEIGHT - 1);
		release_screen();


		
	}// endwhile
	//	else {
	//				blit(gameOver, screen, 0, 0, 0, 0, 640, 480); 
	//}

	gameOver();


	// clean up
	for (n = 0; n < 8; n++)
		destroy_bitmap(player_image[n]);
		delete player;
		delete title;

	//	for (n=0; n<NUM_SOUNDS; n++)
	//		destroy_sample(sounds[n]);


		destroy_sample(music);
	//	destroy_sample(jumpSound);
		destroy_bitmap(title);
		destroy_bitmap(buffer);
		
		MapFreeMem();

		remove_sound();
		allegro_exit();

		return 0;

}