Ejemplo n.º 1
0
void sdl_osd_interface::init(running_machine &machine)
{
	// call our parent
	osd_interface::init(machine);

	sdl_options &options = downcast<sdl_options &>(machine.options());
	const char *stemp;

	// determine if we are benchmarking, and adjust options appropriately
	int bench = options.bench();
	astring error_string;
	if (bench > 0)
	{
		options.set_value(OPTION_THROTTLE, false, OPTION_PRIORITY_MAXIMUM, error_string);
		options.set_value(OPTION_SOUND, false, OPTION_PRIORITY_MAXIMUM, error_string);
		options.set_value(SDLOPTION_VIDEO, "none", OPTION_PRIORITY_MAXIMUM, error_string);
		options.set_value(OPTION_SECONDS_TO_RUN, bench, OPTION_PRIORITY_MAXIMUM, error_string);
		assert(!error_string);
	}

	// Some driver options - must be before audio init!
	stemp = options.audio_driver();
	if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
	{
		mame_printf_verbose("Setting SDL audiodriver '%s' ...\n", stemp);
		osd_setenv(SDLENV_AUDIODRIVER, stemp, 1);
	}

	stemp = options.video_driver();
	if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
	{
		mame_printf_verbose("Setting SDL videodriver '%s' ...\n", stemp);
		osd_setenv(SDLENV_VIDEODRIVER, stemp, 1);
	}

#if (SDLMAME_SDL2)
		stemp = options.render_driver();
		if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
		{
			mame_printf_verbose("Setting SDL renderdriver '%s' ...\n", stemp);
			//osd_setenv(SDLENV_RENDERDRIVER, stemp, 1);
			SDL_SetHint(SDL_HINT_RENDER_DRIVER, stemp);
		}
#endif

	/* Set the SDL environment variable for drivers wanting to load the
	 * lib at startup.
	 */
#if USE_OPENGL
	/* FIXME: move lib loading code from drawogl.c here */

	stemp = options.gl_lib();
	if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
	{
		osd_setenv("SDL_VIDEO_GL_DRIVER", stemp, 1);
		mame_printf_verbose("Setting SDL_VIDEO_GL_DRIVER = '%s' ...\n", stemp);
	}
#endif

	/* get number of processors */
	stemp = options.numprocessors();

	osd_num_processors = 0;

	if (strcmp(stemp, "auto") != 0)
	{
		osd_num_processors = atoi(stemp);
		if (osd_num_processors < 1)
		{
			mame_printf_warning("Warning: numprocessors < 1 doesn't make much sense. Assuming auto ...\n");
			osd_num_processors = 0;
		}
	}

	/* Initialize SDL */

	if (!SDLMAME_INIT_IN_WORKER_THREAD)
	{
#if (SDLMAME_SDL2)
		if (SDL_InitSubSystem(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
#else
		if (SDL_Init(SDL_INIT_TIMER|SDL_INIT_AUDIO| SDL_INIT_VIDEO| SDL_INIT_JOYSTICK|SDL_INIT_NOPARACHUTE)) {
#endif
			mame_printf_error("Could not initialize SDL %s\n", SDL_GetError());
			exit(-1);
		}
		osd_sdl_info();
	}
	// must be before sdlvideo_init!
	machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(osd_exit), &machine));

	defines_verbose();

	if (!SDLMAME_HAS_DEBUGGER)
		if (machine.debug_flags & DEBUG_FLAG_OSD_ENABLED)
		{
			mame_printf_error("sdlmame: -debug not supported on X11-less builds\n\n");
			osd_exit(machine);
			exit(-1);
		}

	if (sdlvideo_init(machine))
	{
		osd_exit(machine);
		mame_printf_error("sdlvideo_init: Initialization failed!\n\n\n");
		fflush(stderr);
		fflush(stdout);
		exit(-1);
	}

	sdlinput_init(machine);
	sdlaudio_init(machine);
	sdloutput_init(machine);

#ifdef SDLMAME_NETWORK
	sdlnetdev_init(machine);
#endif

	if (options.oslog())
		machine.add_logerror_callback(output_oslog);

	/* now setup watchdog */

	int watchdog_timeout = options.watchdog();
	int str = options.seconds_to_run();

	/* only enable watchdog if seconds_to_run is enabled *and* relatively short (time taken from ui.c) */
	if ((watchdog_timeout != 0) && (str > 0) && (str < 60*5 ))
	{
		m_watchdog = auto_alloc(machine, watchdog);
		m_watchdog->setTimeout(watchdog_timeout);
	}

#if (SDLMAME_SDL2)
	SDL_EventState(SDL_TEXTINPUT, SDL_TRUE);
#else
	SDL_EnableUNICODE(SDL_TRUE);
#endif
}

#if defined(SDLMAME_UNIX) && (!defined(SDLMAME_EMSCRIPTEN))
#define POINT_SIZE 144.0

#ifdef SDLMAME_MACOSX

#define EXTRA_HEIGHT 1.0
#define EXTRA_WIDTH 1.15

//-------------------------------------------------
//  font_open - attempt to "open" a handle to the
//  font with the given name
//-------------------------------------------------

osd_font sdl_osd_interface::font_open(const char *_name, int &height)
{
	CFStringRef font_name = NULL;
	CTFontRef ct_font = NULL;
	CTFontDescriptorRef font_descriptor;
	CGAffineTransform affine_transform = CGAffineTransformIdentity;

	astring name(_name);

	if (name == "default")
	{
		name = "LucidaGrande";
	}

	/* handle bdf fonts in the core */
	if (name.len() > 4)
		if (name.makeupper().substr(name.len()-4,4) == ".BDF" )
			return NULL;

	font_name = CFStringCreateWithCString( NULL, _name, kCFStringEncodingUTF8 );

	if( font_name != NULL )
	{
		font_descriptor = CTFontDescriptorCreateWithNameAndSize( font_name, POINT_SIZE );

		if( font_descriptor != NULL )
		{
			ct_font = CTFontCreateWithFontDescriptor( font_descriptor, POINT_SIZE, &affine_transform );

			CFRelease( font_descriptor );
		}
	}

	CFRelease( font_name );

	if (!ct_font)
	{
		printf("WARNING: Couldn't find/open font %s, using MAME default\n", name.cstr());
		return NULL;
	}

	CFStringRef real_name = CTFontCopyPostScriptName( ct_font );
	char real_name_c_string[255];
	CFStringGetCString ( real_name, real_name_c_string, 255, kCFStringEncodingUTF8 );
	mame_printf_verbose("Matching font: %s\n", real_name_c_string);
	CFRelease( real_name );

	CGFloat line_height = 0.0;
	line_height += CTFontGetAscent(ct_font);
	line_height += CTFontGetDescent(ct_font);
	line_height += CTFontGetLeading(ct_font);
	height = ceilf(line_height * EXTRA_HEIGHT);

	return (osd_font)ct_font;
}
Ejemplo n.º 2
0
int main( int argc, char *argv[] )
{
	AVFormatContext *pFormatCtx;
	int				i, audioStream;
	AVCodecContext	*pCodecCtx;
	AVCodec			*pCodec;
	AVPacket		*packet;
	uint8_t			*out_buffer;
	AVFrame			*pFrame;
	SDL_AudioSpec	wanted_spec;
	int ret;
	uint32_t len = 0;
	int got_picture;
	int index = 0;
	int64_t in_channel_layout;
	struct SwrContext* au_conert_ctx;

	FILE* pFile = NULL;
	char url[] = "F:/video/6s_kapian.flv";

	av_register_all();
	pFormatCtx = avformat_alloc_context();

	//Open
	if( avformat_open_input(&pFormatCtx, url, NULL, NULL) != 0 )
	{
		printf("Couldn't open input stream.\n");
		return -1;
	}

	//Find Stream information
	if( avformat_find_stream_info(pFormatCtx, NULL) < 0 )
	{
		printf("Couldn't find stream information.\n");
		return -1;
	}
	//Dump valid information into standard error
	av_dump_format(pFormatCtx, 0, url, false);

	//Find the first audio stream
	audioStream = -1;
	for( i = 0; i < pFormatCtx->nb_streams; ++i	)
		if( pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO )
		{
			audioStream = i;
			break;
		}

	if( audioStream == -1 )
	{
		printf("Didn't find a audio stream.\n");
		return -1;
	}

	//Get a pointer to the codec contex for the audio stream
	pCodecCtx = pFormatCtx->streams[audioStream]->codec;

	//Find the decoder for the audio stream
	pCodec = avcodec_find_decoder( pCodecCtx->codec_id );

	if( pCodec == NULL )
	{
		printf("Codec not found.\n");
		return -1;
	}

	//Open codec
	if( avcodec_open2(pCodecCtx, pCodec, NULL) < 0 )
	{
		printf("Could not open codec.\n");
		return -1;
	}

#if OUTPUT_PCM
	pFile=fopen("output.pcm", "wb");
#endif

	packet = (AVPacket *)av_malloc( sizeof(packet) );
	av_init_packet(packet);

	//Out Audio Param
	uint64_t out_channel_layout = AV_CH_LAYOUT_STEREO;
	//nb_samples:
	int out_nb_samples = pCodecCtx->frame_size;
	AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
	int out_sample_rate = 44100;
	int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);

	//Out buffer size
	int out_buffer_size = av_samples_get_buffer_size( NULL, out_channels, out_nb_samples, out_sample_fmt, 1 );

	out_buffer = (uint8_t *)av_malloc( MAX_AUDIO_FRAME_SIZE );
	pFrame = av_frame_alloc();

	//SDL------------------
#if USE_SDL
	//Init
	if(SDL_Init( SDL_INIT_AUDIO | SDL_INIT_TIMER)) {  
		printf( "Could not initialize SDL - %s\n", SDL_GetError()); 
		return -1;
	}
	//SDL_AudioSpec
	wanted_spec.freq = out_sample_rate; 
	wanted_spec.format = AUDIO_S16SYS; 
	wanted_spec.channels = out_channels; 
	wanted_spec.silence = 0; 
	wanted_spec.samples = out_nb_samples; 
	wanted_spec.callback = fill_audio; 
	wanted_spec.userdata = pCodecCtx; 

	if (SDL_OpenAudio(&wanted_spec, NULL)<0){ 
		printf("can't open audio.\n"); 
		return -1; 
	} 
#endif

	in_channel_layout = av_get_default_channel_layout(pCodecCtx->channels);
	//swr

	au_conert_ctx = swr_alloc();
	au_conert_ctx = swr_alloc_set_opts( au_conert_ctx, out_channel_layout, out_sample_fmt, out_sample_rate,
		in_channel_layout, pCodecCtx->sample_fmt, pCodecCtx->sample_rate, 0, NULL);
	swr_init(au_conert_ctx);

	while( av_read_frame(pFormatCtx, packet) >= 0 ){
		if( packet->stream_index == audioStream ){
			ret = avcodec_decode_audio4(pCodecCtx, pFrame, &got_picture, packet);
			if( ret < 0 ){
				printf("Error in decoding audio frame.\n");
				return -1;
			}//end if
			if( got_picture > 0 ){
				swr_convert( au_conert_ctx, &out_buffer, MAX_AUDIO_FRAME_SIZE, (const uint8_t **)pFrame->data, pFrame->nb_samples );
#if 1
				printf("index:%5d\t pts:%lld\t packet size:%d\n",index,packet->pts,packet->size);
#endif
#if OUTPUT_PCM
				//Write PCM
				fwrite(out_buffer, 1, out_buffer_size, pFile);
#endif
				index++;
			}//end if
#if USE_SDL
			while(audio_len>0)//Wait until finish
				SDL_Delay(1); 

			//Set audio buffer (PCM data)
			audio_chunk = (Uint8 *) out_buffer; 
			//Audio buffer length
			audio_len =out_buffer_size;
			audio_pos = audio_chunk;

			//Play
			SDL_PauseAudio(0);
#endif
		}//end if
		av_free_packet(packet);
	}//end while

	swr_free(&au_conert_ctx);

#if USE_SDL
	SDL_CloseAudio();//Close SDL
	SDL_Quit();
#endif
	// Close file
#if OUTPUT_PCM
	fclose(pFile);
