int sdlplayer_fx(char *filename, int volume) { Mix_Chunk *sample; g_warning("sdlplayer %s\n", filename); sample=Mix_LoadWAV_RW(SDL_RWFromFile(filename, "rb"), 1); if(!sample) { return(cleanExit("Mix_LoadWAV_RW")); // handle error } Mix_VolumeChunk(sample, MIX_MAX_VOLUME); if((_channel_fx = Mix_PlayChannel(-1, sample, 0))==-1) { return(cleanExit("Mix_LoadChannel(0x%p,1)", _channel_fx)); } while( Mix_Playing( _channel_fx ) ) { SDL_Delay(50); } // free the sample // Mix_Chunk *sample; Mix_FreeChunk(sample); _channel_fx = -1; g_warning("sdlplayer complete playing of %s\n", filename); return(0); }
/*---------------------main() routine--------------------------* * tasks for main * generate socket and get socket id, * Accept request from client and generate new socket * Communicate with client and close new socket after done *---------------------------------------------------------------------------*/ main(int argc, char *argv[]) { //Declare variables and clear memory where necessary. int newsockid; /* return value of the accept() call */ int my_port; struct sockaddr_in my_addr, client_addr; memset(&my_addr,'\0', sizeof(my_addr)); memset(&client_addr, '\0', sizeof(client_addr)); //Check that we have the proper arguments in the command line if (argc != 3) { printf("Error: Wrong number of arguments\nShould take the form 'SimpServer Port# Directory'\n"); } my_port = atoi(argv[1]); strcpy(directory,argv[2]); //Open socket and bind. if ((socketfd = socket(AF_INET, SOCK_STREAM, getprotobyname("tcp")->p_proto)) < 0) { printf("Error opening socket\n"); cleanExit(); } //Setup my_addr my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = htons(INADDR_ANY); my_addr.sin_port = htons(my_port); //Bind the socket to our IP if ((bind(socketfd, (struct sockaddr*)&my_addr, sizeof(my_addr))) < 0) { printf("Error binding socket to port\n"); cleanExit(); } if ((listen(socketfd,MAX_BACKLOG)) < 0 ) { printf("Error listening on port %d",my_port); } //Wait until there is a connection request to perform HTTP while (1) { int comm_fd; if ((comm_fd = accept(socketfd, (struct sockaddr*) NULL, NULL)) < 0) { printf("Error accepting socket\n"); }else { perform_http(comm_fd); } close(comm_fd); } cleanExit(); }
int main(int argc, char *argv[], char *env[]) { initApp(); // send arguments for (int i = 2; i < argc; i++) if (argv[i] != NULL) sendCmd("/arg", argv[i]); // send environment for (int i = 0; env[i]; i++) if (env[i] != NULL) sendCmd("/env", env[i]); // current working directory char *cwd = _getcwd(NULL, 0); sendCmd("/dir", cwd); free(cwd); // send clj file if (argc > 1) { sendCmd("/main", argv[1]); } else { fprintf(stderr, "Starting Clojure REPL...\nType Ctrl-Z <Enter> to exit\n"); sendCmd("/main", ""); } bool eof = false; // process input from stdin and from the server while(1) { char buf[5] = {0}; int len = sizeof(buf)-1; if (recv(server_socket, buf, len, 0) < len) cleanExit(-4); if (strcmp(buf, "/out") == 0) { recvToFD(stdout_handle, getLen()); } else if (strcmp(buf, "/err") == 0) { recvToFD(stderr_handle, getLen()); } else if (strcmp(buf, "/ext") == 0) { // processExit(buf, getCmdLen()); } else { fprintf(stderr, "Unexpected server command %s\n", buf); char dbuf[21] = {0}; recv(server_socket, dbuf, sizeof(dbuf)-1, 0); cleanExit(-5); } } }
void initApp() { WSADATA wsd; WSAStartup(2, &wsd); struct hostent *hostinfo = gethostbyname(server_address); if (hostinfo == NULL) { fprintf(stderr, "Unknown host: %s\n", server_address); cleanExit(-1); } if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { if ((server_socket = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); cleanExit(-2); } } struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(server_port); server_addr.sin_addr = *(struct in_addr *) hostinfo->h_addr; memset(&(server_addr.sin_zero), '\0', 8); if (connect(server_socket, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("connect"); cleanExit(-3); } // non-block console io AllocConsole(); stdin_handle = GetStdHandle(STD_INPUT_HANDLE); stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); stderr_handle = GetStdHandle(STD_ERROR_HANDLE); SECURITY_ATTRIBUTES attrs; attrs.bInheritHandle = TRUE; attrs.lpSecurityDescriptor = NULL; attrs.nLength = 0; DWORD id = 0; if (!CreateThread(&attrs, 0, &processStdin, NULL, 0, &id)) handleError(); }
static void cleanupAndExit( const int exitStatus ) { int status; status = cryptEnd(); if( status == CRYPT_ERROR_INCOMPLETE ) puts( "cryptEnd() failed with CRYPT_ERROR_INCOMPLETE." ); cleanExit( exitStatus ); }
int main(int argc, char* argv[]) { atexit (cleanExit); int port; int option = 1; char ident[MAX_STR_LEN]; // Process CMD Line Args [BEGIN] //////////////////////////////////////////////////////////////////////////// if(argc==1) { port = SERVER_PORT_ID; } else if (argc==3) { port = atoi(argv[1]); strcpy(ident, argv[2]); } else if (argc==2) { port = atoi(argv[1]); } else { DEBUG_PRINT(("Wrong number of Arguments: exiting")); return 0; } //////////////////////////////////////////////////////////////////////////// // Process CMD Line Args [END] // Setup Socket [BEGIN] //////////////////////////////////////////////////////////////////////////// char str[MAX_STR_LEN]; int listen_fd, comm_fd; struct sockaddr_in servaddr; listen_fd = socket(AF_INET, SOCK_STREAM, 0); bzero( &servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htons(INADDR_ANY); servaddr.sin_port = htons(port); // tells kernal to force reuse of the address preventing binding problems setsockopt(listen_fd,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(int)); bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listen_fd, 10); comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL); bzero( str, MAX_STR_LEN); read(comm_fd,str,MAX_STR_LEN); //////////////////////////////////////////////////////////////////////////// // Setup Socket [END] printf("Processing Request - %s",str); perform_http(comm_fd, str, ident); cleanExit(); }
int sdlplayer_init() { int audio_rate,audio_channels; Uint16 audio_format; // initialize SDL for audio if(SDL_Init(SDL_INIT_AUDIO)<0) return(cleanExit("SDL_Init")); // initialize sdl mixer, open up the audio device if(Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,AUDIO_BUFFERS)<0) return(cleanExit("Mix_OpenAudio")); // print out some info on the audio device and stream Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels); bits=audio_format&0xFF; g_warning("Opened audio at %d Hz %d bit %s, %d bytes audio buffer\n", audio_rate, bits, audio_channels>1?"stereo":"mono", AUDIO_BUFFERS ); return(0); }
static gboolean delete_event( GtkWidget *widget, GdkEvent *event, gpointer data ) { // If you return FALSE in the "delete_event" signal handler, // GTK will emit the "destroy" signal. Returning TRUE means // you don't want the window to be destroyed. // This is useful for popping up 'are you sure you want to quit?' // type dialogs. cleanExit(); return TRUE; }
void deamonize () { int pidfile; int i; char str[10]; switch (fork ()) { case 0: setsid(); for (i=getdtablesize();i>=0;--i) close(i); i=open("/dev/null",O_RDWR); /* open stdin */ dup(i); /* stdout */ dup(i); /* stderr */ umask(027); if ((pidfile=open(PID_FILE,O_RDWR|O_CREAT,0640))<0) { syslog(LOG_CRIT,"Failed to create pid file: %m"); cleanExit(EXIT_FAILURE); } if (lockf(pidfile,F_TLOCK,0)<0) { syslog(LOG_CRIT,"Failed to lock pid file: %m"); cleanExit(EXIT_FAILURE); /* can not lock */ } sprintf(str,"%d\n",getpid()); write(pidfile,str,strlen(str)); /* record pid to lockfile */ loop (); break; case -1: perror ("Failed to deamonize"); cleanExit (EXIT_FAILURE); default: break; } }
int sdlplayer_music(char *filename, int volume) { Mix_Music *music; g_warning("sdlplayer_bg %s\n", filename); // load the song if(!(music=Mix_LoadMUS(filename))) return(cleanExit("Mix_LoadMUS(\"%s\")",filename)); if(Mix_PlayMusic(music, 1)==-1) { return(cleanExit("Mix_LoadMUS(0x%p,1)",music)); } Mix_VolumeMusic(volume); // wait for the music to complete while(Mix_PlayingMusic() || Mix_PausedMusic()) { SDL_Delay(50); } return(0); }
void handleError() { int error = GetLastError(); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL); // MessageBox( NULL, (LPCTSTR)lpMsgBuf, (LPCWSTR)"Error", MB_OK | MB_ICONERROR ); fprintf(stderr, (const char *) lpMsgBuf); LocalFree( lpMsgBuf ); cleanExit(error); }
void SYNA_PDTScan_BootloaderMode() { unsigned char j, tmp = 255; unsigned char in[10]; unsigned short i; i = 0; j = 0; // reset func addr info index readRMI((i << 8) | PDT_ADDR, &tmp, 1); if(tmp & 0x40) { printk("\nNon-Standard Page Description Table not supported\n"); cleanExit(1); } while(1) { j++; readRMI((i << 8) | (PDT_ADDR - PDT_SIZE*j), in, 6); if(in[5] == 0x00) { // No more functions on this page return; } else if(in[5] == 0x34) { // Function34 F34_Query_Base = (i << 8) | in[0]; F34_Cmd_Base = (i << 8) | in[1]; F34_Ctrl_Base = (i << 8) | in[2]; F34_Data_Base = (i << 8) | in[3]; printk("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j)); } else if(in[5] == 0x01) { // Function01 F01_Query_Base = (i << 8) | in[0]; F01_Cmd_Base = (i << 8) | in[1]; F01_Ctrl_Base = (i << 8) | in[2]; F01_Data_Base = (i << 8) | in[3]; printk("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j)); } else { printk("\n-- RMI Function $%02X not supported --\n", in[5]); } } }
void handleKeyPress(SDL_keysym *keysym) { switch (keysym->sym) { case SDLK_ESCAPE: case SDLK_q: printf("q/Esc pressed\n"); cleanExit(0); break; case SDLK_F1: case SDLK_f: printf("F1/f pressed - toggle fullscreen\n"); videoFlags ^= SDL_FULLSCREEN; // Toggle fullscreen bit. surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags); initGL(); resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT); break; default: break; } return; }
void usage(int exitcode) { fprintf(stderr, "Usage: clj [<clj-file>] [args]\n"); cleanExit(exitcode); }
/*---------------------------------------------------------------------------* * * Accepts a request from "sockid" and sends a response to "sockid". * *---------------------------------------------------------------------------*/ perform_http(int sockid) { char str_rec_buff[MAX_REC_LEN]; bzero( str_rec_buff, MAX_REC_LEN); char str_send_buff[MAX_SEND_LEN]; bzero( str_send_buff, MAX_SEND_LEN); FILE *file_to_send; //Read from the socket if ((readn(sockid,str_rec_buff,MAX_REC_LEN)) < 0){ printf("Error reading TCP stream from client\n"); close(sockid); cleanExit(); } //Parse received string; char method[MAX_REC_LEN]; char request_URI[MAX_REC_LEN]; char http_version[MAX_REC_LEN]; sscanf(str_rec_buff, "%s %s %s\r\n", method, request_URI, http_version); //Parse the URI for the requested file char hostname[MAX_REC_LEN]; char identifier[MAX_REC_LEN]; int port; parse_URI(request_URI, hostname, &port, identifier, MAX_REC_LEN); //Ensure the GET method is the one being asked for if ((strcmp(method,"GET") != 0) || (strcmp(http_version,"HTTP/1.0")) ){ writen(sockid, "HTTP/1.0 501 Not Implemented\r\n\r\n", MAX_SEND_LEN); return; } //Get System Information struct utsname unameData; uname(&unameData); //Get System Time time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); //Setup the strings that gives us the file location and the system info char file_location[2*MAX_REC_LEN]; snprintf(file_location, MAX_REC_LEN*2, "%s/%s",directory,identifier); char server_info[MAX_SEND_LEN]; snprintf(server_info, MAX_REC_LEN, "Date: %sServer: %s %s %s\r\n\r\n", asctime(timeinfo), unameData.sysname, unameData.nodename, unameData.release); //HTTP Header is built and sent here if file is found if ((file_to_send = fopen(file_location,"r")) != NULL) { strcpy(str_send_buff, "HTTP/1.0 200 OK\r\n"); strcat(str_send_buff, server_info); int http_len = strlen(str_send_buff); fread(str_send_buff+http_len, 1, MAX_SEND_LEN-http_len, (FILE*)file_to_send); writen(sockid, str_send_buff, MAX_SEND_LEN); fclose(file_to_send); }else { strcpy(str_send_buff, "HTTP/1.0 404 Not Found"); strcat(str_send_buff, server_info); writen(sockid, str_send_buff, MAX_SEND_LEN); return; } }
static gint menuFileQuit_CB(GtkWidget *widget, gpointer data) { cleanExit(); return TRUE; }
void loop () { // event interface int fd = -1; /* the file descriptor for the device */ int i; /* loop counter */ size_t read_bytes; /* how many bytes were read */ struct input_event ev[64]; /* the events (up to 64 at once) */ int key; /*key code */ /* used if event hit fn */ int hasSomething; #ifdef HAVE_LIBXOSD // prepare queue handling int flag = 0, brightness = 0, sound = 0; createqueue (); #endif if (strcasecmp(devinput,"AUTO")==0) { // try to figure out rigth event value for keyboard snprintf(devinput,MAX_DEVINPUT_SIZE,"/dev/input/event%d",getItemEvent(DEFAULT_KEYBOARD_NAME)); syslog(LOG_INFO,"autodevice determines %s as keyboard event",devinput); } if ((fd = open (devinput, O_RDONLY)) < 0) { syslog (LOG_CRIT,"event interface (%s) open failed: %m",devinput); // shoot auto as LAST chance snprintf(devinput,MAX_DEVINPUT_SIZE,"/dev/input/event%d",getItemEvent(DEFAULT_KEYBOARD_NAME)); syslog(LOG_CRIT,"autodevice determines %s as a last chance keyboard event",devinput); if ((fd = open (devinput, O_RDONLY)) < 0) { syslog(LOG_CRIT,"Event interface (%s) open failed: %m",devinput); cleanExit(EXIT_FAILURE); } } /* handle important signal */ if (signal(SIGTERM,signal_handler) < 0) { perror("signal"); exit(EXIT_FAILURE); } if (signal(SIGHUP,signal_handler) < 0) { perror("signal"); exit(EXIT_FAILURE); } syslog(LOG_INFO,"fsfn loaded"); while (1) { /* loop */ hasSomething = 0; /* nothing yet */ /* * read the event interface */ if ( (read_bytes = read (fd, ev, sizeof (struct input_event) * 64))==-1) { //fprintf(stderr,"Error: %d\n",errno); if (errno==ENODEV) { // event is now invalid ? must be back from sleep... syslog(LOG_NOTICE,"Start sleeping..."); sleep(10); syslog(LOG_NOTICE,"End sleeping..."); close(fd); // is this needed ?? syslog(LOG_NOTICE,"Input device changed, back from suspend ?: %m"); // get new event snprintf(devinput,MAX_DEVINPUT_SIZE,"/dev/input/event%d",getItemEvent(DEFAULT_KEYBOARD_NAME)); syslog(LOG_NOTICE,"autodevice determines %s as new event",devinput); // reopen - seems to be problems after a hibernate :( if ((fd = open (devinput, O_RDONLY)) < 0) { syslog(LOG_CRIT,"New event interface (%s) open failed: %m",devinput); cleanExit(EXIT_FAILURE); } // read it if ((read_bytes = read (fd, ev, sizeof (struct input_event) * 64))==-1) { syslog(LOG_CRIT,"Reading new device (%s) failed: %m",devinput); cleanExit(EXIT_FAILURE); } } else { syslog(LOG_CRIT,"Input device reading failed: %m"); cleanExit(EXIT_FAILURE); } } if (read_bytes < (int) sizeof (struct input_event)) { syslog (LOG_CRIT,"short read: %m"); cleanExit(EXIT_FAILURE); } /* * Loop for all readed events until we have something * interesting.. */ for (i = 0; !hasSomething && (i < (int) (read_bytes / sizeof (struct input_event))); i++) { hasSomething = (ev[i].type == FN_INPUT_TYPE) && (ev[i].code == FN_INPUT_CODE) && (ev[i].value == FN_INPUT_VALUE); } /* * If we got a FN event, plz do something... */ if (hasSomething && (key = getCodes ())) { if ((key & FN_F5) == FN_F5) { // check config if (!checkConfig("F5_CMD")) { // lower brightness #ifdef HAVE_LIBXOSD flag = MOD_BRIGHTNESS; brightness = setBrightness (getBrightness () - 1); sendmsg (flag, brightness, sound); sendcmd (FN_F5); #else setBrightness (getBrightness () - 1); #endif } } if ((key & FN_F6) == FN_F6) { // check config if (!checkConfig("F6_CMD")) { // higher brightness #ifdef HAVE_LIBXOSD flag = MOD_BRIGHTNESS; brightness = setBrightness (getBrightness () + 1); sendmsg (flag, brightness, sound); sendcmd (FN_F6); #else setBrightness (getBrightness () + 1); #endif } } if ((key & FN_F2) == FN_F2) { // check config if (!checkConfig("F2_CMD")) { #ifdef HAVE_LIBXOSD flag = MOD_SOUND; sound = mute (SOUND_STEP); sendmsg (flag, brightness, sound); sendcmd(FN_F2); #else mute (SOUND_STEP); #endif } } if ((key & FN_F3) == FN_F3) { if (!checkConfig("F3_CMD")) { #ifdef HAVE_LIBXOSD flag = MOD_SOUND; sound = volume_down (SOUND_STEP); //mod by SilSha sendmsg (flag, brightness, sound); sendcmd(FN_F3); #else volume_down (SOUND_STEP); #endif } } if ((key & FN_F4) == FN_F4) { if (!checkConfig("F4_CMD")) { #ifdef HAVE_LIBXOSD flag = MOD_SOUND; sound = volume_up (SOUND_STEP); //mod by SilSha sendmsg (flag, brightness, sound); sendcmd(FN_F4); #else volume_up (SOUND_STEP); #endif } } /* NO built in commands */ if ((key & FN_F7) == FN_F7) { #ifdef HAVE_LIBXOSD if (!checkConfig("F7_CMD")) sendcmd(FN_F7); #else sendcmd(FN_F7); #endif } if ((key & FN_F10) == FN_F10) { #ifdef HAVE_LIBXOSD if(!checkConfig("F10_CMD")) sendcmd(FN_F10); #else sendcmd(FN_F10); #endif } if ((key & FN_F12) == FN_F12) { #ifdef HAVE_LIBXOSD if (!checkConfig("F12_CMD")) sendcmd(FN_F12); #else checkConfig("F12_CMD"); #endif } if (( key & S1_BTN) == S1_BTN) { #ifdef HAVE_LIBXOSD if (!checkConfig("S1_CMD")) sendcmd(S1_BTN); #else checkConfig("S1_CMD"); #endif } if (( key & S2_BTN) == S2_BTN) { #ifdef HAVE_LIBXOSD if (!checkConfig("S2_CMD")) sendcmd(S2_BTN); #else checkConfig("S2_CMD"); #endif } } }// while }
/* signal handler */ void signal_handler(sig) { cleanExit(EXIT_FAILURE); }
int main (int argc, char *argv[]) { int deamon = 1; /* deamon by default */ int xosd = 0; /* do not start as xosd client */ openlog("fsfn",LOG_CONS|LOG_NDELAY|LOG_PID,LOG_DAEMON); /* fill a default */ //strncpy (devinput, "/dev/input/event0", 255); strncpy (devinput, getConfig("DEVICE"), MAX_CFG_LENGTH); /* parse command line */ while (0 == 0) { int option_index = 0; int next_option; static struct option long_options[] = { {"help", 0, NULL, 'h'}, {"nodaemon", 0, NULL, 'n'}, {"device", 1, NULL, 'd'}, #ifdef HAVE_LIBXOSD {"osd", 0, NULL, 'o'}, #endif {NULL, 0, NULL, 0} }; #ifdef HAVE_LIBXOSD next_option = getopt_long (argc, argv, "hnd:o", long_options, &option_index); #else next_option = getopt_long (argc, argv, "hnd:", long_options, &option_index); #endif if (next_option == -1) { break; } switch (next_option) { case 'n': deamon = 0; break; case 'o': // printf("We are osd\n"); xosd = 1; break; case 'd': if (optarg) { // printf("We are changing devinput: %s\n",devinput); strncpy (devinput, optarg, 255); break; } default: // printf("Unknow option: %c\n",next_option); usage (argv[0]); cleanExit(-1); exit (-1); } } deamon&=!xosd; //could not be deamon if osd if (deamon) { deamonize (); } else { if (!xosd) { loop (); } #ifdef HAVE_LIBXOSD else { looposd (); } #endif } cleanExit(EXIT_SUCCESS); return EXIT_SUCCESS; }
BuildGraph::BuildGraph(const vector<ParseRule> &rules) { BuildIDTable bs; std::set<string> uniqTargets; for(auto r: rules) { for(string &t : r.targets) { if(uniqTargets.find(t) != uniqTargets.end()) { startErr() << "Multiple definition for target `" << t << "'\n"; cleanExit(-1); } uniqTargets.insert(t); bs.put(t); } for(string &s : r.sources) { bs.put(s); } } steps.resize(bs.size()); for(auto &it : bs.all()) { int id = it.second; const string &name = it.first; steps[id] = new BuildStep(id, name); } // insert dependencies based on steps for(auto r: rules) { for(string &t : r.targets) { BuildStep *cur = steps[bs.get(t)]; for(string &src : r.sources) { BuildStep *dep = steps[bs.get(src)]; cur->deps.push_back(dep); } cur->action = r.action; } } // check for circular dependencies and for rules that need actions bool error = false; for(auto *s : steps) { if(s->isCircular()) { startErr() << "Circular dependency detected in target: `" << s->name << "'\n"; error = true; } // if it's not a fake target, and not a pure source, it should have an action if(!s->phony() && !s->isSource() && !s->hasAction()) { auto &err = startErr() << "No action to make target: `" << s->name << "' from "; for(size_t i=0; i<s->deps.size(); i++) { if(i != 0) err << ", "; err << s->deps[i]->name; } err << "\n"; error = true; } } if(error) { cleanExit(-1); } }
int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Video initialization failed: %s\n", SDL_GetError()); cleanExit(1); } const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo(); if (!videoInfo) { fprintf(stderr, "Video query failed: %s\n", SDL_GetError()); cleanExit(1); } videoFlags |= SDL_DOUBLEBUF | SDL_HWSURFACE; videoFlags |= SDL_HWPALETTE; videoFlags |= SDL_RESIZABLE; SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, videoFlags); if (!surface) { fprintf(stderr, "Video mode set failed: %s\n", SDL_GetError()); cleanExit(1); } printf("screen is hardware surface = %d\n", (surface->flags & SDL_HWSURFACE == 0)); initGL(); resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT); // Event loop. for (;;) { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_VIDEORESIZE: printf("SDL_VIDEORESIZE w=%d h=%d\n", event.resize.w, event.resize.h, event.resize); surface = SDL_SetVideoMode(event.resize.w, event.resize.h, SCREEN_BPP, videoFlags); if (!surface) { fprintf(stderr, "Could not get a surface after resize: %s\n", SDL_GetError()); cleanExit(1); } initGL(); resizeWindow(SCREEN_WIDTH, SCREEN_HEIGHT); break; case SDL_KEYDOWN: handleKeyPress(&event.key.keysym); break; case SDL_QUIT: printf("SDL_QUIT\n"); goto finished; default: break; } } drawScene(); } finished: cleanExit(0); // Never reached. return 0; }
int main( int argc, char **argv ) { const char *zargPtr = NULL; BOOLEAN sessionTestError = FALSE, loopbackTestError = FALSE; int flags, status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); /* If we're running in test mode, run the test code and exit */ #ifdef CONFIG_SUITEB_TESTS return( suiteBMain( argc, argv ) ); #endif /* CONFIG_SUITEB_TESTS */ /* Print a general banner to let the user know what's going on */ printf( "testlib - cryptlib %d-bit self-test framework.\n", ( int ) sizeof( long ) * 8 ); /* Cast for gcc */ puts( "Copyright Peter Gutmann 1995 - 2012." ); puts( "" ); /* Skip the program name and process any command-line arguments */ argv++; argc--; status = processArgs( argc, argv, &flags, &zargPtr ); if( !status ) exit( EXIT_FAILURE ); #ifdef USE_TCHECK THREAD_DEBUG_SUSPEND(); #endif /* USE_TCHECK */ /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* VisualAge C++ doesn't set the TZ correctly. The check for this isn't as simple as it would seem since most IBM compilers define the same preprocessor values even though it's not documented anywhere, so we have to enable the tzset() call for (effectively) all IBM compilers and then disable it for ones other than VisualAge C++ */ #if ( defined( __IBMC__ ) || defined( __IBMCPP__ ) ) && !defined( __VMCMS__ ) tzset(); #endif /* VisualAge C++ */ /* Initialise cryptlib */ printf( "Initialising cryptlib..." ); status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } puts( "done." ); #ifndef TEST_RANDOM /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ #if defined( __MVS__ ) || defined( __VMCMS__ ) #pragma convlit( resume ) cryptAddRandom( "xyzzy", 5 ); #pragma convlit( suspend ) #else cryptAddRandom( "xyzzy", 5 ); #endif /* Special-case EBCDIC handling */ #endif /* TEST_RANDOM */ /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) { cryptEnd(); exit( EXIT_FAILURE ); } /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ #ifndef _WIN32_WCE testSystemSpecific2(); #endif /* WinCE */ #ifdef USE_TCHECK THREAD_DEBUG_RESUME(); #endif /* USE_TCHECK */ /* For general testing purposes we can insert test code at this point to test special cases that aren't covered in the general tests below */ testKludge( zargPtr ); #ifdef SMOKE_TEST /* Perform a general smoke test of the kernel */ smokeTest(); #endif /* SMOKE_TEST */ /* Test each block of cryptlib functionality */ if( ( flags & DO_SELFTEST ) && !testSelfTest() ) goto errorExit; if( ( flags & DO_LOWLEVEL ) && !testLowLevel() ) goto errorExit; if( ( flags & DO_RANDOM ) && !testRandom() ) goto errorExit; if( ( flags & DO_CONFIG ) && !testConfig() ) goto errorExit; if( ( flags & DO_DEVICE ) && !testDevice() ) goto errorExit; if( ( flags & DO_MIDLEVEL ) && !testMidLevel() ) goto errorExit; if( ( flags & DO_CERT ) && !testCert() ) goto errorExit; if( ( flags & DO_KEYSETFILE ) && !testKeysetFile() ) goto errorExit; if( ( flags & DO_KEYSETDBX ) && !testKeysetDatabase() ) goto errorExit; if( ( flags & DO_CERTPROCESS ) && !testCertMgmt() ) goto errorExit; if( ( flags & DO_HIGHLEVEL ) && !testHighLevel() ) goto errorExit; if( ( flags & DO_ENVELOPE ) && !testEnveloping() ) goto errorExit; if( ( flags & DO_SESSION ) && !testSessions() ) { sessionTestError = TRUE; goto errorExit; } if( ( flags & DO_SESSIONLOOPBACK ) && !testSessionsLoopback() ) { loopbackTestError = TRUE; goto errorExit; } if( ( flags & DO_USER ) && !testUsers() ) goto errorExit; /* Shut down cryptlib */ status = cryptEnd(); if( cryptStatusError( status ) ) { if( status == CRYPT_ERROR_INCOMPLETE ) { puts( "cryptEnd() failed with error code CRYPT_ERROR_INCOMPLETE, " "a code path in the\nself-test code resulted in an error " "return without a full cleanup of objects.\nIf you were " "running the multithreaded loopback tests this may be " "because one\nor more threads lost sync with other threads " "and exited without cleaning up\nits objects. This " "happens occasionally due to network timing issues or\n" "thread scheduling differences." ); } else { printf( "cryptEnd() failed with error code %d, line %d.\n", status, __LINE__ ); } goto errorExit1; } puts( "All tests concluded successfully." ); return( EXIT_SUCCESS ); /* All errors end up here */ errorExit: cryptEnd(); errorExit1: puts( "\nThe test was aborted due to an error being detected. If you " "want to report\nthis problem, please provide as much information " "as possible to allow it to\nbe diagnosed, for example the call " "stack, the location inside cryptlib where\nthe problem occurred, " "and the values of any variables that might be\nrelevant." ); if( sessionTestError ) { puts( "\nThe error occurred during one of the network session tests, " "if the error\nmessage indicates a network-level problem such " "as ECONNREFUSED, ECONNRESET,\nor a timeout or read error then " "this is either due to a transient\nnetworking problem or a " "firewall interfering with network connections. This\nisn't a " "cryptlib error, and doesn't need to be reported." ); } if( loopbackTestError ) { puts( "\nThe error occurred during one of the multi-threaded network " "loopback\ntests, this was probably due to the different threads " "losing synchronisation.\nFor the secure sessions this usually " "results in read/write, timeout, or\nconnection-closed errors " "when one thread is pre-empted for too long. For the\n" "certificate-management sessions it usually results in an error " "related to the\nserver being pre-empted for too long by database " "updates. Since the self-\ntest exists only to exercise " "cryptlib's capabilities, it doesn't bother with\ncomplex thread " "synchronisation during the multi-threaded loopback tests.\nThis " "type of error is non-fatal, and should disappear if the test is " "re-run." ); } cleanExit( EXIT_FAILURE ); return( EXIT_FAILURE ); /* Get rid of compiler warnings */ }
void SYNA_PDTScan(void) { unsigned char j, tmp = 255; unsigned char FUNC_EXISTS = 0; unsigned char in[10]; unsigned short i; //tmp16, l, m; --HSLEE i = 0; // constructF01F81(); do { readRMI((i << 8) | PDT_ADDR, &tmp, 1); if(tmp & 0x40) { printk("\nNon-Standard Page Description Table not supported\n"); cleanExit(1); } FUNC_EXISTS = 0; // reset flag j = 0; // reset func addr info index while(1) { j++; readRMI((i << 8) | (PDT_ADDR - PDT_SIZE*j), in, 6); readRMI((i << 8) | 0xFF, &tmp, 1); if(in[5] == 0x00) { // No more functions on this page if(FUNC_EXISTS == 0) { // constructPrivRMI(); return; } else { i++; } break; } else if(in[5] == 0x11) { // Function11 F11_Query_Base = (i << 8) | in[0]; F11_Cmd_Base = (i << 8) | in[1]; F11_Ctrl_Base = (i << 8) | in[2]; F11_Data_Base = (i << 8) | in[3]; printk("\n-- RMI Function $%02X, Address = 0x%02x, QueryAdd = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j), (i << 8) | in[0]); } else if(in[5] == 0x34) { // Function34 F34_Query_Base = (i << 8) | in[0]; F34_Cmd_Base = (i << 8) | in[1]; F34_Ctrl_Base = (i << 8) | in[2]; F34_Data_Base = (i << 8) | in[3]; printk("\n-- RMI Function $%02X, Address = 0x%02x, QueryAdd = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j), (i << 8) | in[0]); } else if(in[5] == 0x01) { // Function01 F01_Query_Base = (i << 8) | in[0]; F01_Cmd_Base = (i << 8) | in[1]; F01_Ctrl_Base = (i << 8) | in[2]; F01_Data_Base = (i << 8) | in[3]; printk("\n-- RMI Function $%02X, Address = 0x%02x, QueryAdd = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j), (i << 8) | in[0]); } else if(in[5] == 0x54) { F54_Query_Base = (i << 8) | in[0]; F54_Command_Base = (i << 8) | in[1]; F54_Control_Base = (i << 8) | in[2]; F54_Data_Base = (i << 8) | in[3]; F54_Data_LowIndex = F54_Data_Base + 1; F54_Data_HighIndex = F54_Data_Base + 2; F54_Data_Buffer = F54_Data_Base + 3; #ifdef _DS4_3_0_ F54_PhysicalRx_Addr = F54_Control_Base + 18; #endif printk("\n-- RMI Function $%02X, Address = 0x%02x, QueryAdd = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j), (i << 8) | in[0]); } else if(in[5] == 0x1A) { F1A_Query_Base = (i << 8) | in[0]; F1A_Command_Base = (i << 8) | in[1]; F1A_Control_Base = (i << 8) | in[2]; F1A_Data_Base = (i << 8) | in[3]; F1A_Button_Mapping = F1A_Control_Base + 3; printk("\n-- RMI Function $%02X, Address = 0x%02x, QueryAdd = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE*j), (i << 8) | in[0]); } else { printk("\n-- RMI Function $%02X not supported --\n", in[5]); } FUNC_EXISTS = 1; } } while(FUNC_EXISTS == 1); }
int main(int argc, char *argv[]) { int i; int ret = 0; uint8_t ticket_enc_key[256]; uint8_t ticket_enc_hash[32]; char *password_text = NULL; uint8_t public_uid_text[PUBLIC_UID_BYTE_SIZE<<1]; uint8_t public_uid_bin[PUBLIC_UID_BYTE_SIZE]; uint8_t public_uid_bin_size = 0; yk_ticket tkt; ykdb_entry entry; ykdb_h *handle; uint8_t tkt_private_uid_hash[32]; uint32_t crc; int delta_use; int delta_session; struct passwd *pw; progname = argv[0]; parseCommandLine(argc, argv); if (mode == MODE_VALIDATE && otp == NULL) { fprintf(stderr, "You must at least provide an OTP!\n\n"); showUsage(progname); ret = 1; } else if (mode == MODE_USAGE) { showUsage(progname); } else if (mode == MODE_VERSION) { showVersion(); } else if (mode == MODE_VALIDATE) { if (user == NULL) { /* get passwd structure for current user */ pw = getPWEnt(); if (!pw) { fprintf(stderr, "Can't determine your user name!\n"); cleanExit(1); } user = strdup(pw->pw_name); } /* get passwd structure for desired user */ pw = getpwnam(user); if (!pw) { fprintf(stderr, "Unknown user: %s\n", user); cleanExit(1); } ret = _yubi_run_helper_binary(otp, user); if (ret != PAM_SUCCESS) printf("OTP is INVALID!\n"); else printf("OTP is VALID.\n"); } cleanExit(ret); }
int main(int argc, char **argv) { int audio_rate,audio_channels; Uint16 audio_format; Uint32 t; Mix_Music *music; int volume=SDL_MIX_MAXVOLUME; /* initialize SDL for audio and video */ if(SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO)<0) cleanExit("SDL_Init"); atexit(SDL_Quit); int initted=Mix_Init(0); printf("Before Mix_Init SDL_mixer supported: "); print_init_flags(initted); initted=Mix_Init(~0); printf("After Mix_Init SDL_mixer supported: "); print_init_flags(initted); Mix_Quit(); if(argc<2 || argc>4) { fprintf(stderr,"Usage: %s filename [depth] [any 3rd argument...]\n" " filename is any music file supported by your SDL_mixer library\n" " depth is screen depth, default is 8bits\n" " if there is a third argument given, we go fullscreen for maximum fun!\n", *argv); return 1; } /* open a screen for the wav output */ if(!(s=SDL_SetVideoMode(W,H,(argc>2?atoi(argv[2]):8),(argc>3?SDL_FULLSCREEN:0)|SDL_HWSURFACE|SDL_DOUBLEBUF))) cleanExit("SDL_SetVideoMode"); SDL_WM_SetCaption("sdlwav - SDL_mixer demo","sdlwav"); /* hide the annoying mouse pointer */ SDL_ShowCursor(SDL_DISABLE); /* get the colors we use */ white=SDL_MapRGB(s->format,0xff,0xff,0xff); black=SDL_MapRGB(s->format,0,0,0); /* initialize sdl mixer, open up the audio device */ if(Mix_OpenAudio(44100,MIX_DEFAULT_FORMAT,2,BUFFER)<0) cleanExit("Mix_OpenAudio"); /* we play no samples, so deallocate the default 8 channels... */ Mix_AllocateChannels(0); /* print out some info on the formats this run of SDL_mixer supports */ { int i,n=Mix_GetNumChunkDecoders(); printf("There are %d available chunk(sample) decoders:\n",n); for(i=0; i<n; ++i) printf(" %s\n", Mix_GetChunkDecoder(i)); n = Mix_GetNumMusicDecoders(); printf("There are %d available music decoders:\n",n); for(i=0; i<n; ++i) printf(" %s\n", Mix_GetMusicDecoder(i)); } /* print out some info on the audio device and stream */ Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels); bits=audio_format&0xFF; sample_size=bits/8+audio_channels; rate=audio_rate; printf("Opened audio at %d Hz %d bit %s, %d bytes audio buffer\n", audio_rate, bits, audio_channels>1?"stereo":"mono", BUFFER ); /* calculate some parameters for the wav display */ dy=s->h/2.0/(float)(0x1<<bits); /* load the song */ if(!(music=Mix_LoadMUS(argv[1]))) cleanExit("Mix_LoadMUS(\"%s\")",argv[1]); { Mix_MusicType type=Mix_GetMusicType(music); printf("Music type: %s\n", type==MUS_NONE?"MUS_NONE": type==MUS_CMD?"MUS_CMD": type==MUS_WAV?"MUS_WAV": /*type==MUS_MOD_MODPLUG?"MUS_MOD_MODPLUG":*/ type==MUS_MOD?"MUS_MOD": type==MUS_MID?"MUS_MID": type==MUS_OGG?"MUS_OGG": type==MUS_MP3?"MUS_MP3": type==MUS_MP3_MAD?"MUS_MP3_MAD": type==MUS_FLAC?"MUS_FLAC": "Unknown"); } /* set the post mix processor up */ Mix_SetPostMix(postmix,argv[1]); SDL_FillRect(s,NULL,black); SDL_Flip(s); SDL_FillRect(s,NULL,black); SDL_Flip(s); /* start playing and displaying the wav */ /* wait for escape key of the quit event to finish */ t=SDL_GetTicks(); if(Mix_PlayMusic(music, 1)==-1) cleanExit("Mix_PlayMusic(0x%p,1)",music); Mix_VolumeMusic(volume); while((Mix_PlayingMusic() || Mix_PausedMusic()) && !done) { SDL_Event e; while(SDL_PollEvent(&e)) { switch(e.type) { case SDL_KEYDOWN: switch(e.key.keysym.sym) { case SDLK_ESCAPE: done=1; break; case SDLK_LEFT: if(e.key.keysym.mod&KMOD_SHIFT) { Mix_RewindMusic(); position=0; } else { int pos=position/audio_rate-1; if(pos<0) pos=0; Mix_SetMusicPosition(pos); position=pos*audio_rate; } break; case SDLK_RIGHT: switch(Mix_GetMusicType(NULL)) { case MUS_MP3: Mix_SetMusicPosition(+5); position+=5*audio_rate; break; case MUS_OGG: case MUS_FLAC: case MUS_MP3_MAD: /*case MUS_MOD_MODPLUG:*/ Mix_SetMusicPosition(position/audio_rate+1); position+=audio_rate; break; default: printf("cannot fast-forward this type of music\n"); break; } break; case SDLK_UP: volume=(volume+1)<<1; if(volume>SDL_MIX_MAXVOLUME) volume=SDL_MIX_MAXVOLUME; Mix_VolumeMusic(volume); break; case SDLK_DOWN: volume>>=1; Mix_VolumeMusic(volume); break; case SDLK_SPACE: if(Mix_PausedMusic()) Mix_ResumeMusic(); else Mix_PauseMusic(); break; default: break; } break; case SDL_QUIT: done=1; break; default: break; } } /* the postmix processor tells us when there's new data to draw */ if(need_refresh) refresh(); SDL_Delay(0); } t=SDL_GetTicks()-t; /* free & close */ Mix_FreeMusic(music); Mix_CloseAudio(); SDL_Quit(); /* show a silly statistic */ printf("fps=%.2f\n",((float)flips)/(t/1000.0)); return(0); }
static void cleanupAndExit( const int exitStatus ) { cryptEnd(); cleanExit( exitStatus ); }
int main(int argc, char* argv[]) { int width = 1024, height = 768; if(argc == 5 && strcmp(argv[2], "-r") == 0 ){ width = atoi(argv[3]); height = atoi(argv[4]); } else if(argc == 4 && strcmp(argv[1], "-r") == 0 ){ width = atoi(argv[2]); height = atoi(argv[3]); } /*Initialisation SDL, OpenGL etc */ if( initWindow(width, height) == EXIT_FAILURE){ perror("Impossible d'initialiser la fenêtre SDL, le programme va fermer.\n"); exit(-1); } /* initialisation de SDL_TTF*/ if(TTF_Init()== -1){ printf("Error loading TTF: %s\n",TTF_GetError()); exit(1); } bool askedForQuit = false; World world; world.towersList = NULL; world.map.name = NULL; world.map.tabXYConstruct = NULL; world.map.image = NULL; world.map.pathNodeList = NULL; Interface interface; interface.lstButtons = NULL; char* mapName= NULL; BUTTON_OF_MENU.lstMapName = NULL; BUTTON_OF_MENU.lstMapButton = NULL; BUTTON_OF_MENU.lstMapTextureIndex = NULL; bool play = false; List* lstMaps = createEmptyList(); readDirectory(lstMaps); /* selection d'une carte en ligne de commande*/ if (argc >= 2 && strcmp(argv[1], "-r") != 0){ char* curMap = NULL; while( (curMap = (char*) nextData(lstMaps)) != NULL){ if (strcmp(argv[1],curMap)==0){ mapName = (char*) malloc(strlen(argv[1])*sizeof(char)); if(mapName == NULL){ fprintf(stderr, "Erreur fatale : impossible d'allouer la mémoire nécessaire.\n"); exit(EXIT_FAILURE); } strcpy(mapName,argv[1]); play = true; break; } } if(! play) fprintf(stderr, "Erreur le nom donné en paramètre ne correspond à aucun fichier map\n"); } freeListComplete(lstMaps); /*-------------- GESTION DU MENU --------------------*/ do{ interface.lstButtons = NULL; /* chargement des polices */ int playIsPush = 0; int menuOpen = 0; int aideOpen = 0; initMenuGraphics(); /* ouverture du répertoire data */ while(!play && askedForQuit == false) { /* Récupération du temps au début de la boucle */ Uint32 startTime = SDL_GetTicks(); /* Placer ici le code de dessin du menu */ drawMenu(&menuOpen,&aideOpen,&playIsPush,mapName); /* Echange du front et du back buffer : mise à jour de la fenêtre */ SDL_GL_SwapBuffers(); /* Renvoie une chaine de caractère contenant le nom du fichier ITD choisi par l'utilisateur ou NULL si rien n'a encore été choisi */ askedForQuit = handleMenuActions(&mapName,&playIsPush, &menuOpen,&aideOpen); if(playIsPush == 2) play = true; /* Calcul du temps écoulé */ Uint32 elapsedTime = SDL_GetTicks() - startTime; /* Si trop peu de temps s'est écoulé, on met en pause le programme */ if(elapsedTime < FRAMERATE_MILLISECONDS) { SDL_Delay(FRAMERATE_MILLISECONDS - elapsedTime); } } /*-------------- GESTION DU JEU --------------------*/ bool gameFinished = false; //Surtout à appeler APRES avoir initialisé la SDL char mapPath[50] = "data/"; float width = .15;//10% de largeur float height = 1.; //Toute la hauteur float positionX = 0.85; //A 90% de la largeur float positionY = .0; //A 100% de la hauter if(!askedForQuit){ strcat(mapPath, mapName); world = initWorld(mapPath); initGameGraphics(); GAME_TEXTURES_ID.MAP_ID = makeTextureFromSurface(world.map.image); //Initialisation interface interface = initGameInterface(width, height, positionX, positionY); startWorld(&world); } while(!gameFinished && !askedForQuit) { /* Récupération du temps au début de la boucle */ Uint32 startTime = SDL_GetTicks(); /* On tente un nouveau cycle de tours de jeu si besoin. Le temps est géré par la fonction. La plupart du temps plusieurs tours de jeu sont joués d'affilé. */ worldNewStep(&world); drawWorld(&world); drawInterface(&interface, &world); /* Calcul du temps écoulé, si temps < 10 ms, on ne passe pas au tour suivant. */ Uint32 elapsedTime = SDL_GetTicks() - startTime; /* Si trop peu de temps s'est écoulé, on ne dessine rien. */ if(elapsedTime < FRAMERATE_MILLISECONDS) { /* Echange du front et du back buffer : mise à jour de la fenêtre */ SDL_GL_SwapBuffers(); SDL_Delay(FRAMERATE_MILLISECONDS - elapsedTime); } /* Boucle traitant les evenements */ askedForQuit = handleGameActions(&world, &interface, &gameFinished); } play = false; mapName = NULL; cleanWorld(&world); cleanInterface(&interface); }while(! askedForQuit); /* Liberation des ressources */ cleanExit(&world, &interface); return EXIT_SUCCESS; }
// based on http://www.willusher.io/sdl2%20tutorials/2013/08/17/lesson-1-hello-world/ int main( int argc, char* args[] ) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; cleanExit(1); } std::cout << "SDL initialised OK!\n"; // Initialise the audio mixer and also explained the variables. // 44100 - Common hertz level for these things // MIX_DEFAULT_FORMAT - Like the SDL_INIT_EVERYTHING, some init settings // 2 - Audio Channels for stereo play // 2048 - Sample size, can affect lag time for effect to play // != 0 - Same as other init stuff, not sure why, just needs it. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) != 0) { std::cout << "SDL_Mixer init error: " << Mix_GetError() << std::endl; cleanExit(1); } std::cout << "SDP_Mixer Initialised OK!" << std::endl; //create window win = SDL_CreateWindow("SDL Hello World!", 100, 100, screenW, screenH, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); //error handling if (win == nullptr) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; cleanExit(1); } std::cout << "SDL CreatedWindow OK!\n"; ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; cleanExit(1); } player = new sprite("./assets/spritesheet.png", 50.0f, 520.0f, 24.0f, 32.0f, ren); player->srcRect.x = 0.0f; player->srcRect.y = 96.0f; player->srcRect.w = 24.0f; player->srcRect.h = 32.0f; player->playerScore = 0; player->bufferMax = 5; #pragma region Hens hen1 = new enemy("./assets/spritesheet.png", 500, 100, 24, 40, ren); hens.push_back(hen1); hen1->state = enemy::moveRight; hen1->flipDirection = true; hen1->xTarget1 = 200.0f; hen1->xTarget2 = 250.0f; hen1->srcRect.x = 0.0f; hen1->srcRect.y = 0.0f; hen1->srcRect.w = 24.0f; hen1->srcRect.h = 40.0f; hen2 = new enemy("./assets/spritesheet.png", 700, 530, 24, 40, ren); hens.push_back(hen2); hen2->state = enemy::moveLeft; hen2->xTarget1 = 100.0f; hen2->xTarget2 = 750.0f; hen2->srcRect.x = 0.0f; hen2->srcRect.y = 0.0f; hen2->srcRect.w = 24.0f; hen2->srcRect.h = 40.0f; hen3 = new enemy("./assets/spritesheet.png", 600, 280, 24, 40, ren); hens.push_back(hen3); hen3->state = enemy::moveRight; hen3->xTarget1 = 100.0f; hen3->xTarget2 = 750.0f; hen3->srcRect.x = 0.0f; hen3->srcRect.y = 0.0f; hen3->srcRect.w = 24.0f; hen3->srcRect.h = 40.0f; #pragma endregion #pragma region Audio stuff // This is formatted in the same way to the default code from John as it makes sense and I want to stick to it. jumpEffect = Mix_LoadWAV("./assets/jump.wav"); if (jumpEffect == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } pickup1 = Mix_LoadWAV("./assets/pickup1.wav"); if (pickup1 == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } pickup2 = Mix_LoadWAV("./assets/pickup2.wav"); if (pickup2 == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } background = Mix_LoadMUS("./assets/background_music.wav"); if (background == nullptr) { std::cout << "Mix_LoadWAV Error: " << Mix_GetError() << std::endl; cleanExit(1); } #pragma endregion if( TTF_Init() == -1 ) { std::cout << "TTF_Init Failed: " << TTF_GetError() << std::endl; cleanExit(1); } TTF_Font* sans = TTF_OpenFont("./assets/Hack-Regular.ttf", 96); if (sans == nullptr) { std::cout << "TTF_OpenFont Error: " << TTF_GetError() << std::endl; cleanExit(1); } SDL_Color White = { 255, 255, 255 }; SDL_Color Purple = { 165, 0, 220 }; std::string lives = "Lives: " + std::to_string(player->playerLives); const char* lifeCounts = lives.c_str(); loading = new text(ren, "Loading...", 200, 200, 400, 130, sans, White); Load(); scoreCount = new text(ren, player->playerScore, 0, 0, 180, 60, sans, Purple); lifeCount = new text(ren, lifeCounts, 600, 0, 180, 60, sans, Purple); drawTileMap(); loading->isShowing = false; Mix_PlayMusic(background, -1); while (!done) //loop until done flag is set) { handleInput(); // this should ONLY SET VARIABLES updateSimulation(); // this should ONLY SET VARIABLES according to simulation render(); // this should render the world state according to VARIABLES SDL_Delay(20); // unless vsync is on?? } cleanExit(0); return 0; }
void SYNA_PDTScan(void) { unsigned char j, tmp = 255; unsigned char FUNC_EXISTS = 0; unsigned char in[10]; #ifdef F54_Porting unsigned short i; char buf[512] = { 0 }; int ret = 0; #else unsigned short i, tmp16, l, m; #endif i = 0; /* constructF01F81(); */ do { readRMI((i << 8) | PDT_ADDR, &tmp, 1); if (tmp & 0x40) { #ifdef F54_Porting ret = sprintf(buf, "\nNon-Standard Page Description Table not supported\n"); #else pr_err("\nNon-Standard Page Description Table not supported\n"); #endif cleanExit(1); } FUNC_EXISTS = 0; /* reset flag */ j = 0; /* reset func addr info index */ while (1) { j++; readRMI((i << 8) | (PDT_ADDR - PDT_SIZE * j), in, 6); readRMI((i << 8) | 0xFF, &tmp, 1); if (in[5] == 0x00) { /* No more functions on this page */ if (FUNC_EXISTS == 0) { /* constructPrivRMI(); */ #ifdef F54_Porting write_log(buf); #endif return; } else { i++; } break; } else if (in[5] == 0x11) { /* Function11 */ F11_Query_Base = (i << 8) | in[0]; F11_Cmd_Base = (i << 8) | in[1]; F11_Ctrl_Base = (i << 8) | in[2]; F11_Data_Base = (i << 8) | in[3]; #ifdef F54_Porting ret += sprintf(buf + ret, "\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #else pr_err("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #endif } else if (in[5] == 0x34) { /* Function34 */ F34_Query_Base = (i << 8) | in[0]; F34_Cmd_Base = (i << 8) | in[1]; F34_Ctrl_Base = (i << 8) | in[2]; F34_Data_Base = (i << 8) | in[3]; #ifdef F54_Porting ret += sprintf(buf + ret, "\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #else pr_err("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #endif } else if (in[5] == 0x01) { /* Function01 */ F01_Query_Base = (i << 8) | in[0]; F01_Cmd_Base = (i << 8) | in[1]; F01_Ctrl_Base = (i << 8) | in[2]; F01_Data_Base = (i << 8) | in[3]; #ifdef F54_Porting ret += sprintf(buf + ret, "\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #else pr_err("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #endif } else if (in[5] == 0x54) { F54_Query_Base = (i << 8) | in[0]; F54_Command_Base = (i << 8) | in[1]; F54_Control_Base = (i << 8) | in[2]; F54_Data_Base = (i << 8) | in[3]; F54_Data_LowIndex = F54_Data_Base + 1; F54_Data_HighIndex = F54_Data_Base + 2; F54_Data_Buffer = F54_Data_Base + 3; F54_CBCSettings = F54_Control_Base + 8; #ifdef _DS4_3_0_ F54_PhysicalRx_Addr = F54_Control_Base + 18; #endif #ifdef F54_Porting ret += sprintf(buf + ret, "\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #else pr_err("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #endif } else if (in[5] == 0x1A) { F1A_Query_Base = (i << 8) | in[0]; F1A_Command_Base = (i << 8) | in[1]; F1A_Control_Base = (i << 8) | in[2]; F1A_Data_Base = (i << 8) | in[3]; F1A_Button_Mapping = F1A_Control_Base + 2; #ifdef F54_Porting ret += sprintf(buf + ret, "\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #else pr_err("\n-- RMI Function $%02X, Address = 0x%02x --\n", in[5], (PDT_ADDR - PDT_SIZE * j)); #endif } else { #ifdef F54_Porting ret += sprintf(buf + ret, "\n-- RMI Function $%02X not supported --\n", in[5]); #else pr_err("\n-- RMI Function $%02X not supported --\n", in[5]); #endif } FUNC_EXISTS = 1; } } while (FUNC_EXISTS == 1); }
int main( int argc, char **argv ) { Music music; int audio_rate, audio_channels, //set this to any of 512,1024,2048,4096 //the higher it is, the more FPS shown and CPU needed audio_buffers = 4096; #ifdef HAVE_SDL Uint16 audio_format; //initialize SDL for audio and video if (SDL_Init( SDL_INIT_AUDIO ) < 0) cleanExit( "SDL_Init\n" ); Mix_HookMusicFinished( &music_finished ); #else #ifdef __APPLE__ if ( !FSOUND_Init( 44100, 64, FSOUND_INIT_GLOBALFOCUS ) ) { printf( "SOUND Error %d\n", FSOUND_GetError() ); exit( 1 ); } #endif #endif INET_startup(); GetMaxVolume(); //initialize sdl mixer, open up the audio device #ifdef HAVE_SDL if (Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, audio_buffers ) < 0) cleanExit( "Mix_OpenAudio\n" ); //print out some info on the audio device and stream Mix_QuerySpec( &audio_rate, &audio_format, &audio_channels ); bits = audio_format&0xFF; #endif printf( "Opened audio at %d Hz %d bit %s, %d bytes audio buffer\n", audio_rate, bits, audio_channels > 1 ? "stereo" : "mono", audio_buffers ); //load the song for (int i = 0; i < 10 && mysocket == -1; i++) mysocket = INET_AcceptFrom( 4364, "localhost" ); if (mysocket == -1) return 1; printf( "\n[CONNECTED]\n" ); char ministr[2] = {'\0', '\0'}; while (!done) { //if ((Mix_PlayingMusic() || Mix_PausedMusic())&&(!done)) { char arg; std::string str; arg = INET_fgetc( mysocket ); printf( "%c", arg ); switch (arg) { case 'p': case 'P': arg = INET_fgetc( mysocket ); while (arg != '\0' && arg != '\n') { if (arg != '\r') { ministr[0] = arg; str += ministr; } arg = INET_fgetc( mysocket ); } printf( "%s", str.c_str() ); if ( (str != curmus || invalid_string) #ifdef HAVE_SDL || ( !Mix_PlayingMusic() ) #endif ) { music = PlayMusic( str.c_str(), music ); if (music.m) { printf( "\n[PLAYING %s WITH %d FADEIN AND %d FADEOUT]\n", str.c_str(), fadein, fadeout ); curmus = str; invalid_string = false; } else { printf( "\n[UNABLE TO PLAY %s WITH %d FADEIN AND %d FADEOUT]\n", str.c_str(), fadein, fadeout ); music_finished(); } } else { printf( "\n[%s WITH %d FADEIN AND %d FADEOUT IS ALREADY PLAYING]\n", str.c_str(), fadein, fadeout ); } break; case 'i': case 'I': arg = INET_fgetc( mysocket ); while (arg != '\0' && arg != '\n') { if (arg != '\r') { ministr[0] = arg; str += ministr; } arg = INET_fgetc( mysocket ); } printf( "%s", str.c_str() ); fadein = atoi( str.c_str() ); printf( "\n[SETTING FADEIN TO %d]\n", fadein ); break; case 'o': case 'O': arg = INET_fgetc( mysocket ); while (arg != '\0' && arg != '\n') { if (arg != '\r') { ministr[0] = arg; str += ministr; } arg = INET_fgetc( mysocket ); } printf( "%s", str.c_str() ); fadeout = atoi( str.c_str() ); printf( "\n[SETTING FADEOUT TO %d]\n", fadeout ); break; case 'v': case 'V': arg = INET_fgetc( mysocket ); while (arg != '\0' && arg != '\n') { if (arg != '\r') { ministr[0] = arg; str += ministr; } arg = INET_fgetc( mysocket ); } printf( "%s", str.c_str() ); volume = atof( str.c_str() ); printf( "\n[SETTING VOLUME TO %f]\n", volume ); music.SetVolume( volume ); break; case 't': case 'T': case '\0': INET_close( mysocket ); done = true; printf( "\n[TERMINATING MUSIC SERVER]\n" ); break; } } //free & close INET_cleanup(); #ifdef HAVE_SDL Mix_CloseAudio(); SDL_Quit(); #endif return 0; }