#endif
	av_free(out_buffer);
	// Close the codec
	avcodec_close(pCodecCtx);
	// Close the video file
	avformat_close_input(&pFormatCtx);

	return 0;
}
Ejemplo n.º 3
0
int main(int argc, char *argv[])
{
	const SDL_VideoInfo *info;
	int i;
	SDL_Rect **modes;
	char driver[128];

	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr,
			"Couldn't initialize SDL: %s\n", SDL_GetError());
		exit(1);
	}
	if ( SDL_VideoDriverName(driver, sizeof(driver)) ) {
		printf("Video driver: %s\n", driver);
	}
	info = SDL_GetVideoInfo();
	printf(
"Current display: %d bits-per-pixel\n",info->vfmt->BitsPerPixel);
	if ( info->vfmt->palette == NULL ) {
		printf("	Red Mask = 0x%.8x\n", info->vfmt->Rmask);
		printf("	Green Mask = 0x%.8x\n", info->vfmt->Gmask);
		printf("	Blue Mask = 0x%.8x\n", info->vfmt->Bmask);
	}
	/* Print available fullscreen video modes */
	modes = SDL_ListModes(NULL, SDL_FULLSCREEN);
	if ( modes == (SDL_Rect **)0 ) {
		printf("No available fullscreen video modes\n");
	} else
	if ( modes == (SDL_Rect **)-1 ) {
		printf("No special fullscreen video modes\n");
	} else {
		printf("Fullscreen video modes:\n");
		for ( i=0; modes[i]; ++i ) {
			printf("\t%dx%dx%d\n", modes[i]->w, modes[i]->h, info->vfmt->BitsPerPixel);
		}
	}
	if ( info->wm_available ) {
		printf("A window manager is available\n");
	}
	if ( info->hw_available ) {
		printf("Hardware surfaces are available (%dK video memory)\n",
			info->video_mem);
	}
	if ( info->blit_hw ) {
		printf(
"Copy blits between hardware surfaces are accelerated\n");
	}
	if ( info->blit_hw_CC ) {
		printf(
"Colorkey blits between hardware surfaces are accelerated\n");
	}
	if ( info->blit_hw_A ) {
		printf(
"Alpha blits between hardware surfaces are accelerated\n");
	}
	if ( info->blit_sw ) {
		printf(
"Copy blits from software surfaces to hardware surfaces are accelerated\n");
	}
	if ( info->blit_sw_CC ) {
		printf(
"Colorkey blits from software surfaces to hardware surfaces are accelerated\n");
	}
	if ( info->blit_sw_A ) {
		printf(
"Alpha blits from software surfaces to hardware surfaces are accelerated\n");
	}
	if ( info->blit_fill ) {
		printf(
"Color fills on hardware surfaces are accelerated\n");
	}

	if ( argv[1] && (strcmp(argv[1], "-benchmark") == 0) ) {
		RunVideoTests();
	}

	SDL_Quit();
	return(0);
}
Ejemplo n.º 4
0
int main(int argc, char** argv)
{
	if(argc != 2)
		usage(argv[0]);

	FILE* infile = fopen(argv[1], "r");
	if(infile == NULL)
	{
		perror("Error opening input file");
		return EXIT_FAILURE;
	}
	System* sys = load_system(infile);
	if(sys == NULL)
	{
		printf("Loading input file failed\n");
		return EXIT_FAILURE;
	}
	init_simulation(sys);
	state.sys = sys;
	state.views = malloc(sys->nplanets * sizeof(PlanetView));
	for(int i = 0; i < sys->nplanets; i++)
		state.views[i].radius = pow(sys->planets[i].mass / DENSITY_FACTOR, 1.0f/3.0f);
	state.scale = 1.0f;
	Vector* fst_pos = &sys->planets[0].position;
	vector_copy(state.pos, *fst_pos);
	state.pos[1] += 1.1f*get_planet_radius(0);
	state.pos[0] -= get_planet_radius(0);
	state.rot_x = 90.0f;
	state.locked_planet = -1;
	state.hours_per_sec = DEFAULT_SIMULATION_SPEED;
	state.time_step = sys->time_step;
	state.paused = true;
	state.trails_enabled = true;

	if(SDL_Init(SDL_INIT_VIDEO) < 0)
		die("SDL initialization failed");
	atexit(SDL_Quit);
	const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
	if(!videoInfo)
		die("Could not get video information");
	int videoFlags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE | SDL_HWSURFACE | SDL_HWACCEL;

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags);
	if(!surface)
	{
		printf("Surface creation failed, trying to disable anti-aliasing...\n");
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
		surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags);
	}
	if(!surface)
		die("Changing video mode failed");

	init_gl();
	init_viewport();
	SDL_ShowCursor(0);
	SDL_WM_GrabInput(SDL_GRAB_ON);

	SDL_Event event;
	while(SDL_PollEvent(&event))
		;  /* ignore spurious mouse events at startup */

	bool window_is_active = true;
	int step = 0;
	while (true)
	{
		Uint32 next_update = SDL_GetTicks() + FRAME_INTERVAL;
		while (SDL_PollEvent(&event))
		{
			switch(event.type)
			{
				case SDL_ACTIVEEVENT:
					window_is_active = event.active.gain;
					break;			    
				case SDL_VIDEORESIZE:
					surface = SDL_SetVideoMode(event.resize.w,
							event.resize.h,
							SCREEN_BPP, videoFlags);
					if(!surface)
						die("Lost video surface during resize");
					init_viewport();
					break;
				case SDL_KEYDOWN:
					handle_keypress(&event.key.keysym);
					break;
				case SDL_MOUSEMOTION:
					handle_mouse(&event.motion);
					break;
				case SDL_QUIT:
					goto out;
				default:
					break;
			}
		}
		update();
		if(window_is_active)
		{
			draw_scene();
			glFlush();
			SDL_GL_SwapBuffers();
		}
		if(!state.paused)
		{
			for(int i = 0; i < (state.hours_per_sec * 3600.0f / FRAME_INTERVAL) / state.time_step; i++)
			{
				if((step % TRAILS_INTERVAL) == 0)
					update_trails();
				simulate_one_step(sys, step++, state.time_step);
			}
		}
		Sint32 delta = next_update - SDL_GetTicks();
		if(delta > 0)
			SDL_Delay(delta);
	}
out:

	return 0;
}
Ejemplo n.º 5
0
int main(int, char**) {
	if (SDL_Init(SDL_INIT_VIDEO) != 0) {
		printf("SDL_Init Error: %s\n", SDL_GetError());
		return 1;
	}

	SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 800, 400, SDL_WINDOW_SHOWN);
	if (win == nullptr) {
		printf("SDL_CreateWindow Error: %s\n", SDL_GetError());
		SDL_Quit();
		return 1;
	}

	SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	assert(ren);

	SDL_Texture* texture = SDL_CreateTexture(ren, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, WIDTH, HEIGHT);
	assert(texture);

	OledSim oled(WIDTH, HEIGHT);
	Renderer display;
	display.Attach(WIDTH, HEIGHT, oled.Buffer());

	SDL_SetRenderDrawColor(ren, 128, 128, 128, 255);

	UIRenderData data;
	data.volume = 2;
	data.power = 3;
	data.mVolts = 3219;
	data.fontName = "Bespin";

	DotStarUI::Test();

	SDL_Event e;
	int scale = 4;
	int mode = 0;
	int count = 0;
	uint32_t lastUpdate = SDL_GetTicks();

	const char* FONT_NAMES[8] = {
		"Bespin", "Vader", "Vader", "ObiAni", "Bespin", "JainaSw", "Maul", "MAUL"
	};
	uint8_t COLORS[8] = { 0, 255, 100, 200, 255, 0, 20, 120 };
	data.color.set(COLORS[0], COLORS[1], COLORS[2]);

	int palette = 0;

	while (true) {
		SDL_PollEvent(&e);
		if (e.type == SDL_QUIT) {
			break;
		}
		else if (e.type == SDL_KEYDOWN) {
			if (e.key.keysym.sym >= SDLK_1 && e.key.keysym.sym <= SDLK_8) {
				scale = e.key.keysym.sym - SDLK_0;
			}
			else if (e.key.keysym.sym == SDLK_SPACE) {
				mode = (mode + 1) % Sketcher::NUM_MODES;
			}
			else if (e.key.keysym.sym == SDLK_p) {
				data.power = (data.power + 1) % 5;
				data.mVolts = 3000 + data.power * 111;
			}
			else if (e.key.keysym.sym == SDLK_v) {
				data.volume = (data.volume + 1) % 5;
			}
			else if (e.key.keysym.sym == SDLK_c) {
				palette = (palette + 1) % 8;
				data.color.set(COLORS[(palette * 3 + 0) % 8],
					COLORS[(palette * 2 + 1) % 8],
					COLORS[(palette * 5 + 2) % 8]);
				data.fontName = FONT_NAMES[palette];
				data.palette = palette;
			}
		}

		uint32_t t = SDL_GetTicks();
		if (t - lastUpdate > 100) {
			lastUpdate = t;
			uint8_t value = int(127.8 * (sin(count * 0.2) + 1.0));
			++count;
			sketcher.Push(value);
			sketcher.Draw(&display, 100, mode, &data);
		}

		oled.Commit();

		const SDL_Rect src = { 0, 0, WIDTH, HEIGHT };
		SDL_Rect winRect;
		SDL_GetWindowSize(win, &winRect.w, &winRect.h);
		const int w = WIDTH * scale;
		const int h = HEIGHT * scale;
		SDL_Rect dst = { (winRect.w - w) / 2, (winRect.h - h) / 2, w, h };

		SDL_UpdateTexture(texture, NULL, oled.Pixels(), WIDTH * 4);
		SDL_RenderClear(ren);
		SDL_RenderCopy(ren, texture, &src, &dst);
		SDL_RenderPresent(ren);
	}
	SDL_Quit();
	return 0;
}
Ejemplo n.º 6
0
void displayThread(void)
{
#ifdef LOCAL_DISPLAY
	SDL_Window *win = NULL;
	SDL_Renderer *renderer = NULL;
	SDL_Texture *texture = NULL;
	SDL_Event e;
	int kill = FALSE;
	char resolution[20] = {0};
#else
	FILE *fp = NULL;
#endif
	char *lineseeker = NULL;
	int linecnt = 0;
	int prevline = 0;
	int prevframe = 0;
	int flag = 0;
	VIDEO_DATA *popped = NULL;
	int frame_cnt = 0;

	popped = (VIDEO_DATA *)calloc(1, sizeof(VIDEO_DATA));
	popped->packetbuff = (char *)calloc(1, packetsize - VALID_DATA);
#ifdef LOCAL_DISPLAY
	SDL_Init(SDL_INIT_VIDEO);
	snprintf(resolution, 20, "Receiver : %dx%d", g_capture_width,
		 g_capture_height);
	win = SDL_CreateWindow(resolution,
			SDL_WINDOWPOS_CENTERED,
			SDL_WINDOWPOS_CENTERED,
			g_capture_width,
			g_capture_height,
			SDL_WINDOW_RESIZABLE);

	renderer = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
	texture = SDL_CreateTexture(renderer,
			SDL_PIXELFORMAT_YUY2,
			SDL_TEXTUREACCESS_STREAMING,
			g_capture_width,
			g_capture_height);
#else
	fp = fopen(g_filename, "wb");
#endif
	while(!KillDisplayThread) {
		if((sizeofqueue() > 0) && (g_displaybuff)) {
			poppacket(popped);
		} else {
			continue;
		}

		if(flag == 0) {
			g_skipframe = popped->frame_num;
			prevframe = popped->frame_num;
			pr_dbg("Frame %d is going to skip\n",g_skipframe);
			flag = 1;
		}
#if 0
		/* check SDL event if any */
		if (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT) {
				break;
			} else if(e.key.type == SDL_KEYUP) {
				switch(e.key.keysym.sym) {
					case SDLK_ESCAPE:
						kill = TRUE;
						break;
					default:
						break;
				}
				if(kill) break;
			}
		}
#endif
		if(g_skipframe == popped->frame_num) {
			continue;
		}
		if(popped->line_num == FIRST_LINE) {
			lineseeker = g_displaybuff;
			memcpy(lineseeker, popped->packetbuff,
			       packetsize - VALID_DATA);
			lineseeker += (packetsize - VALID_DATA);
			linecnt ++;
			prevline = FIRST_LINE;
		} else if(popped->line_num == g_last_line) {
			memcpy(lineseeker, popped->packetbuff,
			       packetsize - VALID_DATA);
			linecnt++;
			if(linecnt == g_last_line) {
#ifdef LOCAL_DISPLAY
				/* display frame*/
				SDL_UpdateTexture(texture, 0,
						g_displaybuff,
						g_capture_width*BPP);
				SDL_RenderClear(renderer);
				SDL_RenderCopy(renderer, texture, NULL, NULL);
				SDL_RenderPresent(renderer);
#else
				/* save frame */
				fwrite(g_displaybuff, buffsize, 1, fp);
				if(frame_cnt++ > no_of_frames_to_save) {
					fclose(fp);
					exit(0);
				}
#endif
			}
			lineseeker = g_displaybuff;
			linecnt = 0;
			prevline = 0;
		} else if(prevframe == popped->frame_num) {
			if(popped->line_num == prevline + 1) {
				memcpy(lineseeker, popped->packetbuff,
				       packetsize - VALID_DATA);
				lineseeker += packetsize - VALID_DATA;
				linecnt ++;
			}
			prevline = popped->line_num;
		} else {
			memset(g_displaybuff, 0, buffsize);
			lineseeker = g_displaybuff;
			linecnt = 0;
			g_skipframe = popped->frame_num;
			prevline = popped->line_num;
		}
		if(prevframe != popped->frame_num) {
			prevframe = popped->frame_num;
		}
	}
#ifdef LOCAL_DISPLAY
	SDL_DestroyTexture(texture);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(win);
	SDL_Quit();
#else
	fclose(fp);
#endif
	free(popped->packetbuff);
	free(popped);
	pr_dbg("Exiting Application\n");
	exit(0);
}
Ejemplo n.º 7
0
bool createSurface() //unsigned int display_width, unsigned int display_height)
{
    if(!display_width || !display_height)
    {
        bool success = graphics_get_display_size(0, &display_width, &display_height); //0 = LCD

        if(success < 0)
        {
            std::cerr << "Error getting display size!\n";
            return false;
        }
    }
    std::cout << display_width << "x" << display_height << "...";

    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0)
    {
        std::cerr << "Error initializing SDL!\n";
        std::cerr << SDL_GetError() << "\n";
        std::cerr << "Are you in the 'video' and 'input' groups? Is X closed? Is your firmware up to date? Are you using at least the 192/64 memory split?\n";
        return false;
    }

    sdlScreen = SDL_SetVideoMode(1, 1, 0, SDL_SWSURFACE);
    if(sdlScreen == NULL)
    {
        std::cerr << "Error creating SDL window for input!\n";
        return false;
    }

    //have to reload config to re-open SDL joysticks
    InputManager::loadConfig();



    std::cout << "Creating surface...";

    DISPMANX_ELEMENT_HANDLE_T dispman_element;
    DISPMANX_DISPLAY_HANDLE_T dispman_display;
    DISPMANX_UPDATE_HANDLE_T dispman_update;
    VC_RECT_T dst_rect;
    VC_RECT_T src_rect;



    display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if(display == EGL_NO_DISPLAY)
    {
        std::cerr << "Error getting display!\n";
        return false;
    }

    bool result = eglInitialize(display, NULL, NULL);
    if(result == EGL_FALSE)
    {
        std::cerr << "Error initializing display!\n";
        return false;
    }

    result = eglBindAPI(EGL_OPENGL_ES_API);
    if(result == EGL_FALSE)
    {
        std::cerr << "Error binding API!\n";
        return false;
    }


    static const EGLint config_attributes[] =
    {
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_NONE
    };

    GLint numConfigs;
    result = eglChooseConfig(display, config_attributes, &config, 1, &numConfigs);

    if(result == EGL_FALSE)
    {
        std::cerr << "Error choosing config!\n";
        return false;
    }


    context = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL);
    if(context == EGL_NO_CONTEXT)
    {
        std::cout << "Error: " << eglGetError() << "\n";

        std::cerr << "Error getting context!\n";
        return false;
    }

    dst_rect.x = 0;
    dst_rect.y = 0;
    dst_rect.width = display_width;
    dst_rect.height = display_height;

    src_rect.x = 0;
    src_rect.y = 0;
    src_rect.width = display_width << 16;
    src_rect.height = display_height << 16;

    dispman_display = vc_dispmanx_display_open(0); //0 = LCD
    dispman_update = vc_dispmanx_update_start(0);

    dispman_element = vc_dispmanx_element_add(dispman_update, dispman_display, 0 /*layer*/, &dst_rect, 0 /*src*/, &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0 /*clamp*/, DISPMANX_NO_ROTATE /*transform*/);

    nativewindow.element = dispman_element;
    nativewindow.width = display_width;
    nativewindow.height = display_height;
    vc_dispmanx_update_submit_sync(dispman_update);




    surface = eglCreateWindowSurface(display, config, &nativewindow, NULL);
    if(surface == EGL_NO_SURFACE)
    {
        std::cerr << "Error creating window surface!\n";
        return false;
    }

    result = eglMakeCurrent(display, surface, surface, context);
    if(result == EGL_FALSE)
    {
        std::cerr << "Error with eglMakeCurrent!\n";
        return false;
    }


    std::cout << "success!\n";

    return true;
}
Ejemplo n.º 8
0
void jfSDLWindow::createWindow( jfUint32 width, 
		jfUint32 height, 
		jfUint32 bpp, 
		bool fullscreen, 
		const jfString& title)
{

	if( SDL_Init( SDL_INIT_VIDEO ) != 0 )
	{
		std::stringstream out;
		out<<"Couldn't initialize SDL:"<< SDL_GetError();
        jfLog(JF_LOG_ERROR, out.str());
		assert(0 && "Couldn't initialize SDL");
	}

	//all values are "at least"!
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	// Set the title.
	SDL_WM_SetCaption(title.c_str(), title.c_str());

	// Flags tell SDL about the type of window we are creating.
	int flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWSURFACE | SDL_OPENGLBLIT | SDL_HWPALETTE;

	if(fullscreen)
	{
		flags |= SDL_FULLSCREEN;
	}

	m_Screen = SDL_SetVideoMode( width, height, bpp, flags );

    if ( m_Screen == NULL )
	{
		std::stringstream out;
		out<<"Couldn't set %dx%dx%d video mode:"<<width<<height<<bpp<< SDL_GetError();
        jfLog(JF_LOG_ERROR, out.str());
		assert(0 && "Couldn't set %dx%dx%d video mode:");
    }

    SDL_FillRect(m_Screen, NULL, SDL_MapRGBA(m_Screen->format,0,0,0,0));

	//SDL doesn't trigger off a ResizeEvent at startup, but as we need this for OpenGL, we do this ourself
	SDL_Event resizeEvent;
	resizeEvent.type = SDL_VIDEORESIZE;
	resizeEvent.resize.w = width;
	resizeEvent.resize.h = height;

	SDL_PushEvent(&resizeEvent);

	//Init glew
	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		std::stringstream out;
		out<<"Couldn't initialize GLEW:"<< glewGetErrorString(err);
        jfLog(JF_LOG_ERROR, out.str());
		assert(0 && "Couldn't initialize GLEW");
	}
}
Ejemplo n.º 9
0
bool Game::Init(const char* title, int xpos, int ypos, int width, int height,
		int flags) {

	// attempt to initialize SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) == 0) {
		Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 10000);

//		 init the window

		m_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
		if (m_pWindow != 0) // window init success
				{
			m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);
			if (m_pRenderer != 0) // renderer init success
					{
				SDL_SetRenderDrawColor(m_pRenderer, 255, 255, 255, 255);

			} else {
				return false; // renderer init fail
			}
		} else {
			return false; // window init fail
		}
	} else {
		return false; // SDL init fail
	}

	m_bRunning = true; // everything inited successfully,
//		start the main loop
			//initial game State
	SDL_Surface* temp = IMG_Load("images/GameBackground.png");

//Create texture from surface pixels
	m_BackGroundTexture = SDL_CreateTextureFromSurface(m_pRenderer, temp);
	SDL_FreeSurface(temp);

	SoundsBank::sound = new SoundsBank();
	SoundsBank::sound->initSoundEffect("sounds/hover.wav");
	SoundsBank::sound->initSoundEffect("sounds/connect.wav");
	SoundsBank::sound->initSoundEffect("sounds/button-24.wav");
	SoundsBank::sound->initSoundEffect("sounds/removeCards.wav");

	StateManager::stateMachine = new StateManager();
	StateManager::stateMachine->setCurrentGameStates(MENU);

	Timer::g_Timer = new Timer();

	StartMenu.InitSatistics(m_pRenderer);
	StartMenu.Init(m_pRenderer);
	StartMenu.InitRules(m_pRenderer);

	m_buttonsMenu.Init(m_pRenderer);
	for (int iter = 0; iter < 5; iter++) {
		m_buttonsMenu.setSource(iter * 232, 0, 232, 52);
		m_buttonsMenu.setDestination(100, (250 + 60 * iter), 260, 50);

		m_buttonSet.push_back(m_buttonsMenu);
	}
	PlayButton = m_buttonSet.at(0);
	PlayButton.setSource(0, 0, 232, 52);
	PlayButton.setDestination(410, 684, 240, 60);

	m_buttonSet.at(4).setDestination(25, 699, 150, 45);

	m_cardLogic.Init(m_pRenderer);

	txtTimer.Set(513, 50, 30, 40, " ");
	txtTimer.setTextColor(255, 255, 0, 255);

	gameOver.Set(512, 150, 30, 40, " ");
	gameOver.setTextColor(255, 255, 0, 255);

	level.Set(790, 50, 30, 40, " ");
	level.setTextColor(255, 255, 0, 255);

//	**************
	bet.Set(950, 702, 30, 40, " ");
	bet.setTextColor(255, 255, 0, 255);
	bet.IntToTextMessage(5);

	credit.Set(295, 704, 25, 35, " ");
	credit.setTextColor(255, 255, 0, 255);

	profit.Set(790, 702, 30, 40, " ");
	profit.setTextColor(255, 255, 0, 255);

//	***********************************

	m_statTxtClicks.Set(155, 60, 18, 22, " ");
	m_statTxtClicks.setTextColor(255, 255, 0, 255);

	m_statTxtLevelStatus.Set(240, 35, 18, 22, " ");
	m_statTxtLevelStatus.setTextColor(255, 255, 0, 255);

	m_statTxtSeconds.Set(155, 90, 18, 22, " ");
	m_statTxtSeconds.setTextColor(255, 255, 0, 255);

	m_statTxtLevelNumber.Set(155, 35, 18, 22, " ");
	m_statTxtLevelNumber.setTextColor(255, 255, 0, 255);

	m_stat.createFile();
	m_Recovery.createRecoverFile();

	return true;

}/*end of Init*/
Ejemplo n.º 10
0
void I_InitGraphics(void)
{
    SDL_Event dummy;
    byte *doompal;
    char *env;

    // Pass through the XSCREENSAVER_WINDOW environment variable to 
    // SDL_WINDOWID, to embed the SDL window into the Xscreensaver
    // window.

    env = getenv("XSCREENSAVER_WINDOW");

    if (env != NULL)
    {
        char winenv[30];
        int winid;

        sscanf(env, "0x%x", &winid);
        M_snprintf(winenv, sizeof(winenv), "SDL_WINDOWID=%i", winid);

        putenv(winenv);
    }

    SetSDLVideoDriver();
    SetWindowPositionVars();

    if (SDL_Init(SDL_INIT_VIDEO) < 0) 
    {
        I_Error("Failed to initialize video: %s", SDL_GetError());
    }

    // Set up title and icon.  Windows cares about the ordering; this
    // has to be done before the call to SDL_SetVideoMode.

    I_InitWindowTitle();
    I_InitWindowIcon();

    // Warning to OS X users... though they might never see it :(
#ifdef __MACOSX__
    if (fullscreen)
    {
        printf("Some old versions of OS X might crash in fullscreen mode.\n"
               "If this happens to you, switch back to windowed mode.\n");
    }
#endif

    //
    // Enter into graphics mode.
    //
    // When in screensaver mode, run full screen and auto detect
    // screen dimensions (don't change video mode)
    //

    if (screensaver_mode)
    {
        SetVideoMode(NULL, 0, 0);
    }
    else
    {
        int w, h;

        if (autoadjust_video_settings)
        {
            I_AutoAdjustSettings();
        }

        w = screen_width;
        h = screen_height;

        screen_mode = I_FindScreenMode(w, h);

        if (screen_mode == NULL)
        {
            I_Error("I_InitGraphics: Unable to find a screen mode small "
                    "enough for %ix%i", w, h);
        }

        if (w != screen_mode->width || h != screen_mode->height)
        {
            printf("I_InitGraphics: %s (%ix%i within %ix%i)\n",
                   WindowBoxType(screen_mode, w, h),
                   screen_mode->width, screen_mode->height, w, h);
        }

        SetVideoMode(screen_mode, w, h);
    }

    // Start with a clear black screen
    // (screen will be flipped after we set the palette)

    SDL_FillRect(screenbuffer, NULL, 0);

    // Set the palette

    doompal = W_CacheLumpName(DEH_String("PLAYPAL"), PU_CACHE);
    I_SetPalette(doompal);
    SDL_SetColors(screenbuffer, palette, 0, 256);

    CreateCursors();

    UpdateFocus();
    UpdateGrab();

    // On some systems, it takes a second or so for the screen to settle
    // after changing modes.  We include the option to add a delay when
    // setting the screen mode, so that the game doesn't start immediately
    // with the player unable to see anything.

    if (fullscreen && !screensaver_mode)
    {
        SDL_Delay(startup_delay);
    }

    // Check if we have a native surface we can use
    // If we have to lock the screen, draw to a buffer and copy
    // Likewise if the screen pitch is not the same as the width
    // If we have to multiply, drawing is done to a separate 320x200 buf

    native_surface = screen == screenbuffer
                  && !SDL_MUSTLOCK(screen)
                  && screen_mode == &mode_scale_1x
                  && screen->pitch == SCREENWIDTH
                  && aspect_ratio_correct;

    // If not, allocate a buffer and copy from that buffer to the
    // screen when we do an update

    if (native_surface)
    {
	I_VideoBuffer = (unsigned char *) screen->pixels;

        I_VideoBuffer += (screen->h - SCREENHEIGHT) / 2;
    }
    else
    {
	I_VideoBuffer = (unsigned char *) Z_Malloc (SCREENWIDTH * SCREENHEIGHT, 
                                                    PU_STATIC, NULL);
    }

    V_RestoreBuffer();

    // Clear the screen to black.

    memset(I_VideoBuffer, 0, SCREENWIDTH * SCREENHEIGHT);

    // We need SDL to give us translated versions of keys as well

    SDL_EnableUNICODE(1);

    // Repeat key presses - this is what Vanilla Doom does
    // Not sure about repeat rate - probably dependent on which DOS
    // driver is used.  This is good enough though.

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    // clear out any events waiting at the start and center the mouse
  
    while (SDL_PollEvent(&dummy));

    initialized = true;

    // Call I_ShutdownGraphics on quit

    I_AtExit(I_ShutdownGraphics, true);
}
Ejemplo n.º 11
0
gboolean hello_world_init (HelloWorld* self) {
	gboolean result = FALSE;
	gint _tmp0_ = 0;
	gint _tmp3_ = 0;
	gboolean _tmp6_ = FALSE;
	SDL_Window* _tmp8_ = NULL;
	SDL_Window* _tmp9_ = NULL;
	SDL_Window* _tmp12_ = NULL;
	SDL_Renderer* _tmp13_ = NULL;
	SDL_Renderer* _tmp14_ = NULL;
	SDL_Renderer* _tmp17_ = NULL;
	gint imgInitFlags = 0;
	gint initResult = 0;
	gint _tmp18_ = 0;
	gint _tmp19_ = 0;
	gint _tmp20_ = 0;
	gint _tmp21_ = 0;
	gint _tmp22_ = 0;
	g_return_val_if_fail (self != NULL, FALSE);
	_tmp0_ = SDL_Init ((guint32) SDL_INIT_VIDEO);
	if (_tmp0_ < 0) {
		FILE* _tmp1_ = NULL;
		const gchar* _tmp2_ = NULL;
		_tmp1_ = stdout;
		_tmp2_ = SDL_GetError ();
		fprintf (_tmp1_, "SDL could not initialize! SDL Error: %s\n", _tmp2_);
		result = FALSE;
		return result;
	}
	_tmp3_ = IMG_Init ((gint) IMG_INIT_PNG);
	if (_tmp3_ < 0) {
		FILE* _tmp4_ = NULL;
		const gchar* _tmp5_ = NULL;
		_tmp4_ = stdout;
		_tmp5_ = IMG_GetError ();
		fprintf (_tmp4_, "SDL_image could not initialize! SDL_image Error: %s\n", _tmp5_);
		result = FALSE;
		return result;
	}
	_tmp6_ = SDL_SetHint ("SDL_RENDER_SCALE_QUALITY", "1");
	if (!_tmp6_) {
		FILE* _tmp7_ = NULL;
		_tmp7_ = stdout;
		fputs ("Warining: Linear texture filtering not enabled!", _tmp7_);
	}
	_tmp8_ = SDL_CreateWindow ("SDL Tutorial", (gint) SDL_WINDOWPOS_CENTERED_MASK, (gint) SDL_WINDOWPOS_CENTERED_MASK, HELLO_WORLD_SCREEN_WIDTH, HELLO_WORLD_SCREEN_HEIGHT, (guint32) SDL_WINDOW_SHOWN);
	_SDL_DestroyWindow0 (self->priv->window);
	self->priv->window = _tmp8_;
	_tmp9_ = self->priv->window;
	if (_tmp9_ == NULL) {
		FILE* _tmp10_ = NULL;
		const gchar* _tmp11_ = NULL;
		_tmp10_ = stdout;
		_tmp11_ = SDL_GetError ();
		fprintf (_tmp10_, "Window could not be created! SDL Error: %s\n", _tmp11_);
		result = FALSE;
		return result;
	}
	_tmp12_ = self->priv->window;
	_tmp13_ = SDL_CreateRenderer (_tmp12_, -1, (guint32) SDL_RENDERER_ACCELERATED);
	_SDL_DestroyRenderer0 (self->priv->renderer);
	self->priv->renderer = _tmp13_;
	_tmp14_ = self->priv->renderer;
	if (_tmp14_ == NULL) {
		FILE* _tmp15_ = NULL;
		const gchar* _tmp16_ = NULL;
		_tmp15_ = stdout;
		_tmp16_ = SDL_GetError ();
		fprintf (_tmp15_, "Renderer could not be created! SDL Error: %s\n", _tmp16_);
		result = FALSE;
		return result;
	}
	_tmp17_ = self->priv->renderer;
	SDL_SetRenderDrawColor (_tmp17_, (guint8) 0xFF, (guint8) 0xFF, (guint8) 0xFF, (guint8) SDL_ALPHA_OPAQUE);
	imgInitFlags = (gint) IMG_INIT_PNG;
	_tmp18_ = imgInitFlags;
	_tmp19_ = IMG_Init (_tmp18_);
	initResult = _tmp19_;
	_tmp20_ = initResult;
	_tmp21_ = imgInitFlags;
	_tmp22_ = imgInitFlags;
	if ((_tmp20_ & _tmp21_) != _tmp22_) {
		FILE* _tmp23_ = NULL;
		const gchar* _tmp24_ = NULL;
		_tmp23_ = stdout;
		_tmp24_ = IMG_GetError ();
		fprintf (_tmp23_, "SDL_image could not initialize! SDL_image Error: %s\n", _tmp24_);
		result = FALSE;
		return result;
	}
	result = TRUE;
	return result;
}
Ejemplo n.º 12
0
/////////////////////////////////////////////////////////
// createGemWindow
//
/////////////////////////////////////////////////////////
GEM_EXTERN int createGemWindow(WindowInfo &info, WindowHints &hints)
{
  static int firstTime = 1;
  if (firstTime) {
    SDL_Init(SDL_INIT_VIDEO);
    firstTime = 0;
  }

  if (! hints.actuallyDisplay) {
    return(1);
  }

  int w = hints.width;
  int h = hints.height;
  int x = hints.x_offset;
  int y = hints.y_offset;
  bool fullscreen = (hints.fullscreen != 0);
  bool border = (hints.border != 0);

  info.win = SDL_CreateWindow(hints.title, x, y, w, h
    , SDL_WINDOW_OPENGL
    | SDL_WINDOW_RESIZABLE
    | (fullscreen ? SDL_WINDOW_FULLSCREEN : 0)
    | (border ? 0 : SDL_WINDOW_BORDERLESS)
    );
  info.fs = fullscreen;

  if (! info.win)  {
    error("GEM: Unable to create window");
    return(0);
  }

// Emscripten doesn't support shared contexts yet
#if 0
  if (hints.shared) {
    if (SDL_GL_MakeCurrent(info.win, hints.shared)) {
      error("GEM: Unable to make shared OpenGL context current: %s", SDL_GetError());
      destroyGemWindow(info);
      return(0);
    }
    SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
  }
#endif
  info.context = SDL_GL_CreateContext(info.win);
#if 0
  if (! info.context) {
    error("GEM: Unable to create OpenGL context: %s", SDL_GetError());
    SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0);
    destroyGemWindow(info);
    return(0);
  }
  SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0);
#endif

  if (SDL_GL_MakeCurrent(info.win, info.context)) {
    error("GEM: Unable to make OpenGL context current: %s", SDL_GetError());
    destroyGemWindow(info);
    return(0);
  }

  if (fullscreen) {
    SDL_RaiseWindow(info.win);
  }

  return(1);
}
Ejemplo n.º 13
0
/**
 *\fn int main(int argc, char *argv[])
 * Main
 *\param[in,out] argc argc
 *\param[in,out] argv argv
 */
int main(int argc, char *argv[])
{
    SDL_Surface *screen = NULL;

    int go = 1;
    int ret,ret1, ret2 = 0, ret3, ret4;

    char level_name[MAX_SIZE_FILE_NAME];
    char player_name[MAX_SIZE_FILE_NAME];
    int nb_lvl;
    /*sound*/
    Sound *sound_system;
    sound_system = createSound();

    /*keyboard config*/
    SDLKey kc[NB_KEY-1];

    /*input*/
    Input in;

    SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_JOYSTICK);

    Player *current_player;

    current_player = (Player *)malloc(sizeof(Player));

    /*screen initialization*/
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);

    initInput(&in);

    /*configurations loading */
    loadSoundOptions("configuration/sound.conf",sound_system);


    SDL_WM_SetCaption("Super Martin", NULL); //window name

    SDL_ShowCursor(SDL_DISABLE); //delete the mouse

    while (go) //main loop
    {
        if(titleMenu(screen,&go,sound_system, &in))
        {

            while( (ret3 = menuPlayers(screen, player_name, &go, sound_system, &in)) != -1 && go)
            {
                switch(ret3)
                {
                    case -1:
                        break;
                    case 2  :
                        ret2 = newPlayer(screen, player_name, sound_system, &go);
                        if(ret2 == 1)
                        {
                            current_player->levelMax = 1;
                            current_player->nbCoins = 0;
                            current_player->nbLifes = 3;
                            current_player->nbProjectile = 5;
                            savePlayer("save/.save", player_name, current_player);
                            loadInputOptions("default",kc,&in);
                            saveInputOptions(player_name, kc, &in);
                        }
                        else
                            break;

                    case 1  :
                        loadPlayer("save/.save", player_name, current_player);
                        loadInputOptions(player_name,kc,&in);
                        while(go && (ret1 = mainMenu(screen,&go,sound_system, player_name, &in)) != -1)
                        {
                            switch(ret1)
                            {
                                case -1:
                                    break;
                                case 0:

                                    while( (ret4 = menuLevel(screen,level_name,sound_system, player_name, current_player, &go, &nb_lvl, &in)) != -1 && go)
                                    {
                                        while(play(screen,level_name,sound_system,&go,kc, &in, current_player, player_name, ret4+1, nb_lvl) && go);
                                    }
                                    break;

                                case 1 :
                                    save(screen, "save/.save", player_name, current_player, &go);
                                    loadPlayer("save/.save", player_name, current_player);
                                    break;

                                case 2 :
                                    while((ret = optionMenu(screen,&go,sound_system,kc, &in)) != -1 && go)
                                    {
                                        switch(ret)
                                        {
                                            case -1:
                                                break;
                                            case 0:
                                                soundOptions(screen,&go,sound_system, &in);
                                                break;
                                            case 1:
                                                keyBoardOptions(screen,&go,kc,&in,player_name);
                                                break;
                                            default:;
                                        }
                                    }
                                    break;

                                case 3 :
                                    deletePlayer(screen, "save/players", player_name);
                                    go = 0;
                                    break;

                                default: ;
                            }
                        }
                        go = 1;
                        break;

                    default : ;

                }
            }

        }

        SDL_FillRect(screen,NULL,SDL_MapRGB(screen->format,255,255,255)); //clear screen

        SDL_Flip(screen);
    }


    freeSound(sound_system);
    free((void*)current_player);
    freeInput(&in);
    SDL_Quit();

    return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
    SDL_Surface *screen = NULL;
    SDL_Surface *image = NULL;
    SDL_Surface *rot = NULL;
    const SDL_VideoInfo *videoInfo = NULL;
    FILE* file;
    double scale;
    int value;
    int prevValue = 0;
    int rc = 0;
    void *status[2];

    pthread_t thread[2]; 

    pthread_mutex_init(&mutexRW, NULL);

    pthread_create(&thread[0], NULL, run_thread, NULL);   

    /*-----------------------------------------------------------------*/

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        fprintf(stderr, "SDL_Init failed - %s\n", SDL_GetError());
        return 1;
    }

    /*-----------------------------------------------------------------*/

    videoInfo = SDL_GetVideoInfo();

    if (videoInfo == 0)
    {
        fprintf(stderr, "SDL_GetVideoInfo failed - %s\n", SDL_GetError());
        SDL_Quit();
        return 1;
    }

    /*-----------------------------------------------------------------*/

    rc = pthread_join(thread[0], &status[0]);

    //image = IMG_LoadPNG_RW(getImage());

    image = IMG_LoadPNG_RW(rw);

    //scale = (image->h)/(videoInfo->current_h);
    scale = 0.5;

    /*-----------------------------------------------------------------*/
while(1){
    //pthread_mutex_init(&mutexRW, NULL);

    pthread_create(&thread[0], NULL, run_thread, NULL);

    value = getHeight();

    //drawScreen(image, value, prevValue, scale, videoInfo);

    if (value != image->h) {
        //scale = (image->w)/(videoInfo->current_w);
        scale = 0.5;
	if (prevValue != image->h) {
	    screen = SDL_SetVideoMode((image->h)*scale,
		                      (image->w)*scale,
		                      videoInfo->vfmt->BitsPerPixel,
		                      SDL_SWSURFACE|SDL_DOUBLEBUF);
	}
        rot = rotozoomSurface( image, 90, scale, SMOOTHING_ON );
    }

    if (value == image->h) {
	//scale = (image->h)/(videoInfo->current_h);
        scale = 0.5;
	if (prevValue != image->h) {
	    screen = SDL_SetVideoMode((image->w)*scale,
		                      (image->h)*scale,
		                      videoInfo->vfmt->BitsPerPixel,
		                      SDL_SWSURFACE|SDL_DOUBLEBUF);
	}
        rot = rotozoomSurface( image, 0, scale, SMOOTHING_ON );
    }

    SDL_FreeSurface(image);

    /*if (!image)
    {
        fprintf(stderr, "IMG_LoadBMP_RW failed - %s\n", IMG_GetError());
        SDL_Quit();
        //return 1;
    }*/

    SDL_BlitSurface(rot, NULL, screen, 0);

    SDL_Flip(screen);

    SDL_FreeSurface(rot);

    prevValue = value;

    rc = pthread_join(thread[0], &status[0]);

    //image = IMG_LoadPNG_RW(getImage());
    image = IMG_LoadPNG_RW(rw);

    //SDL_FreeSurface(rw);

}

    //SDL_Delay(5000);

    SDL_Quit();

    return 0;
}
Ejemplo n.º 15
0
int emulate(smn8_rom *rom)
{
	SDL_Window *window;
	SDL_Surface *screen;
#ifdef HAVE_AUDIO
	SDL_AudioSpec audio_spec;
#endif
	smn8_vm vm;
	emulator_state state;

#ifdef HAVE_AUDIO
	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
#else
	if(SDL_Init(SDL_INIT_VIDEO) != 0)
#endif
	{
		fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError());
		return EXIT_FAILURE;
	}

#ifdef HAVE_AUDIO
	SDL_zero(audio_spec);

	audio_spec.freq = 22050;
	audio_spec.format = AUDIO_U16;
	audio_spec.channels = 2;
	audio_spec.samples = 4096;
	audio_spec.callback = audio;

	if(SDL_OpenAudio(&audio_spec, NULL) != 0)
	{
		fprintf(stderr, "Failed to initialize SDL audio: %s\n", SDL_GetError());
		SDL_Quit();
		return EXIT_FAILURE;
	}
#endif

	window = SDL_CreateWindow("SMN8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
									  WIDTH, HEIGHT, 0);

	if(window == NULL)
	{
		fprintf(stderr, "Failed to create SDL Window: %s\n", SDL_GetError());
#ifdef HAVE_AUDIO
		SDL_CloseAudio();
#endif
		SDL_Quit();
		return EXIT_FAILURE;
	}

	SDL_SetHint(SDL_HINT_FRAMEBUFFER_ACCELERATION, "1");

	screen = SDL_GetWindowSurface(window);
	if(screen == NULL)
	{
		fprintf(stderr, "Failed to get a valid SDL Surface: %s\n", SDL_GetError());
		SDL_DestroyWindow(window);
#ifdef HAVE_AUDIO
		SDL_CloseAudio();
#endif
		SDL_Quit();
		return EXIT_FAILURE;
	}

	state.colors[COLOR_BG] = SDL_MapRGB(screen->format, 0x00, 0x00, 0x00);

#ifdef HAVE_LIME
	state.colors[COLOR_FG] = SDL_MapRGB(screen->format, 0x00, 0xFF, 0x00);
#else
	state.colors[COLOR_FG] = SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF);
#endif

	SDL_FillRect(screen, NULL, state.colors[COLOR_BG]);

	state.vm = &vm;
	state.screen = screen;
	state.window = window;
#ifndef __EMSCRIPTEN__
	state.ticks = SDL_GetTicks();
#endif

	if(!smn8_vm_init(&vm, rom))
	{
		smn8_vm_clear(&vm);
		SDL_DestroyWindow(window);
#ifdef HAVE_AUDIO
		SDL_CloseAudio();
#endif
		SDL_Quit();
	}

#ifdef __EMSCRIPTEN__
	emscripten_set_main_loop_arg(tick, &state, 0, 1);
#else
	for(;;)
	{
		if(!tick(&state))
			break;
	}

	smn8_vm_clear(&vm);

	SDL_DestroyWindow(window);
#ifdef HAVE_AUDIO
	SDL_CloseAudio();
#endif

	SDL_Quit();
#endif
	return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
int main( int argc, char *argv[] )
{
    int done = 0;
    
    vre_result result;

    SDL_Surface *screen;

    vre_canvas  canvas;
    vre_tile    tile;
    vre_style   style;

    vre_context *pContext;
	
	vre_polygon *pPoly;
	vre_polygon *pPolyOut;
	vre_polygon *pPolyTmp;
	
	vre_rectangle rect;
	
	vre_bezier *pBezier;
	vre_bezier *pBezier2;
	
	vre_uint32 i;
                 
    vre_point   bezier[3] = 
    {
        {50<<16, 200<<16},
        {300<<16, 10<<16},
        {450<<16, 380<<16}
    };
    
    vre_point   bezier2[4] =
    {
        {150<<16, 100<<16},
        {300<<16, 0<<16},
        {450<<16, 400<<16},
        {10<<16, 50<<16}   
    };

    vre_point   points[6] = 
    {
        {850<<8, 75<<8},
        {958<<8, 137<<8},
        {958<<8, 262<<8},
        {850<<8, 325<<8},        
        {742<<8, 262<<8},
        {742<<8, 137<<8}    
    };

    vre_point   star[10] =
    {
        {350<<8,75<<8},
        {379<<8,161<<8},
        {469<<8,161<<8},
        {397<<8,215<<8},
        {423<<8,301<<8}, 
        {350<<8,250<<8}, 
        {277<<8,301<<8}, 
        {303<<8,215<<8}, 
        {231<<8,161<<8}, 
        {321<<8,161<<8}
    };


        // 
    if( SDL_Init(SDL_INIT_VIDEO) <0 )
    {
        printf("Unable to init SDL: %s\n", SDL_GetError());
        return 1;
    }

    screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE|SDL_DOUBLEBUF);

    if ( screen == NULL )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    SDL_LockSurface(screen); 


    result = vre_create_context (&pContext);
    if ( result != VRE_ERR_OK )
    {
        printf ("Error creating vre engine");
        return -1;
    }

    result = vre_create_bezier ( &pBezier, 3 );
    result = vre_create_bezier ( &pBezier2, 4 );
    
    vre_bezier_set_points ( pBezier, bezier, 3 );
    vre_bezier_set_points ( pBezier2, bezier2, 4 );


    // Draw Polygons 
    canvas.width = 640;
    canvas.height = 480;
    canvas.scanline_width = screen->pitch;
    canvas.pData = screen->pixels;
    
    tile.x = 0;
    tile.y = 0;
    tile.w = 640;
    tile.h = 480;
    tile.scanline_width = screen->pitch;
    tile.pData = screen->pixels;
    
    vre_start_render (pContext, &canvas);

// vre_polygon_convex (pContext, points, 6);
// vre_polygon_convex (pContext, star, 10);

    vre_set_stroke_width (pContext, 5);
	
	vre_polygon_create ( &pPoly, star, 10 );
	
	vre_polygon_create2 ( &pPolyOut, 100 );	
		              
    vre_set_foreground_color (pContext, 20, 150, 50);  
    vre_set_stroke_width (pContext, 2);

    vre_bezier_flatten ( pBezier, pPolyOut, 300, 0, 0 );   
    vre_polyline (pContext, pPolyOut->pVertices, pPolyOut->num_vertices);
    
    vre_bezier_flatten ( pBezier2, pPolyOut, 1000, 0, 0 );
    vre_polyline (pContext, pPolyOut->pVertices, pPolyOut->num_vertices);
                            

    SDL_UnlockSurface(screen);    

    SDL_Flip(screen);    

    while(done == 0)
    {
        while ( SDL_PollEvent(&event) )
        {
            if ( event.type == SDL_QUIT )  
            {  
                done = 1;  
            }
        }
    }
    
    SDL_Quit();
    return 0;
}
Ejemplo n.º 17
0
extern "C" int main(int argc, char *argv[])
{
    init();
	srand (time(NULL)); // SEDING RAND
	SDL_Window * gwindow = NULL;
	SDL_Surface * gsurface = NULL;
	SDL_Surface * human_image = NULL;
	SDL_Surface * zombie_image = NULL;
	SDL_Surface * human_colony_image = NULL;
	SDL_Surface * zombie_nest_image = NULL;
	SDL_Surface * background = NULL;
	SDL_Surface * food_source_image = NULL;
	
	// making the window and setting the surface
	
	bool success = true;
	
	if (SDL_Init(SDL_INIT_VIDEO)<0) { cout << "SDL not initialized!! Error : " << SDL_GetError()<<endl; success = false;}
	
	else
	{
		gwindow = SDL_CreateWindow("ZAS",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,SCREEN_WIDTH, SCREEN_HEIGHT,SDL_WINDOW_SHOWN);
		
		if( gwindow == NULL)
		{
			success = false;
			cout << " Error : "<< SDL_GetError()<<endl;
			
		}
		else
		{
			gsurface = SDL_GetWindowSurface (gwindow);
		}
	}
	
	if (!success )
	{
		cout << "FAILED TO INITIALIZE!"<<endl;		
	}
	
    // loading images
	success = true;
	
	background = SDL_LoadBMP ("background.bmp");
	human_colony_image = SDL_LoadBMP ("human_colony_image.bmp");
	zombie_nest_image = SDL_LoadBMP ("zombie_nest_image.bmp");
	human_image = SDL_LoadBMP ("human_image.bmp");
	zombie_image = SDL_LoadBMP ("zombie_image.bmp");
	food_source_image = SDL_LoadBMP ("food_source_image.bmp");
	
	
	if ( human_image == NULL|| zombie_image == NULL|| human_colony_image == NULL||zombie_nest_image == NULL||background == NULL||food_source_image == NULL)
	{
		cout << " Error : " << SDL_GetError() <<endl;
		success = false;
	}
	
	
	if (! success )
	{
		cout << "FAILED TO LOAD MEDIA!!!" <<endl;
	}
	else
	{
		cout << "Loaded images successfully!"<<endl;
	}
	
	SDL_BlitSurface (background, NULL, gsurface, NULL);
	
	SDL_Rect hcpos,znpos,fspos;
	hcpos.x = h.pos.x;
	hcpos.y = h.pos.y;
	SDL_BlitSurface (human_colony_image, NULL, gsurface, &hcpos);
	fspos.x = f.x;
	fspos.y = f.y;
	SDL_BlitSurface (food_source_image, NULL, gsurface, &fspos);
	//pos2.x = z.pos.x;
	//pos2.y = z.pos.y;
	//SDL_BlitSurface (zombie_nest_image, NULL, gsurface, &pos2);
	

	
	/***********************************************************************/
	
	
	init_grid();
	init_human_list();
	init_zombie_list();


	// actually blitting the image	
		bool quit = false;
		
		while (!quit)
		{   
			SDL_Event e;
			
			while ( SDL_PollEvent(&e) != 0)
			{
				if (e.type == SDL_QUIT)
				{
					quit = true;
				}
			}

			cout << "Entered change state" << endl;
		    change_state();

			cout << "Exited change state" << endl;
			
			vector<human>::iterator tempith;

			vector<zombie>::iterator tempitz;
			for (tempith = H.begin(); tempith!= H.end(); tempith ++)
			{
				
				SDL_Rect temp_pos;
				temp_pos.x = tempith->pos.x;
				temp_pos.y = tempith->pos.y;
			
				
				SDL_BlitSurface (human_image, NULL, gsurface, &temp_pos);

			}
			
			cout << " "<< H[0].pos.x << " " << H[0].pos.y << endl;
			for (tempitz = Z.begin(); tempitz!= Z.end(); tempitz ++)
			{
				SDL_Rect temp_pos;
				temp_pos.x = tempitz->pos.x;
				temp_pos.y = tempitz->pos.y;

				//cout << "Zombie Positions " << "x :" << temp_pos.x << " y : " << temp_pos.y <<endl; 

				
			
				
				SDL_BlitSurface (zombie_image, NULL, gsurface, &temp_pos);

			}
			cout << "food at colony "<< h.food_amount << endl; 

			
			SDL_Delay(10);
		
		
			/*
			//SDL_BlitSurface (zombie_nest_image, NULL, gsurface, &pos2);
			SDL_BlitSurface (background, NULL, gsurface, NULL);
			SDL_BlitSurface (human_colony_image, NULL, gsurface, &hcpos);
			SDL_BlitSurface (food_source_image, NULL, gsurface, &fspos);
			*/
			
		SDL_UpdateWindowSurface(gwindow);
	    }

		
	
	
	
	// closing the stuff
	SDL_FreeSurface(background);
	background = NULL;
	SDL_FreeSurface(human_colony_image);
	human_colony_image = NULL;
	SDL_FreeSurface(zombie_nest_image);
	zombie_nest_image = NULL;
	SDL_FreeSurface(human_image);
	human_image = NULL;
	SDL_FreeSurface(zombie_image);
	zombie_image = NULL;
	SDL_FreeSurface(food_source_image);
	food_source_image = NULL;
	
	SDL_DestroyWindow(gwindow);
	gwindow = NULL;
	SDL_Quit();
	

}
Ejemplo n.º 18
0
int main(int argc, char **argv)
{
    /* SDL SEtup */
    if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
    {
        fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
        exit(1);
    }
    atexit(SDL_Quit);

    SDL_Surface *surface;

    surface = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_HWSURFACE);
    if ( surface == NULL )
    {
        fprintf(stderr, "Could not setup screen to resolution %dx%d : %s\n", 
                WIDTH, HEIGHT, SDL_GetError());
        exit(1);
    }

    /* Initialize variables */
    double complex center = START_POS;
    double zoom = START_ZOOM;

    sdl_draw_mandelbrot(surface, center, zoom);

    SDL_Event event;
    while(1)
    {
        SDL_PollEvent(&event);
        switch (event.type)
        {
            case SDL_QUIT:
                exit(0);
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym == ' ')
                {
                    center = START_POS;
                    zoom = START_ZOOM;
                    sdl_draw_mandelbrot(surface, center, zoom);
                }
                else if (event.key.keysym.sym == SDLK_ESCAPE)
                {
                    exit(0);
                }
                break;
            case SDL_MOUSEBUTTONDOWN:
                center = creal(center) + ((event.button.x - (WIDTH/2))/zoom) +
                         ((cimag(center) + ((event.button.y - (HEIGHT/2))/zoom))
                          *_Complex_I);

                if (event.button.button == 1)
                    zoom *= ZOOM_FACTOR;
                else if (event.button.button == 3)
                    zoom /= ZOOM_FACTOR;

                sdl_draw_mandelbrot(surface, center, zoom);
                break;
        }
    }

    return 0;
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
	// Initializing and loading variables
	SDL_Window *window = nullptr;
	SDL_Surface *windowSurface = nullptr;
	SDL_Surface *image1 = nullptr; 
	SDL_Surface *image2 = nullptr; 
	SDL_Surface *image3 = nullptr;
	SDL_Surface *currentImage = nullptr;

	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);

	SDL_Joystick *joystick = SDL_JoystickOpen(0);
	
	std::cout << "Controller Name: " << SDL_JoystickName(joystick) << std::endl; 
	std::cout << "Num Axes: " << SDL_JoystickNumAxes(joystick) << std::endl; 
	std::cout << "Num Buttons: " << SDL_JoystickNumButtons(joystick) << std::endl;
	
	window = SDL_CreateWindow("SDL CodingMadeEasy Series", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
	windowSurface = SDL_GetWindowSurface(window);

	image1 = SDL_LoadBMP("test.bmp"); 
	image2 = SDL_LoadBMP("test1.bmp"); 
	image3 = SDL_LoadBMP("test2.bmp"); 

	currentImage = image1;

	bool isRunning = true; 
	SDL_Event ev;

	while(isRunning)
	{
		while(SDL_PollEvent(&ev) != 0)
		{
			// Getting the quit and the keyboard events
			if(ev.type == SDL_QUIT)
				isRunning = false;
			else if(ev.type == SDL_JOYBUTTONDOWN)
			{
				if(ev.jbutton.which == 1)
				{
					if(ev.jbutton.button == 0)
						currentImage = image2; 
					else if(ev.jbutton.button == 10)
						currentImage = image3;
				}
			}
		}

		// Drawing the current image to the window
		SDL_BlitSurface(currentImage, NULL, windowSurface, NULL);
		SDL_UpdateWindowSurface(window);
	}

	// Freeing the memory
	SDL_FreeSurface(image1); 
	SDL_FreeSurface(image2); 
	SDL_FreeSurface(image3);
	SDL_DestroyWindow(window);

	if(joystick != NULL)
		SDL_JoystickClose(joystick);

	joystick = nullptr;
	image1 = image2 = image3 = windowSurface = nullptr;
	window = nullptr;

	SDL_Quit();

	return 0;
}
Ejemplo n.º 20
0
int main ( int argc, char** argv )
{
    int CountTaskNote,CurNote,LastNote=0;
    int TaskNote[]=TASK_NOTES;
    int Solve=1;
    CountTaskNote= sizeof(TaskNote)/4;

    // initialize SDL video
    SDL_Init(SDL_INIT_VIDEO);
    // make sure SDL cleans up before exit
    atexit(SDL_Quit);
    // create a new window
    SCREEN = SDL_SetVideoMode(600,400,32, SDL_HWSURFACE|SDL_DOUBLEBUF);
    SDL_WM_SetCaption("C maj","ex1");

    // load images
    LINES=SDL_LoadBMP("NoteLines_600_400.bmp");
    NOTE=SDL_LoadBMP("Note.bmp");
    LINEADD=SDL_LoadBMP("LineAdd.bmp");

    //инициализация портаудио
    FreqOfNotes();// заполняем структуру нот
    PaStreamParameters inputParameters;
    PaStream *stream = NULL;
    float *sampleBlock;
    int j,Real_Note=0;
    int numBytes;
    float Im[FRAMES_PER_BUFFER];

    numBytes = FRAMES_PER_BUFFER * NUM_CHANNELS * SAMPLE_SIZE ;
    sampleBlock = (float *) malloc( numBytes );

    CLEAR( sampleBlock );

    Pa_Initialize();
    inputParameters.device = Pa_GetDefaultInputDevice();
    inputParameters.channelCount = NUM_CHANNELS;
    inputParameters.sampleFormat = PA_SAMPLE_TYPE;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    Pa_OpenStream(
        &stream,
        &inputParameters,
        0,
        SAMPLE_RATE,
        FRAMES_PER_BUFFER,
        paClipOff,
        NULL,
        NULL );

    Pa_StartStream( stream );
    fflush(stdout);

    // ##########################################
    // program main loop
    int done=0;
    while(done==0)
    {
        // message processing loop
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
            case SDL_QUIT:
                done = 1;
                break;
            case SDL_KEYDOWN:
            {
                if (event.key.keysym.sym == SDLK_ESCAPE)
                    done = 1;
                break;
            }

            }// end switch
        }// end of message processing

        // ##########################################
        // GENERATE AND DRAWING

        if (Solve==1)
        {
            do
            {
                CurNote=( rand()%(CountTaskNote));
            }
            while (CurNote==LastNote);
            LastNote=CurNote;
            DrawNote(TaskNote[CurNote]); //DRAW SDL
            Solve=0;
        }

        // ######################################
        // PortAudio analyzer

        float max_sample=0;
        Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );

        // определяем максимальную амплитуду
        for (j=0; j<FRAMES_PER_BUFFER; ++j)
        {
            if (sampleBlock[j] > max_sample) max_sample=sampleBlock[j];
        }

        // ***************************************
        // если аплтитуда мала, ничего не анализируем!
        if (max_sample>0.2)
        {
            // отправляем массив на БПФ, обнулив мнимую часть
            CLEAR( Im );
            FFT(sampleBlock, Im, FRAMES_PER_BUFFER, POW_2, -1);

            Real_Note=GetNote(sampleBlock, Im, FRAMES_PER_BUFFER);


        }
        if (Real_Note==TaskNote[CurNote]) Solve=1 ;

    }// end main loop

//close portaudio
    CLEAR( sampleBlock );
    free( sampleBlock );

    Pa_StopStream( stream );
    Pa_Terminate();

// free loaded bitmap
    SDL_FreeSurface(LINES);
    SDL_FreeSurface(LINEADD);
    SDL_FreeSurface(NOTE);

    return 0;
}
Ejemplo n.º 21
0
static int OPL_SDL_Init(unsigned int port_base)
{
    // Check if SDL_mixer has been opened already
    // If not, we must initialize it now

    if (!SDLIsInitialized())
    {
        if (SDL_Init(SDL_INIT_AUDIO) < 0)
        {
            fprintf(stderr, "Unable to set up sound.\n");
            return 0;
        }

        if (Mix_OpenAudio(opl_sample_rate, AUDIO_S16SYS, 2, GetSliceSize()) < 0)
        {
            fprintf(stderr, "Error initialising SDL_mixer: %s\n", Mix_GetError());

            SDL_QuitSubSystem(SDL_INIT_AUDIO);
            return 0;
        }

        SDL_PauseAudio(0);

        // When this module shuts down, it has the responsibility to 
        // shut down SDL.

        sdl_was_initialized = 1;
    }
    else
    {
        sdl_was_initialized = 0;
    }

    opl_sdl_paused = 0;
    pause_offset = 0;

    // Queue structure of callbacks to invoke.

    callback_queue = OPL_Queue_Create();
    current_time = 0;

    // Get the mixer frequency, format and number of channels.

    Mix_QuerySpec(&mixing_freq, &mixing_format, &mixing_channels);

    // Only supports AUDIO_S16SYS

    if (mixing_format != AUDIO_S16SYS || mixing_channels != 2)
    {
        fprintf(stderr, 
                "OPL_SDL only supports native signed 16-bit LSB, "
                "stereo format!\n");

        OPL_SDL_Shutdown();
        return 0;
    }

    // Mix buffer:

    mix_buffer = malloc(mixing_freq * sizeof(uint32_t) * 2);

    // Create the emulator structure:

    OPL3_Reset(&opl_chip, mixing_freq);
    opl_opl3mode = 0;

    callback_mutex = SDL_CreateMutex();
    callback_queue_mutex = SDL_CreateMutex();

    // TODO: This should be music callback? or-?
    Mix_HookMusic(OPL_Mix_Callback, NULL);

    return 1;
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
	try
	{
#ifdef UNIX
		if(!getuid() || !geteuid())
			I_FatalError("root user detected, quitting odamex immediately");
#endif

		// [ML] 2007/9/3: From Eternity (originally chocolate Doom) Thanks SoM & fraggle!
		Args.SetArgs (argc, argv);

		LOG_FILE = Args.CheckValue("-logfile");
		if(!LOG_FILE)LOG_FILE = "odamex.log";
		LOG.open(LOG_FILE, std::ios::out);

        if (!LOG.is_open())
            std::cerr << "Unable to create logfile: %s\n" << std::endl;

		const char *CON_FILE = Args.CheckValue("-confile");
		if(CON_FILE)CON.open(CON_FILE, std::ios::in);

		// denis - if argv[1] starts with "odamex://"
		if(argc == 2 && argv && argv[1])
		{
			const char *protocol = "odamex://";
			const char *uri = argv[1];

			if(strncmp(uri, protocol, strlen(protocol)) == 0)
			{
				std::string location = uri + strlen(protocol);
				size_t term = location.find_first_of('/');

				if(term == std::string::npos)
					term = location.length();

				Args.AppendArg("-connect");
				Args.AppendArg(location.substr(0, term).c_str());
			}
		}

#ifdef WIN32
    	// From the SDL 1.2.10 release notes: 
    	//
    	// > The "windib" video driver is the default now, to prevent 
    	// > problems with certain laptops, 64-bit Windows, and Windows 
    	// > Vista. 
    	//
    	// The hell with that.
   
   		// SoM: the gdi interface is much faster for windowed modes which are more
   		// commonly used. Thus, GDI is default.
     	if (Args.CheckParm ("-directx"))
        	putenv("SDL_VIDEODRIVER=directx");     
    	else if (getenv("SDL_VIDEODRIVER") == NULL || Args.CheckParm ("-gdi") > 0)
        	putenv("SDL_VIDEODRIVER=windib");
        	

        // Set the process affinity mask to 1 on Windows, so that all threads
        // run on the same processor.  This is a workaround for a bug in 
        // SDL_mixer that causes occasional crashes.
        // Thanks to entryway and fraggle for this.
        
        if (!SetProcessAffinityMask(GetCurrentProcess(), 1))
            LOG << "Failed to set process affinity mask: " << GetLastError() << std::endl;

#endif
		
		if (SDL_Init (SDL_INIT_TIMER|SDL_INIT_NOPARACHUTE) == -1)
			I_FatalError("Could not initialize SDL:\n%s\n", SDL_GetError());

		atterm (SDL_Quit);
		
		/*
		killough 1/98:
		
		  This fixes some problems with exit handling
		  during abnormal situations.
		  
			The old code called I_Quit() to end program,
			while now I_Quit() is installed as an exit
			handler and exit() is called to exit, either
			normally or abnormally.
		*/
		
		atexit (call_terms);
		Z_Init ();					// 1/18/98 killough: start up memory stuff first

		atterm (I_Quit);
		atterm (DObject::StaticShutdown);
		
		// Figure out what directory the program resides in.
		progdir = I_GetBinaryDir();
		startdir = I_GetCWD();
		
		// init console
		C_InitConsole (80 * 8, 25 * 8, false);
		
		Printf (PRINT_HIGH, "Heapsize: %u megabytes\n", got_heapsize);
		
		D_DoomMain ();
	}
	catch (CDoomError &error)
	{
		if (LOG.is_open())
        {
            LOG << error.GetMessage() << std::endl;
        }
#ifndef WIN32
            fprintf(stderr, "%s\n", error.GetMessage().c_str());
#else
		MessageBox(NULL, error.GetMessage().c_str(), "Odamex Error", MB_OK);
#endif
		exit (-1);
	}
#ifndef _DEBUG
	catch (...)
	{
		// If an exception is thrown, be sure to do a proper shutdown.
		// This is especially important if we are in fullscreen mode,
		// because the OS will only show the alert box if we are in
		// windowed mode. Graphics gets shut down first in case something
		// goes wrong calling the cleanup functions.
		call_terms ();
		// Now let somebody who understands the exception deal with it.
		throw;
	}
#endif
	return 0;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{

    enum STATE state = STATE_INIT;

    /* initialize graphics */
    SDL_Init(SDL_INIT_EVERYTHING);

    /* prepare opengl core profile */
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);

    SDL_Window *main_window = SDL_CreateWindow("glDrawElements", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, W, H, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(main_window);
    glewExperimental=GL_TRUE;
    glewInit();

    printf("GL_VENDOR: %s\n", glGetString(GL_VENDOR));
    printf("GL_RENDERER: %s\n", glGetString(GL_RENDERER));
    printf("GL_VERSION: %s\n", glGetString(GL_VERSION));
    printf("GL_SHADING_LANGUAGE_VERSION: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    /* prepare default framebuffer */
    glClearColor(0,0,1,1);

    /* prepare shaders */
    GLuint vs_shader = glCreateShader(GL_VERTEX_SHADER);
    compile_shader(vs_shader, "glsl/pass.vert");
    GLuint fs_shader = glCreateShader(GL_FRAGMENT_SHADER);
    compile_shader(fs_shader, "glsl/pass.frag");

    GLuint program = glCreateProgram();
    glAttachShader(program, vs_shader);
    glAttachShader(program, fs_shader);
    glLinkProgram(program);
    GLint linkStatus = 0;
    glGetProgramiv(program, GL_LINK_STATUS, &linkStatus );
    if ( linkStatus != GL_TRUE )
    {
        GLint logLength;
        glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLength );
        GLchar *infoLog = calloc(logLength+1, sizeof(char));
        glGetProgramInfoLog( program, logLength, NULL, infoLog );
        fprintf(stderr, "Failed to link shader glProgram: %s\n", infoLog);
        free(infoLog);
        exit(EXIT_FAILURE);
    }
    glUseProgram(program);

    /* prepare geometry */
    GLuint vao = 0;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    /* here, besides the vbo for the vertices, there is an array of indexes that will
       define which vertices compose each geometry face */
    GLuint ibo = 0;
    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexes), indexes, GL_STATIC_DRAW);

    GLuint vbo = 0;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(geometry), geometry, GL_STATIC_DRAW);


    GLuint v_pos = glGetAttribLocation(program, "v_pos");
    glEnableVertexAttribArray(v_pos);
    glVertexAttribPointer(v_pos, 3, GL_FLOAT, GL_FALSE, 0, (void*)(0));

    GLuint color = glGetUniformLocation(program, "color");
    glUniform4f(color, 1.f, 0.f, 0.f, 1.f);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    /* event loop */
    state = STATE_RUNNING;
    while(state == STATE_RUNNING)
    {
        /* process input */
        SDL_Event event;
        while(SDL_PollEvent(&event)) {
            switch(event.type)
            {
                case SDL_QUIT:
                    state = STATE_EXIT;
                    break;
            }
        }

        /* draw */
        glClear(GL_COLOR_BUFFER_BIT);
        /* instead of draw arrays, we use draw elements, and pass the index count for the faces */
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)0);
        SDL_GL_SwapWindow(main_window);
    }

    /* destroy */
    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(main_window);

    return 0;
}
Ejemplo n.º 24
0
/////////////////////////////
// Draw_Init
//
// Initializes the game window.
int Draw_Init(int width, int height, char *title, int pfps, int fps) {

	// Set globals
	proc_t_frame = 1000000 / pfps;
	draw_t_frame = 1000000 / fps;
	_fps = fps;
	_width = width;
	_height = height;

	// Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		Print("Draw_Init: Failure initializing SDL.\n");
		Print("\tSDL Error: %s\n", SDL_GetError());
		return (0);
	}

	// Initialize video mode
	_screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE | SDL_OPENGL);
	if (_screen == NULL) {
		Print("Draw_Init: Failure initializing video mode.\n");
		Print("\tSDL Error: %s\n", SDL_GetError());
		return (0);
	}
	SDL_WM_SetCaption(title, NULL);
	Draw_ShowInfo();

#if USE_OpenGL
	// Set the desired state
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glDisable(GL_CULL_FACE);
	glEnable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);
	glDisable(GL_DEPTH_TEST);
	glDepthMask(GL_FALSE);

	// Triplebuffer swap
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT);
	SDL_GL_SwapBuffers();
	glClear(GL_COLOR_BUFFER_BIT);

	glEnableClientState(GL_COLOR_ARRAY);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glEnableClientState(GL_VERTEX_ARRAY);

#endif

#if USE_OpenGLES

	const char vertexShaderSource[] = "attribute vec4 aPosition;       \n"
									  "attribute vec2 aTexCoord;       \n"
									  "attribute vec4 aColor;          \n"
									  "varying vec2 vTexCoord;         \n"
									  "varying vec4 vColor;            \n"
									  "uniform mat4 sProjectionMatrix; \n"
									  "void main() {                   \n"
									  "   gl_Position = aPosition *    \n"
									  "            sProjectionMatrix;  \n"
									  "   vTexCoord = aTexCoord;       \n"
									  "   vColor = aColor;             \n"
									  "}                               \n";

	const char fragmentShaderSource[] =
		"precision mediump float;                                \n"
		"varying vec2 vTexCoord;                                 \n"
		"varying vec4 vColor;                                    \n"
		"uniform sampler2D sTexture;                             \n"
		"void main() {                                           \n"
		"  gl_FragColor = texture2D(sTexture, vTexCoord)*vColor; \n"
		"}                                                       \n";

	programObject = Draw_BuildProgram(vertexShaderSource, fragmentShaderSource);
	glUseProgram(programObject);

	vertPosLoc = glGetAttribLocation(programObject, "aPosition");
	vertTexLoc = glGetAttribLocation(programObject, "aTexCoord");
	vertColorLoc = glGetAttribLocation(programObject, "aColor");

	textureLoc = glGetUniformLocation(programObject, "sTexture");
	projectionMatrixLoc =
		glGetUniformLocation(programObject, "sProjectionMatrix");

	glUniform1i(textureLoc, 0);

	glGenBuffers(1, &vertexObject);
	glBindBuffer(GL_ARRAY_BUFFER, vertexObject);
	glBufferData(GL_ARRAY_BUFFER,
				 Vertex2D_Length * sizeof(float) * Max_Vertices, NULL,
				 GL_DYNAMIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, vertexObject);

	glVertexAttribPointer(vertPosLoc, 2, GL_FLOAT, GL_FALSE,
						  Vertex2D_Length * sizeof(float),
						  (void *)(0 * sizeof(float)));
	glVertexAttribPointer(vertTexLoc, 2, GL_FLOAT, GL_FALSE,
						  Vertex2D_Length * sizeof(float),
						  (void *)(2 * sizeof(float)));
	glVertexAttribPointer(vertColorLoc, 4, GL_FLOAT, GL_FALSE,
						  Vertex2D_Length * sizeof(float),
						  (void *)(4 * sizeof(float)));

	glEnableVertexAttribArray(vertPosLoc);
	glEnableVertexAttribArray(vertTexLoc);
	glEnableVertexAttribArray(vertColorLoc);

	unsigned char whiteTexData[4] = {255, 255, 255, 255};
	_whiteTex = Draw_UploadGLTexture(1, 1, whiteTexData);

#endif

	// Set the proyection (2D)
	glViewport(0, 0, _width, _height);
	float projectionMatrix[16] = {1, 0, 0, 0, 0, 1, 0, 0,
								  0, 0, 1, 0, 0, 0, 0, 1};
	projectionMatrix[0] = (2.0f / _width);
	projectionMatrix[5] = -(2.0f / _height);
	projectionMatrix[10] = -0.001f;
	projectionMatrix[3] = -1.0f;
	projectionMatrix[7] = 1.0f;
	Draw_SetMatrix(projectionMatrix);

	// Enable Alpha blending
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Initialize the triangle array
	_quadArray = QuadArray2D_Create(400);

	Draw_SetColor(1.0f, 1.0f, 1.0f, 1.0f);

	return (1);
}
Ejemplo n.º 25
0
void S_Resourcemanager::initialize()
{
	SDL_Init(SDL_INIT_EVERYTHING);
	TTF_Init();

	TextColor.r = 255;
	TextColor.g = 255;
	TextColor.b = 100;

	this->p_screen = SDL_SetVideoMode(900,600,32,SDL_SWSURFACE);

	SDL_Surface * LoadedImage1 = IMG_Load("player_walk_down.png");

	SDL_Surface * OptimizedImage1 = NULL;

	OptimizedImage1 = SDL_DisplayFormatAlpha(LoadedImage1);

	font = TTF_OpenFont( "ZIPERHEA.ttf", 28 );

	if(font == NULL)
	{
		cout << "Laden des Fonts fehlgeschlagen" << endl;
	}

	this->p_player = OptimizedImage1;

	this->p_game_over = IMG_Load("game_over_raw.png");
	this->p_win = IMG_Load("win_proto.png");
	this->p_main_menue = IMG_Load("MainMenue.png");
	this->p_player_up = IMG_Load("Player_walk_up.png");
	this->p_player_right = IMG_Load("Player_walk_right.png");
	this->p_player_left = IMG_Load("Player_walk_left.png");
	this->p_hirn1 = IMG_Load("hirn1.png");
	this->p_hirn2 = IMG_Load("hirn2.png");
	this->p_hirn3 = IMG_Load("hirn3.png");
	this->p_hirn4 = IMG_Load("hirn4.png");
	this->p_Pfleger = IMG_Load("Pfleger.png");
	this->p_tot = IMG_Load("tot.png");
	this->p_pille = IMG_Load("pille.png");
	this->p_heiltrank = IMG_Load("Heal_Spritze.png");
	this->p_crazy_enemy_up = IMG_Load("PATIENToben.png");
	this->p_crazy_enemy_right = IMG_Load("PATIENTrechts.png");
	this->p_crazy_enemy_left = IMG_Load("PATIENTlinks.png");
	this->p_elektrode = IMG_Load("Elektrode.png");
	this->p_spritze = IMG_Load("Spritze.png");
	this->p_shop = IMG_Load("shop.png");
	this->p_npc1 = IMG_Load("npc1.png");
	this->p_npc2 = IMG_Load("npc2.png");
	this->p_qabfrage = IMG_Load("qabfrage.png");
	this->p_qbelohnung = IMG_Load("qbelohnung.png");
	this->p_manaspritze = IMG_Load("Mana_Spritze.png");
	this->p_mana_leer = IMG_Load("mana_leer.png");
	this->p_mana_halbvoll = IMG_Load("mana_halbvoll.png");
	this->p_mana_voll = IMG_Load("mana_voll.png");
	this->p_Aufforderung_e = IMG_Load("inter_aufforderung.png");
	this->p_gekauft = IMG_Load("gekauft.png");
	this->p_nichtgekauft = IMG_Load("nichtgekauft.png");
	this->p_weak = IMG_Load("weak.png");
	this->p_tut = IMG_Load("tutorial_sequenz.png");
	this->p_ep_empty = IMG_Load("ep_empty.png");
	this->p_ep_10 = IMG_Load("ep_10.png");
	this->p_ep_20 = IMG_Load("ep_20.png");
	this->p_ep_30 = IMG_Load("ep_30.png");
	this->p_ep_40 = IMG_Load("ep_40.png");
	this->p_ep_50 = IMG_Load("ep_50.png");
	this->p_ep_60 = IMG_Load("ep_60.png");
	this->p_ep_70 = IMG_Load("ep_70.png");
	this->p_ep_80 = IMG_Load("ep_80.png");
	this->p_ep_90 = IMG_Load("ep_90.png");
	this->p_ep_100 = IMG_Load("ep_100.png");
	this->p_ep_110 = IMG_Load("ep_110.png");
	this->p_ep_120 = IMG_Load("ep_120.png");
	this->p_ep_125 = IMG_Load("ep_125.png");
	this->p_skilltree = IMG_Load("skilltree.png");
	this->p_t1_2 = IMG_Load("t1_mana_-10.png");
	this->p_t1_1 = IMG_Load("t1_1.png");
	this->p_t1_3 = IMG_Load("t1_shop_-2.png");
	this->p_t1_4 = IMG_Load("t1_mana_speed.png");
	this->p_t1_5 = IMG_Load("t1_dmgMelee.png");
	this->p_check = IMG_Load("check.png");
	this->p_nopoints = IMG_Load("nopoints.png");
	this->p_skilled = IMG_Load("skilled.png");
	this->p_t2_1 = IMG_Load("t2_1.png");
	this->p_t2_2 = IMG_Load("t2_2.png");
	this->p_t2_3 = IMG_Load("t2_3.png");
	this->p_t3_1 = IMG_Load("t3_1.png");
	this->p_t3_2 = IMG_Load("t3_2.png");
	this->p_lvl1 = IMG_Load("lvl1.png");
	this->p_lvl2 = IMG_Load("lvl2.png");
	this->p_lvl3 = IMG_Load("lvl3.png");
	this->p_lvl4 = IMG_Load("lvl4.png");
	this->p_lvl5 = IMG_Load("lvl5.png");
	this->p_lvl6 = IMG_Load("lvl6.png");
	this->p_lvl7 = IMG_Load("lvl7.png");
	this->p_lvl8 = IMG_Load("lvl8.png");
	this->p_lvl8 = IMG_Load("lvl9.png");
	this->p_lvl10 = IMG_Load("lvl10.png");
	this->p_not_yet = IMG_Load("not_yet.png");
	this->p_tp_0 = IMG_Load("tp_0.png");
	this->p_tp_1 = IMG_Load("tp_1.png");
	this->p_tp_2 = IMG_Load("tp_2.png");
	this->p_tp_3 = IMG_Load("tp_3.png");
	this->p_tp_4 = IMG_Load("tp_4.png");
	this->p_tp_5 = IMG_Load("tp_5.png");
	this->p_tp_gt5 = IMG_Load("tp_gt5.png");
	this->p_not_skillable = IMG_Load("not_skillable.png");
	this->p_lvl_up = IMG_Load("lvl_up.png");
	this->p_Baer = IMG_Load("Baer.png");
	this->p_Baer_spricht = IMG_Load("Baer spricht.png");
	this->p_lobby = IMG_Load("Lobby.png");
	this->p_player = IMG_Load("player.png");
	this->p_not_rdy = IMG_Load("notready.png");
	this->p_rdy = IMG_Load("ready.png");
	this->p_gamestart = IMG_Load("gamestart.png");
	this->p_player1_not_rdy = IMG_Load("player1_not_rdy.png");
	this->p_player2_not_rdy = IMG_Load("player2_not_rdy.png");
	///SDL_mixer wird initalisiert
	



	if(p_spritze == NULL)
	{
		cout << "keine Spritze" << endl;
	}

	SDL_Surface * LoadedImage2 = IMG_Load("Licht_thronsaal.png");

	SDL_Surface * OptimizedImage2 = NULL;

	OptimizedImage2 = SDL_DisplayFormatAlpha(LoadedImage2);

	this->p_trans = OptimizedImage2;



	if(p_player == NULL)
	{
		std::cout << "Initialisierung des Players ist fehlgeschlagen" << std::endl;
	}

	SDL_Surface * LoadedImage = IMG_Load("map.png");
	 SDL_Surface * OptimizedImage = NULL;

	 SDL_Surface * LoadedImageMap2 = IMG_Load("map2.png");
	 SDL_Surface * OptimizedImageMap2 = NULL;

	 SDL_Surface * LoadedImageMap3 = IMG_Load("map3.png");
	 SDL_Surface * OptimizedImageMap3 = NULL;

	  OptimizedImage = SDL_DisplayFormat(LoadedImage);
	  OptimizedImageMap2 = SDL_DisplayFormat(LoadedImageMap2);
	  OptimizedImageMap3 = SDL_DisplayFormat(LoadedImageMap3);

	  this->p_background = OptimizedImage;
	  this->p_map2 = OptimizedImageMap2;
	  this->p_map3 = OptimizedImageMap3;

	  ///SDL_FreeSurface(OptimizedImage);

	if(p_background == NULL)
	{
		std::cout << "initzialisierung des Levels  ist fehlgeschlagen" << std::endl;
	}

	this->p_menue = IMG_Load("mainmenu_raw.png");
	this->p_crazy_enemy = IMG_Load("patient_walk.png");
	this->p_princess = IMG_Load("metamorphose.png");

	this->PlayerDownClips[0].x = 0;
	this->PlayerDownClips[0].y = 0;
	this->PlayerDownClips[0].w = PLAYER_WIDTH;
	this->PlayerDownClips[0].h = PLAYER_HEIGHT;

	this->PlayerDownClips[1].x = 60;
	this->PlayerDownClips[1].y = 0;
	this->PlayerDownClips[1].w = PLAYER_WIDTH;
	this->PlayerDownClips[1].h = PLAYER_HEIGHT;

	this->PlayerDownClips[2].x = 120;
	this->PlayerDownClips[2].y = 0;
	this->PlayerDownClips[2].w = PLAYER_WIDTH;
	this->PlayerDownClips[2].h = PLAYER_HEIGHT;

	this->PlayerDownClips[3].x = 180;
	this->PlayerDownClips[3].y = 0;
	this->PlayerDownClips[3].w = PLAYER_WIDTH;
	this->PlayerDownClips[3].h = PLAYER_HEIGHT;

	this->PlayerDownClips[4].x = 240;
	this->PlayerDownClips[4].y = 0;
	this->PlayerDownClips[4].w = PLAYER_WIDTH;
	this->PlayerDownClips[4].h = PLAYER_HEIGHT;

	this->PlayerDownClips[5].x = 300;
	this->PlayerDownClips[5].y = 0;
	this->PlayerDownClips[5].w = PLAYER_WIDTH;
	this->PlayerDownClips[5].h = PLAYER_HEIGHT;

	this->PlayerUpClips[0].x = 0;
	this->PlayerUpClips[0].y = 0;
	this->PlayerUpClips[0].w = PLAYER_WIDTH;
	this->PlayerUpClips[0].h = PLAYER_HEIGHT;

	this->PlayerUpClips[1].x = 60;
	this->PlayerUpClips[1].y = 0;
	this->PlayerUpClips[1].w = PLAYER_WIDTH;
	this->PlayerUpClips[1].h = PLAYER_HEIGHT;

	this->PlayerUpClips[2].x = 120;
	this->PlayerUpClips[2].y = 0;
	this->PlayerUpClips[2].w = PLAYER_WIDTH;
	this->PlayerUpClips[2].h = PLAYER_HEIGHT;

	this->PlayerUpClips[3].x = 180;
	this->PlayerUpClips[3].y = 0;
	this->PlayerUpClips[3].w = PLAYER_WIDTH;
	this->PlayerUpClips[3].h = PLAYER_HEIGHT;

	this->PlayerUpClips[4].x = 240;
	this->PlayerUpClips[4].y = 0;
	this->PlayerUpClips[4].w = PLAYER_WIDTH;
	this->PlayerUpClips[4].h = PLAYER_HEIGHT;

	this->PlayerUpClips[5].x = 300;
	this->PlayerUpClips[5].y = 0;
	this->PlayerUpClips[5].w = PLAYER_WIDTH;
	this->PlayerUpClips[5].h = PLAYER_HEIGHT;


	this->PlayerRightClips[0].x = 0;
	this->PlayerRightClips[0].y = 0;
	this->PlayerRightClips[0].w = PLAYER_WIDTH;
	this->PlayerRightClips[0].h = PLAYER_HEIGHT;

	this->PlayerRightClips[1].x = 60;
	this->PlayerRightClips[1].y = 0;
	this->PlayerRightClips[1].w = PLAYER_WIDTH;
	this->PlayerRightClips[1].h = PLAYER_HEIGHT;

	this->PlayerRightClips[2].x = 120;
	this->PlayerRightClips[2].y = 0;
	this->PlayerRightClips[2].w = PLAYER_WIDTH;
	this->PlayerRightClips[2].h = PLAYER_HEIGHT;

	this->PlayerRightClips[3].x = 180;
	this->PlayerRightClips[3].y = 0;
	this->PlayerRightClips[3].w = PLAYER_WIDTH;
	this->PlayerRightClips[3].h = PLAYER_HEIGHT;

	this->PlayerRightClips[4].x = 240;
	this->PlayerRightClips[4].y = 0;
	this->PlayerRightClips[4].w = PLAYER_WIDTH;
	this->PlayerRightClips[4].h = PLAYER_HEIGHT;

	this->PlayerRightClips[5].x = 300;
	this->PlayerRightClips[5].y = 0;
	this->PlayerRightClips[5].w = PLAYER_WIDTH;
	this->PlayerRightClips[5].h = PLAYER_HEIGHT;


	this->PlayerLeftClips[0].x = 0;
	this->PlayerLeftClips[0].y = 0;
	this->PlayerLeftClips[0].w = PLAYER_WIDTH;
	this->PlayerLeftClips[0].h = PLAYER_HEIGHT;

	this->PlayerLeftClips[1].x = 60;
	this->PlayerLeftClips[1].y = 0;
	this->PlayerLeftClips[1].w = PLAYER_WIDTH;
	this->PlayerLeftClips[1].h = PLAYER_HEIGHT;

	this->PlayerLeftClips[2].x = 120;
	this->PlayerLeftClips[2].y = 0;
	this->PlayerLeftClips[2].w = PLAYER_WIDTH;
	this->PlayerLeftClips[2].h = PLAYER_HEIGHT;

	this->PlayerLeftClips[3].x = 180;
	this->PlayerLeftClips[3].y = 0;
	this->PlayerLeftClips[3].w = PLAYER_WIDTH;
	this->PlayerLeftClips[3].h = PLAYER_HEIGHT;

	this->PlayerLeftClips[4].x = 240;
	this->PlayerLeftClips[4].y = 0;
	this->PlayerLeftClips[4].w = PLAYER_WIDTH;
	this->PlayerLeftClips[4].h = PLAYER_HEIGHT;

	this->PlayerLeftClips[5].x = 300;
	this->PlayerLeftClips[5].y = 0;
	this->PlayerLeftClips[5].w = PLAYER_WIDTH;
	this->PlayerLeftClips[5].h = PLAYER_HEIGHT;

	this->EndbossClips[0].x = 0;
	this->EndbossClips[0].y = 0;
	this->EndbossClips[0].w = 120;
	this->EndbossClips[0].h = 120;

	this->EndbossClips[1].x = 120;
	this->EndbossClips[1].y = 0;
	this->EndbossClips[1].w = 120;
	this->EndbossClips[1].h = 120;

	this->EndbossClips[2].x = 240;
	this->EndbossClips[2].y = 0;
	this->EndbossClips[2].w = 120;
	this->EndbossClips[2].h = 120;

	this->EndbossClips[3].x = 360;
	this->EndbossClips[3].y = 0;
	this->EndbossClips[3].w = 120;
	this->EndbossClips[3].h = 120;

	this->EndbossClips[4].x = 480;
	this->EndbossClips[4].y = 0;
	this->EndbossClips[4].w = 120;
	this->EndbossClips[4].h = 120;

	this->EndbossClips[5].x = 600;
	this->EndbossClips[5].y = 0;
	this->EndbossClips[5].w = 120;
	this->EndbossClips[5].h = 120;

	this->EndbossClips[6].x = 720;
	this->EndbossClips[6].y = 0;
	this->EndbossClips[6].w = 120;
	this->EndbossClips[6].h = 120;

}
Ejemplo n.º 26
0
int main(int argc, char *argv[])
{
	SDL_Event event;
	SDL_Rect position;
	int continuer = 1;
	if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) == -1)
    {
        printf("%s", Mix_GetError());
    }
    TTF_Init();
    if(TTF_Init() == -1)
    {
        fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());/*S'il y a eu une erreur au
        démarrage de SDL_ttf, un fichier stderr.txt sera créé contenant un message explicatif de l'erreur.la fonction
        TTF_GetError() renvoie le dernier message d'erreur de SDL_ttf.C'est pour cela qu'on l'utilise dans le fprintf.*/
        exit(EXIT_FAILURE);
    }
    // initialize SDL video
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }
    // make sure SDL cleans up before exit
    atexit(SDL_Quit);
    // create a new window
    SDL_Surface *ecran = SDL_SetVideoMode(1150,750,32,SDL_HWSURFACE | SDL_DOUBLEBUF);//602,402
    if ( !ecran )
    {
        printf("Unable to set 602x402 video: %s\n", SDL_GetError());
        return 1;
    }
	SDL_WM_SetCaption("Menu de jeu TIC TAC TOE", NULL);
    // load an image
    SDL_Surface* bmp = SDL_LoadBMP("images/morpion.bmp");
    if (!bmp)
    {
        printf("Unable to load bitmap: %s\n", SDL_GetError());
        return 1;
    }
    // centre the bitmap on screen
    SDL_Rect font;
    font.x = (ecran->w-bmp->w) / 2;
    font.y = (ecran->h-bmp->h) / 2;
    Musiques m;
    Mix_AllocateChannels(2);
    m.musique= Mix_LoadMUS("musiques/musique1.mp3");
    m.Clic= Mix_LoadWAV("musiques/clic1.wav");
    Mix_VolumeMusic(200);
    Mix_PlayMusic(m.musique,-1);
    Mix_PlayChannel(0,m.Clic,0);
	while (continuer)
	{
		SDL_WaitEvent(&event);
		switch(event.type)
		{
            case SDL_QUIT:
                continuer = 0;
                break;
            case SDL_MOUSEBUTTONDOWN:
                position.x = event.motion.x ;
                position.y = event.motion.y ;
                break;
            case SDL_KEYUP:
                if(event.key.keysym.sym==SDLK_s)
                    continuer= 0;
                break;
		}
        // clear screen
		SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format,0,0,0));
		 // draw bitmap
        SDL_BlitSurface(bmp,0,ecran,&font);
		SDL_Flip(ecran);
        MenuPrincipal();
	}
	Mix_FreeMusic(m.musique);
    Mix_FreeChunk(m.Clic);
    Mix_CloseAudio();
	TTF_Quit();
	SDL_Quit();
	return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
Game::Game() {
	SDL_Init(SDL_INIT_EVERYTHING);
	SDL_ShowCursor(SDL_DISABLE);
	eventLoop();
}
Ejemplo n.º 28
0
IsoEng::IsoEng()
{
	SDL_Init(SDL_INIT_VIDEO);
}
Ejemplo n.º 29
0
int main(int argc, char *argv[])
{


	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	

#ifdef _WINDOWS
	glewInit();
#endif


	SDL_Event event;
	bool done = false;


	glViewport(0, 0, 640, 360);
	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
	
	//GLuint charTexture = LoadTexture("char1.png");
	GLuint emojiTexture = LoadTexture("emoji.png");
	GLuint cardbackTexture = LoadTexture("cardback.png");
	GLuint starTexture = LoadTexture("star.png");
	//GLuint charmanderTexture = LoadTexture("Charmander.png");
	Matrix projectionMatrix;
	Matrix modelMatrixEmoji;
	Matrix modelMatrixCardback;
	Matrix modelMatrixStar;

	Matrix viewMatrix;
	projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f);
	glUseProgram(program.programID);

	float lastFrameTicks = 0.0f;

	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}

		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;


		glClear(GL_COLOR_BUFFER_BIT);

		program.setModelMatrix(modelMatrixEmoji);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glBindTexture(GL_TEXTURE_2D, emojiTexture);

		
		float vertices[] = { -1, -1, 0, -1, 0, 0, -1, -1, 0, 0, -1, 0 };

		float shiftX = 0;
		float shiftY = 0;
		shiftX += 0.5f * elapsed;
		shiftY += 0.3f * elapsed;
		modelMatrixEmoji.Translate(shiftX, 0, 0);
		modelMatrixCardback.Translate(-shiftX, 0, 0);
		modelMatrixStar.Translate(0, -shiftY, 0);
		


		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
		glEnableVertexAttribArray(program.positionAttribute);
		
		float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
		glEnableVertexAttribArray(program.texCoordAttribute);


		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		program.setModelMatrix(modelMatrixCardback);

		glBindTexture(GL_TEXTURE_2D, cardbackTexture);

		float vertices2[] = { 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1 };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords2[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		program.setModelMatrix(modelMatrixStar);

		glBindTexture(GL_TEXTURE_2D, starTexture);



		float vertices3[] = { -2, 0, -1, 0, -1, 1, -2, 0, -1, 1, -2, 1 };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords3[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		SDL_GL_SwapWindow(displayWindow);
	}

	SDL_Quit();
	return 0;
}
Ejemplo n.º 30
0
int main(int argc, char **argv)
{
	int res = 0;

#else

/* gee */
extern "C" DECLSPEC void SDLCALL SDL_SetModuleHandle(void *hInst);

// translated to utf8_main
int main(int argc, char *argv[])
{
	int res = 0;

#if !(SDLMAME_SDL2)
	/* Load SDL dynamic link library */
	if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) {
		fprintf(stderr, "WinMain() error: %s", SDL_GetError());
		return(FALSE);
	}
	SDL_SetModuleHandle(GetModuleHandle(NULL));
#endif
#endif
	// disable I/O buffering
	setvbuf(stdout, (char *) NULL, _IONBF, 0);
	setvbuf(stderr, (char *) NULL, _IONBF, 0);

	#ifdef SDLMAME_UNIX
	sdl_entered_debugger = 0;
	#if (!defined(SDLMAME_MACOSX)) && (!defined(SDLMAME_HAIKU)) && (!defined(SDLMAME_EMSCRIPTEN))
#if !(SDLMAME_SDL2)
	if (TTF_Init() == -1)
	{
		printf("SDL_ttf failed: %s\n", TTF_GetError());
	}
#endif
	FcInit();
	#endif
	#endif

	#ifdef SDLMAME_OS2
	MorphToPM();
	#endif

#if defined(SDLMAME_X11) && (SDL_MAJOR_VERSION == 1) && (SDL_MINOR_VERSION == 2)
	if (SDL_Linked_Version()->patch < 10)
	/* workaround for SDL choosing a 32-bit ARGB visual */
	{
		Display *display;
		if ((display = XOpenDisplay(NULL)) && (DefaultDepth(display, DefaultScreen(display)) >= 24))
		{
			XVisualInfo vi;
			char buf[130];
			if (XMatchVisualInfo(display, DefaultScreen(display), 24, TrueColor, &vi)) {
				snprintf(buf, sizeof(buf), "0x%lx", vi.visualid);
				osd_setenv(SDLENV_VISUALID, buf, 0);
			}
		}
		if (display)
			XCloseDisplay(display);
	}
#endif

	osd_init_midi();    // this is a blues riff in B, watch me for the changes and try to keep up...

	{
		sdl_osd_interface osd;
		sdl_options options;
		cli_frontend frontend(options, osd);
		res = frontend.execute(argc, argv);
	}

#ifdef MALLOC_DEBUG
	{
		void check_unfreed_mem(void);
		check_unfreed_mem();
	}
#endif

	// already called...
	//SDL_Quit();

	#ifdef SDLMAME_UNIX
	#if (!defined(SDLMAME_MACOSX)) && (!defined(SDLMAME_HAIKU)) && (!defined(SDLMAME_EMSCRIPTEN))
#if !(SDLMAME_SDL2)
	TTF_Quit();
#endif
	if (!sdl_entered_debugger)
	{
		FcFini();
	}
	#endif
	#endif

	osd_shutdown_midi();

	exit(res);

	return res;
}