void prvCommsTask(void *pvParameters) { pvParameters = pvParameters; static uint8_t line[80]; static uint8_t characterPosition = 0; initGlobals(); /* Timer to cause outgoing communications to cease if nothing received for 10 seconds */ lapseCommsTimer = xTimerCreate("Lapse Comms",10000,pdFALSE,0,lapseCommsCallback); while(1) { /* Build a command line string before actioning. The task will block indefinitely waiting for input. */ char character; xQueueReceive(commsReceiveQueue,&character,portMAX_DELAY); if ((character == 0x0D) || (character == 0x0A) || (characterPosition > 78)) { if (lapseCommsTimer != NULL) xTimerReset(lapseCommsTimer,0); line[characterPosition] = 0; characterPosition = 0; parseCommand(line); } else line[characterPosition++] = character; } }
int main(int argc, char **argv) { #ifdef DEBUG /* flush stderr */ setvbuf(stdout, (char *) NULL, _IONBF, 0); #endif /* DEBUG */ /* init the callback library */ initCblib(); /* init global variables */ initGlobals(); /* check for ipv6 avilibility */ checkForIpv6(); /* parse arguments and set up sockets */ parseArgs(argc, argv); /* init and add own registrar */ initRegistrar(); /* find other registrars */ startRegistrarServerHunt(); /* start actions by starting main event handle loop */ handleEvents(); /* practically unreachable code */ return 1; }
int main (int argc, char **argv) { int ret = 0; // Check usage if (argc != 2) { fprintf(stderr, "usage: readCfg config-file-name\n"); exit(1); } // Initialize global data initGlobals(); // Display global variables: Before displayGlobals("\n\nBEFORE:\n======="); // Parse config file if ((ret = parseFile(argv[1])) == 0) { // Display global variables: After displayGlobals("\n\nAFTER:\n======"); } return ret; }
/* ======================================================================================================================= generate a new state for starting the next instance of climbing ======================================================================================================================= */ void genRandomConsistentState ( State **startState, long noOfBids, long numberCompanies, long numberBlocks, float *p, long timeInSeconds ) { freeStateObject(startState); initStateObject(startState, noOfBids); /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /* * printf("** %ld **", timeInSeconds); * code related to time from man pages */ struct timespec startTW, currentTW; /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ clock_gettime(CLOCK_MONOTONIC, &startTW); do { clock_gettime(CLOCK_MONOTONIC, ¤tTW); if(currentTW.tv_sec - startTW.tv_sec >= timeInSeconds) { freeStateObject(startState); initStateObject(startState, noOfBids); (*p) /= 2; break; } genRandomBoolList((*startState)->allocList, noOfBids, *p); } while(!isConsistent((*startState), numberCompanies, numberBlocks)); /*~~~~~~~~~~~~~~~~~~~~~~~*/ long i; Bid *currentBid = NULL; /*~~~~~~~~~~~~~~~~~~~~~~~*/ for(i = 0; i < (*startState)->lenAllocList; i++) { if((*startState)->allocList[i]) { currentBid = bidList[i]; (*startState)->value += currentBid->amount; } } initGlobals(*startState, numberCompanies, numberBlocks); }
void Matrix::initTable(int rows, int cols) { initGlobals(); d_view_type = TableView; d_matrix_model = new MatrixModel(rows, cols, this); initTableView(); // resize the table setGeometry(50, 50, QMIN(_Matrix_initial_columns_, cols)*d_table_view->horizontalHeader()->sectionSize(0) + 55, (QMIN(_Matrix_initial_rows_,rows)+1)*d_table_view->verticalHeader()->sectionSize(0)); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); #ifdef Q_OS_MACX // connect to plugins directory app.setLibraryPaths(app.applicationDirPath() + "/../PlugIns"); #endif parseCmdLine(argc, argv); initGlobals(); Clipboard::create(); PointSetStyles::create(); DefaultSettings::create(); DefaultSettings& rSettings = DefaultSettings::instance(); if (rSettings.getWindowMainFontOverride()) { app.setFont(QFont(rSettings.getWindowMainFontName(), rSettings.getWindowMainFontSize())); } QTranslator tor (0); // set the location where your .qm files are in load() below as the last parameter instead of "." // for development, use "/" to use the english original as // .qm files are stored in the base project directory. tor.load (QString("digitizer.") + QTextCodec::locale(), "."); app.installTranslator (&tor); DigitMain digitizer(cmdExport); qApp->setMainWidget(&digitizer); digitizer.show(); if (!cmdImport.isEmpty()) { if (cmdXYAxes) { digitizer.importImageFile(cmdImport, cmdXMinG, cmdXMaxG, cmdYMinG, cmdYMaxG); } else { digitizer.importImageFile(cmdImport); } } if (!cmdOpen.isEmpty()) digitizer.openDocumentFile (cmdOpen); return app.exec(); }
int main() { char *key = malloc (4), *value = malloc (4); char *res; strncpy(key, "foo", 4); strncpy(value, "bar", 4); printf("test 1: init\n"); initGlobals(); printf("test 2: count\n"); printf("\t%i\n",countGlobals()); printf("test 3: write (%s, %s) ...\n", key, value); res=setGlobal(key, value); printf("\t...%s\n", res); printf("test 4: count\n"); printf("\t%i\n",countGlobals()); res=0; printf("test 5: read foo...\n"); res=getGlobal(key); printf("\t...%s\n", res); res=0; printf("test 6: read other...\n"); res=getGlobal("zip"); printf("\t...%s\n", res); res=0; printf("test 7: remove other...\n"); res=removeGlobal("zip"); printf("\t...%s\n", res); printf("test 8: count\n"); printf("\t%i\n",countGlobals()); res=0; printf("test 9: remove foo...\n"); res=removeGlobal("foo"); printf("\t...%s\n", res); printf("test 10: count\n"); printf("\t%i\n",countGlobals()); printf("test 11: freeing\n"); freeGlobals(); return 0; }
// ************************************************************** void MainScene::init() { // Enables vector normalization glEnable(GL_NORMALIZE); initGlobals(); initCameras(); initLights(); unsigned long updatePeriod = 50; setUpdatePeriod(updatePeriod); display(); }
/* Main method: */ int main(int argc, char **argv) { handleCommandLineArguments(argc, argv); // OSG init OSG::osgInit(argc,argv); // GLUT init int winid = setupGLUT(&argc, argv); initGlobals(); { OSG::GLUTWindowUnrecPtr gwin= OSG::GLUTWindow::create(); gwin->setGlutId(winid); gwin->init(); OSG::NodeUnrecPtr scene = createScene(gwin); createAnimations(); OSG::commitChanges(); // Create the SimpleSceneManager helper G.mgr = OSG::SimpleSceneManager::create(); G.mgr->setUseTraversalAction(true); // Tell the manager what to manage: G.mgr->setWindow(gwin ); G.mgr->setRoot (scene); // Create a background: OSG::GradientBackgroundUnrecPtr bg = OSG::GradientBackground::create(); bg->addLine(OSG::Color3f(0.9f, 0.9f, 1.0f), 0); bg->addLine(OSG::Color3f(0.0f, 0.3f, 0.9f), 1); G.mgr->setBackground(bg); // Set the eye position: OSG::Pnt3f from(18,18,18); OSG::Pnt3f at (0,0,0); OSG::Vec3f up (0,1,0); setEyePositionHelper(from, at, up); } // GLUT main loop glutMainLoop(); return 0; }
void StMessageBox::Error(const StString& theMessage) { StLogger::GetDefault().write(theMessage, StLogger::ST_ERROR); #ifdef _WIN32 MessageBoxW(NULL, theMessage.toUtfWide().toCString(), L"Error", MB_OK | MB_ICONERROR | MB_SETFOREGROUND | MB_TOPMOST); #elif defined(__linux__) if(initGlobals()) { gdk_threads_enter(); GtkWidget* dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", theMessage.toCString()); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); gdk_flush(); // we need this call! gdk_threads_leave(); } #endif }
bool StMessageBox::Question(const StString& theMessage) { #ifdef _WIN32 return MessageBoxW(NULL, theMessage.toUtfWide().toCString(), L"Question", MB_YESNO | MB_ICONQUESTION | MB_SETFOREGROUND | MB_TOPMOST) == IDYES; #elif defined(__linux__) if(initGlobals()) { gdk_threads_enter(); GtkWidget* aDialog = gtk_message_dialog_new(NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, "%s", theMessage.toCString()); gint anAnswer = gtk_dialog_run(GTK_DIALOG(aDialog)); gtk_widget_destroy(aDialog); gdk_flush(); // we need this call! gdk_threads_leave(); return anAnswer == GTK_RESPONSE_YES; } return false; #endif }
uint8_t getData(dht11Data_t* recvData) { DHTPOUT &= ~DHTPIN; initGlobals(); // Config Timer TB0CCTL0 = CCIE; // TRCCR0 interrupt enabled TB0CCR0 = 54000; // 18ms @ 3MHz TB0CTL = TBSSEL_2 | ID_2 | MC_1 | TBCLR; // SMCLK/4 = 3MHz, upmode, clear TBR DHTPDIR |= DHTPIN; // set to output __bis_SR_register(LPM0_bits + GIE); recvData->rawData = receivedData; return verifyChecksum(recvData); // data is only valid if checkSum is OK }
int main(int argc, char **argv) { float mainLocal, mainLocalArray[19], * mainLocalPtr, mainInitLocal = 19, mainInitLocalArray[19] = {19}, * mainInitLocalPtr = & mainInitLocal; static float mainStaticLocal, mainStaticLocalArray[19], * mainStaticLocalPtr, mainStaticInitLocal = 19, mainStaticInitLocalArray[19] = {19}, * mainStaticInitLocalPtr = & mainStaticInitLocal; printf("Christopher Sorenson csorens2\n"); printf("%s %s from main\n",mainCHello, mainCWorld); //Make sure globals are ready initGlobals(); //Initialize local variables mainLocal = 19, mainLocalPtr = & mainLocal; for(int i = 0; i < 19; i++) mainLocalArray[i] = 19; mainStaticLocal = 19, mainStaticLocalPtr = & mainStaticLocal; for(int i = 0; i < 19; i++) mainStaticLocalArray[i] = 19; //Add up values int total = 0; //First local variables total += mainLocal + *mainLocalPtr + mainInitLocal + *mainInitLocalPtr + mainStaticLocal + *mainStaticLocalPtr + mainStaticInitLocal + *mainStaticInitLocalPtr; for(int i = 0; i < 19; i++) { total += mainLocalArray[i] + mainInitLocalArray[i] + mainStaticLocalArray[i] + mainStaticInitLocalArray[i]; } //Next globals total += mainCGlobal + *mainCGlobalPtr + mainCInitGlobal + *mainCInitGlobalPtr + mainCStaticGlobal + *mainCStaticGlobalPtr + mainCStaticInitGlobal + *mainCStaticInitGlobalPtr; for(int i = 0; i < 19; i++) { total += mainCGlobalArray[i] + mainCInitGlobalArray[i] + mainCStaticGlobalArray[i] + mainCStaticInitGlobalArray[i]; } total += func1C(mainCGlobal, & mainCGlobal); total += func2C(mainCGlobal, & mainCGlobal); printf("Current total after main, func1, func2, and func3: %d \n",total); }
int main( void ) { /* At this stage the microcontroller clock setting is already configured, this is done through SystemInit() function which is called from startup file (startup_stm32f2xx.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f2xx.c file */ /* NVIC configuration */ /* Configure the Priority Group to 4 bits: 4 bit pre-emption and 0 for subpriority */ NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 ); initGlobals(); GCPSUInit(); xTaskCreate( GCPSUTask, (const signed char*)"GCPSUTask", 64, NULL, 4, &GCPowerSupplyTaskHandle ); xTaskCreate( GCCommunicationTask, (const signed char*)"GCCommTask", 256, NULL, 6, &GCCommTaskHandle ); xTaskCreate( LedBlinkTask, (const signed char*)"LedBlinkTask", 64, NULL, 3, &ledBlinkTaskHandle ); xTaskCreate( SystemInitTask, (const signed char*)"SysInitTask", 128, NULL, 2, &SystemInitTaskHandle ); xTaskCreate( SystemPeriodicTask, (const signed char*)"SysPeriodicTk", 128, NULL, 4, &SystemPeriodicTaskHandle ); xTaskCreate( UpdateGPIOandBrakeTask, (const signed char*)"UpdateIOnBrake", 64, NULL, 5, &UpdateGPIOandBrakeTaskHandle ); xTaskCreate( SimpleMotionTask, (const signed char*)"SimpleMotion", 512, NULL, 2, &SimpleMotionTaskHandle ); xTaskCreate( SimpleMotionBufferedTask, (const signed char*)"SimpleMotionBuf", 512, NULL, 3, &SimpleMotionBufferedTaskHandle ); xTaskCreate( SlowTask, (const signed char*)"SlowTask", 128, NULL, 1, &SlowTaskHandle );//in the wrost case this task may not get execution time as SM task could eat all remaining power at higher priority xTaskCreate( EncoderOutputTask, (const signed char*)"EncoderOut", 128, NULL, 5, &EncoderOutTaskHandle ); // sys.setSignal(System::RunProductionTest); /* Start the scheduler. */ vTaskStartScheduler(); }
void Matrix::initImage(const QImage& image) { initGlobals(); d_view_type = ImageView; d_matrix_model = new MatrixModel(image, this); initImageView(); int w = image.width(); int h = image.height(); if (w <= 500 && h <= 400){ int size = QMAX(w, h); imageLabel->resize(size, size); } else imageLabel->resize(500, 500); displayImage(image); }
int CDECL main(int argc, char **argv) { if (argc ==1) { cerr << "Usage: makeeco eco_file" << endl; return -1; } Bitboard::init(); initOptions(argv[0]); Attacks::init(); Scoring::init(); if (!initGlobals(argv[0], false)) { cleanupGlobals(); exit(-1); } atexit(cleanupGlobals); ifstream eco_file( argv[argc-1], ios::in); if (!eco_file.good()) { cerr << "Cannot open file: " << argv[argc-1] << endl; return -1; } Board b; cout << "// This is a machine-generated file. Do not edit." << endl; cout << endl; cout << "#include \"ecodata.h\"" << endl << endl; cout << "const struct ECOData eco_codes[] =" << endl; cout << "{{" << '"' << "A00" << '"' << ", "; write_64(b.hashCode(),cout); cout << ", " << '"' << '"' << "}," << endl; int lines = 1; while (eco_file.good() && !eco_file.eof()) { string eco_line; getline(eco_file,eco_line); if (do_eco(eco_line)) { cerr << "error in ECO file, line " << lines << endl; } ++lines; } cout << "{0,0," << '"' << '"' << "}};" << endl; return 0; }
GermCellSimulator::GermCellSimulator(bool *valid, QWidget *parent) : QMainWindow(parent), ui(new Ui::GermCellSimulator) { srand(time(NULL)); this->sim = NULL; // Setup default settings set by Qt Designer ui->setupUi(this); // Initialize global variables if (!initGlobals()) { string message = "Please place the parameters.txt file in the same directory as the "; message.append("executable for this program"); QMessageBox msgBox(QMessageBox::Warning, tr("Parameter Read Error"), tr(message.c_str())); msgBox.exec(); *valid = false; return; } this->sim = new Simulator( ); // Install an event filter for the Graphics View. This will allow us to change which object // catches and handles events. See eventFilter() and wheelEvent(). ui->graphicsViewVisual->viewport()->installEventFilter(this); ui->graphicsViewVisual->setScene(&this->simModel); ui->graphicsViewVisual->setBackgroundBrush(QBrush(QColor("Black"))); this->initializeColors(); // Connect the timer's timeout signal with the update() slot. This will cause the update() slot // function to be called on each timer "tick". connect(&this->timer,SIGNAL(timeout()),this, SLOT(update())); this->picFileName = ""; this->flag_time = 0; *valid = true; }
int main(int argc, char **argv) { Client c; initGlobals(argc, argv); if (clientInit(&c) < 0) { fprintf(stderr, "ERROR: clientInit failed\n"); return -1; } // ok startup our connection to the server if (startConnection(&c, globals.host, globals.port, update_event_handler)<0) { fprintf(stderr, "ERROR: startConnection failed\n"); return -1; } shell(&c); return 0; }
int main(int argc, char **argv) { string directive; // input directive string strArg; // string argument double dblArg; // double argument int intArg; // integer argument KMdata* dataPts = NULL; // the data points KMalg alg; // which algorithm to use initGlobals(); // initialize global values getCmdArgs(argc, argv); kmOut->precision(4); // output precision *kmOut << "------------------------------------------------------------\n" << "kmltest: " << KMlongName << "\n" << " Version: " << KMversion << " " << KMversionCmt << "\n" << " Copyright: " << KMcopyright << ".\n" << " Latest Revision: " << KMlatestRev << ".\n" << "------------------------------------------------------------\n\n"; //-------------------------------------------------------------------- // Main input loop //-------------------------------------------------------------------- // read input directive while (getDirective(*kmIn, directive)) { //---------------------------------------------------------------- // Read options //---------------------------------------------------------------- if (directive == "quit") { kmExit(); } else if (directive == "dim") { *kmIn >> dim; new_clust = true; // force new clusters } else if (directive == "data_size") {
void Game::init() { if (initialized) { return; } initGlobals(); initialized = true; // SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) { Log::message(Log::Error, SDL_GetError()); exit(0); } // TTF if (TTF_Init()) { Log::message(Log::Error, TTF_GetError()); exit(0); } // SDLNet if (SDLNet_Init()) { Log::message(Log::Error, SDLNet_GetError()); exit(0); } // OpenAL if (!initOpenAL()) { Log::message(Log::Error, alError); exit(0); } initLocks(); Graphics::init(); Audio::init(); }
return_val Init( void ) { return_val error; const char * const *list; const char *name; hash_entry_data key_entry; error = RC_OKAY; OutputDest = STDOUT_FILENO; ChangePrintDest( OutputDest ); relocSections.first = NULL; relocSections.last = NULL; if( !MsgInit() ) { // MsgInit does its own error message printing return( RC_ERROR ); } MemOpen(); error = HandleArgs(); if( error != RC_OKAY ) { return( error ); } openFiles(); initGlobals(); error = initHashTables(); if( error != RC_OKAY ) { PrintErrorMsg( error, WHERE_INIT_HASH_TABLES ); return( error ); } error = initServicesUsed(); if( error != RC_OKAY ) { // initServicesUsed does its own error message printing return( error ); } error = initSectionTables(); if( error != RC_OKAY ) { PrintErrorMsg( error, WHERE_CREATE_SEC_TABLES ); return( error ); } if( Options & PRINT_PUBLICS ) { CreatePublicsArray(); } if( IsMasmOutput() ) { CommentString = MASM_COMMENT_STRING; } if( IsIntelx86() ) { SkipRefTable = HashTableCreate( RECOGNITION_TABLE_SIZE, HASH_STRING_IGNORECASE ); if( SkipRefTable != NULL ) { for( list = intelSkipRefList; (name = *list) != NULL; ++list ) { key_entry.key.u.string = name; key_entry.data.u.string = *list; error = HashTableInsert( SkipRefTable, &key_entry ); if( error != RC_OKAY ) { break; } } } } if( LabelChar == 0 ) { if( IsMasmOutput() ) { LabelChar = 'L'; } else { LabelChar = 'X'; } } return( error ); }
int update_with_box_scores(Model **m, Hmm **tmp_hmm, RMat *data, Real **postpC, Real log_D, int *c_ls, int ll, int cc, enum training_mode training_mode, int upper_triangular, RMat *score_matrices) { /* tmp_hmm[c] is scratch space. It must have at least as many states as m[c]->hmm. */ /* needs work: must call compute_posterior externally */ int c, l, u; int *xu; Real** scores; for (c = 0; c<cc; c++) { if (g_lastData!=data||ll>g_ll||m[c]->uu>g_uu) { g_lastData = data; initGlobals(ll, m[c]->uu, data); } zeroHMMlinear(tmp_hmm[c]); for (l = 0; l<ll; l++) { scores = MATRIX(score_matrices[l]); switch (training_mode) { case HMM_ML: if (c!=c_ls[l]) continue; for (u = 0; u<m[c]->uu; u++) { FFM_logL_with_box_scores(m[c]->ffm[u], g_logL[l][u], data[l],scores[u]); } HMM_updateModel(m[c]->hmm, tmp_hmm[c], g_logL[l], g_gamma[l], log_D, 0.0, -1, -1, training_mode); break; case HMM_DT: for (u = 0; u<m[c]->uu; u++) { FFM_logL_with_box_scores(m[c]->ffm[u], g_logL[l][u], data[l],scores[u]); } HMM_updateModel(m[c]->hmm, tmp_hmm[c], g_logL[l], g_gamma[l], log_D, my_exp(postpC[c][l]), c, c_ls[l], training_mode); break; default: panic("unrecognized training mode"); } } xu = (int *)safe_malloc(sizeof(int) * m[c]->uu); if (!normaliseHMMlinear(tmp_hmm[c], upper_triangular, training_mode, xu)) { assert(training_mode == HMM_DT); free(xu); return FALSE; } /*if !normaliseHMMlinear(tmp_hmm[c], upper_triangular)) { assert(training_mode == HMM_DT); return FALSE; }*/ copyHMM(m[c]->hmm, tmp_hmm[c]); for (u = 0; u<m[c]->uu; u++) { switch (training_mode) { case HMM_ML: assert(FFM_maximise(m[c]->ffm[u], data, g_gamma_r[u], ll, log_D, NULL, c, c_ls)); break; case HMM_DT: if (!FFM_maximise(m[c]->ffm[u], data, g_gamma_r[u], ll, log_D, postpC[c], c, c_ls)) return FALSE; break; default: panic("unrecognized training mode"); } } } return TRUE; }
/* update - Performs a single update on the HMM model for the given data. */ int update(Model **m, Hmm **tmp_hmm, RMat *data, Real **postpC, Real log_D, int *c_ls, int ll, int cc, enum training_mode training_mode, int upper_triangular) { /* tmp_hmm[c] is scratch space. It must have at least as many states as m[c]->hmm. */ int c, l, u; int *xu; for (c = 0; c<cc; c++) { if (g_lastData!=data||ll>g_ll||m[c]->uu>g_uu) { g_lastData = data; initGlobals(ll, m[c]->uu, data); } zeroHMMlinear(tmp_hmm[c]); for (l = 0; l<ll; l++) { switch (training_mode) { case HMM_ML: if (c!=c_ls[l]) continue; for (u = 0; u<m[c]->uu; u++) { FFM_logL(m[c]->ffm[u], g_logL[l][u], data[l]); } HMM_updateModel(m[c]->hmm, tmp_hmm[c], g_logL[l], g_gamma[l], log_D, 0.0, -1, -1, training_mode); break; case HMM_DT: for (u = 0; u<m[c]->uu; u++) { FFM_logL(m[c]->ffm[u], g_logL[l][u], data[l]); //if(g_logL[l][u][tt-1] != NEGATIVE_INFINITY) flag = 1; } HMM_updateModel(m[c]->hmm, tmp_hmm[c], g_logL[l], g_gamma[l], log_D, my_exp(postpC[c][l]), c, c_ls[l], training_mode); break; default: panic("unrecognized training mode"); } } xu = (int *)safe_malloc(sizeof(int) * m[c]->uu); if (!normaliseHMMlinear(tmp_hmm[c], upper_triangular, training_mode, xu)) { assert(training_mode == HMM_DT); free(xu); return FALSE; } copyHMM(m[c]->hmm, tmp_hmm[c]); for (u = 0; u<m[c]->uu; u++) { switch (training_mode) { case HMM_ML: assert(FFM_maximise(m[c]->ffm[u], data, g_gamma_r[u], ll, log_D, NULL, c, c_ls)); break; case HMM_DT: if (!FFM_maximise(m[c]->ffm[u], data, g_gamma_r[u], ll, log_D, postpC[c], c, c_ls)){ free(xu); return FALSE; } break; default: panic("unrecognized training mode"); } } /* Remove redundant states by shifting the memory if necessary. */ for(u = 0; u < m[c]->uu; u ++) if(xu[u]) break; if(u < m[c]->uu) removeStates(m[c], xu, tmp_hmm[c]); free(xu); } return TRUE; }
void Init( void ) { char cmd_line[ CMD_LINE_LEN ]; return_val error; char **list; OutputDest = STDOUT_FILENO; ChangePrintDest( OutputDest ); relocSections.first = NULL; relocSections.last = NULL; if( !MsgInit() ) { // MsgInit does its own error message printing exit( -1 ); } MemOpen(); getcmd( cmd_line ); HandleArgs( cmd_line ); openFiles(); initGlobals(); error = initHashTables(); if( error == OKAY ) { error = initServicesUsed(); if( error == OKAY ) { error = initSectionTables(); if( error != OKAY ) { // free hash tables and services MemClose(); LeaveProgram( error, WHERE_CREATE_SEC_TABLES ); } } else { // free hash tables CloseFiles(); FreeHashTables(); // initServicesUsed does its own error message printing exit( error ); } } else { CloseFiles(); MemClose(); LeaveProgram( error, WHERE_INIT_HASH_TABLES ); } if( Options & PRINT_PUBLICS ) { CreatePublicsArray(); } if( IsMasmOutput() ) { CommentString = MASM_COMMENT_STRING; } if( IsIntelx86() ) { SkipRefTable = HashTableCreate( RECOGNITION_TABLE_SIZE, HASH_STRING, (hash_table_comparison_func) stricmp ); if( SkipRefTable ) { list = intelSkipRefList; while( *list ) { error = HashTableInsert( SkipRefTable, (hash_value) *list, (hash_data) *list ); if( error != OKAY ) break; list++; } } } if( !LabelChar ) { if( IsMasmOutput() ) { LabelChar = 'L'; } else { LabelChar = 'X'; } } }
// SetUp ReaderTests() { // initialize ybscheme initGlobals(); initReader(); flushReaderInputStream(); }
/** Function called in a protected Lua state. * * Initialize the Lua state if the global service has not been defined, * then do something. This function assumes that the caller is living * within the constraints of lua_cpcall(), meaning that it is passed * exactly one argument on the Lua stack which is a light userdata * wrapping an opaque pointer, and it isn't allowed to return anything. * * That pointer must be either NULL or a pointer to a C string naming the * script file or code fragment to load and execute in the Lua context. * * If a NULL is passed, the private registry value PENDING_WORK is pushed * and called. Any results are collected in a table and stored in the * registry at the private key WORK_RESULTS, and the value at PENDING_WORK * is freed to the the garbage collector. * * If a non-null string is passed, it is loaded (but not called) and * stored in the registry at the private key PENDING_WORK. Any prevous * work results are released to the the garbage collector. * * A string is assumed to be a file name, but a future version probably * should allow for a litteral script as well. * * \param L Lua state context for the function. * \returns The number of values on the Lua stack to be returned * to the Lua caller. */ static int pmain(lua_State *L) { char szPath[MAX_PATH+1]; char *cp; char *arg; int status; arg = (char *)lua_touserdata(L,-1); lua_getglobal(L, "service"); if (!lua_toboolean(L,-1)) { lua_gc(L, LUA_GCSTOP, 0); /* stop gc during initialization */ luaL_openlibs(L); /* open libraries */ initGlobals(L); lua_gc(L, LUA_GCRESTART, 0); } lua_pop(L,2); /* don't need the light userdata or service objects on the stack */ if (arg) { // load but don't call the code // first, release any past results lua_pushnil(L); local_setreg(L,WORK_RESULTS); lua_pushnil(L); local_setreg(L,PENDING_WORK); /** * \note The script file name is always relative to the * service folder. This protects against substitution of * the script by a third party, at least to some degree. */ GetModuleFileName(GetModuleHandle(NULL), szPath, MAX_PATH); cp = strrchr(szPath, '\\'); if (cp) { cp[1] = '\0'; if ((cp - szPath) + strlen(arg) + 1 > MAX_PATH) return luaL_error(L, "Script name '%s%s' too long", szPath, arg); strcpy(cp+1, arg); } else { return luaL_error(L, "Module name '%s' isn't fully qualified", szPath); } SvcDebugTraceStr("Script: %s\n", szPath); status = luaL_loadfile(L,szPath); if (status) { return luaL_error(L,"%s\n",lua_tostring(L,-1)); } local_setreg(L,PENDING_WORK); return 0; } else { int n; int i; int results; // call pending code and save any results // first, release any past results lua_pushnil(L); local_setreg(L,WORK_RESULTS); lua_createtable(L, 5, 0); results = lua_gettop(L); //#define NO_DEBUG_TRACEBACK #ifdef NO_DEBUG_TRACEBACK n = lua_gettop(L); local_getreg(L,PENDING_WORK); status = lua_pcall(L,0,LUA_MULTRET,0); #else lua_getglobal(L,"debug"); // debug lua_getfield(L, -1, "traceback"); // debug debug.traceback lua_remove(L, -2); // debug.traceback n = lua_gettop(L); local_getreg(L,PENDING_WORK); // debug.traceback function if (lua_type(L,-1) != LUA_TFUNCTION) return luaL_error(L,"No pending work function to run"); status = lua_pcall(L, 0, LUA_MULTRET, -2); // debug.traceback ... #endif if (status) { return luaL_error(L,"%s\n",lua_tostring(L,-1)); } SvcDebugTrace("Saved work result count: %d", lua_gettop(L) - n); for (i=lua_gettop(L); i>n; --i) { SvcDebugTraceStr("item: %s", lua_typename(L,lua_type(L,-1))); lua_rawseti(L,results,i-n); } assert(lua_gettop(L) == n); if (lua_gettop(L) != results) lua_settop(L, results); assert(lua_type(L,-1) == LUA_TTABLE); local_setreg(L,WORK_RESULTS); return 0; } }
int main() { // Initialize globals initGlobals(); // Window window.setSize(sf::Vector2u(window_width, window_height)); window.setPosition(sf::Vector2i(200, 200)); window.setFramerateLimit(FRAMES_PER_SECOND); //window.setVerticalSyncEnabled(true); window.setKeyRepeatEnabled(false); // Camera view sf::View windowView; // Menu initializeMenu(); // UI ui.init(); // Minimap // Minimap minimap; // Create & Set contactlistener BoxContactListener boxContactListener; physicsWorld.SetContactListener(&boxContactListener); // Build world //gameWorld.generateWorld(physicsWorld); // ------------------------------- MAIN LOOP ------------------------------- while(window.isOpen()) { // ------------------------------- Input & Views ------------------------------- sf::Event event; gameEvents.processEvents(window, event); // Update view in case of window resize window_width = window.getSize().x; window_height = window.getSize().y; windowView.setSize(window_width, window_height); // if(minimap.updateViewThroughMinimap) // { // windowView.setCenter(minimap.newViewCenter.x, minimap.newViewCenter.y); // } if(player.hasNewFocus) { windowView.setCenter(player.getNewFocus().x, player.getNewFocus().y); } // Update normal view with inputs windowView = updateView(windowView); if(gameWorld.completionStarted && gameWorld.completionTimer.timeReached()) { windowView.setCenter(window_width/2, window_height/2); global_levelComplete = false; } // Clear window window.clear(sf::Color(255, 255, 255, 255)); if(global_isMenu) { ui.setSize(window_width, window_height); window.setView(ui.getView()); menu_logo_bottom->setPosition(window_width - textures["menu_logo_bottom"].getSize().x, window_height - textures["menu_logo_bottom"].getSize().y); menu.update(gameEvents); menu.draw(window); // Instructions if(show_instructions) { showInstructions(); if(show_instructions_controls) { showControls(); } if(show_instructions_gameplay) { showGameplay(); } } } else { window.setView(windowView); // ------------------------------- Updates ------------------------------- // Player player.update(physicsWorld, gameEvents, gameWorld); if(!global_isPaused) { // Physics physicsWorld.Step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS); // World gameWorld.update(gameEvents, physicsWorld, player); // UI ui.update(gameWorld, player); } // Calculate viewable area int viewShiftX = window.getSize().x/2 - window.getView().getCenter().x; int viewShiftY = window.getSize().y/2 - window.getView().getCenter().y; int windowMinX = -100 - viewShiftX; int windowMaxX = windowMinX + window_width + 200; int windowMinY = -100 - viewShiftY; int windowMaxY = windowMinY + window_height + 200; // ------------------------------- Drawing ------------------------------- window.setView(ui.getView()); // Background sf::Vertex rectangle[] = { sf::Vertex(sf::Vector2f(0.0f, 0.0f), sf::Color(0, 100, 130, 255)), sf::Vertex(sf::Vector2f(window_width, 0.0f), sf::Color(0, 100,130, 255)), sf::Vertex(sf::Vector2f(window_width, window_height), sf::Color(0, 200, 230, 255)), sf::Vertex(sf::Vector2f(0.0f, window_height), sf::Color(0, 200, 230, 255)) }; window.draw(rectangle, 4, sf::Quads); window.setView(windowView); // World & Player gameWorld.draw(window, b2Vec2(windowMinX, windowMinY), b2Vec2(windowMaxX, windowMaxY), false); player.draw(window); // HUD !!CLASS!! ui.setSize(window_width, window_height); window.setView(ui.getView()); if(!gameWorld.completionTimer.timeReached() && gameWorld.completionStarted) { sf::Text temp("You have won", font_default, 40); int midX = window_width / 2.0f - 100; int midY = window_height / 2.0f - 40; temp.setPosition(midX, midY); temp.setColor(sf::Color::White); window.draw(temp); } if(global_isPaused) { sf::RectangleShape rect; rect.setSize(sf::Vector2f(window_width, window_height)); rect.setPosition(0,0); rect.setFillColor(sf::Color(100, 100, 100, 155)); window.draw(rect); } ui.draw(window); // sf::RectangleShape border; // border.setPosition(0.0f, window_height - (window_height*minimapSize + MINIMAP_BORDER_SIZE)); // border.setSize(sf::Vector2f(window_width*minimapSize + MINIMAP_BORDER_SIZE, window_height*minimapSize + MINIMAP_BORDER_SIZE)); // border.setFillColor(sf::Color(0, 0, 200, 255)); // // window.draw(border); // // // ------------------------------- Minimap ------------------------------- // // minimap.setSize(MAX_WORLD_WIDTH * BOX_SIZE, MAX_WORLD_WIDTH * BOX_SIZE, window_width, window_height); // minimap.calcViewport(minimapSize); // minimap.setCameraPosition(windowView.getCenter().x, windowView.getCenter().y); // window.setView(minimap.getUpdatedView()); // // minimap.update(gameEvents); // // minimap.draw(window); // gameWorld.draw(window, b2Vec2(-10000, -20000), b2Vec2(10000, 10000), true); // player.draw(window); // minimap.drawCameraWindow(window); // Default View again window.setView(windowView); } // Display window.display(); } return 0; }
int main(int argc, char **argv) { Client c; if (!FASTINPUTMODE) fprintf(stderr, "Type 'connect <host:port>' to connect to a game.\n"); if (clientInit(&c) < 0) { fprintf(stderr, "ERROR: clientInit failed\n"); return -1; } initGlobals(argc, argv); if (FASTINPUTMODE) { startConnection(&c, globals.host, globals.port, update_event_handler); doRPCCmd(&c, 'q'); //query for the map if (STRESS_TEST==1) proto_client_hello(c.ph); } shell(&c); // Cannot put shell on a separate thread because fget() function doesn't work for some reason // pthread_t tid; // pthread_create(&tid, NULL, shell, &c); Proto_Client *proto_client = c.ph; Player *me = getPlayer(&proto_client->game, proto_client->playerID); if (DISPLAYUI==1) { // If I am not the host and we are stress testing, I should be wandering if (me->isHost==0 && STRESS_TEST==1) { // Wander(&c, 0); docmd(&c, "test\n"); } // The host will be the only ones that has UI showing, other players just wonder else { //window will be consistently 20x20 // pthread_t tid; // pthread_create(&tid, NULL, shell, NULL); // Init for UI stuff tty_init(STDIN_FILENO); ui_init(&(ui)); // WITH OSX ITS IS EASIEST TO KEEP UI ON MAIN THREAD // SO JUMP THROW HOOPS :-( Proto_Client *client = (Proto_Client *) c.ph; Player *me = getPlayer(&client->game, client->playerID); doRPCCmd(&c, 'q'); //query for the map ui_main_loop(ui, (32 * WINDOW_SIZE), (32 * WINDOW_SIZE), &client->game, me, &c); } } // launchUI(&c); return 0; }
/* * Initialize all necessary state, and indicate that we're ready to go. */ static void initOnce(void) { initGlobals(); initGeneral(); }
int main(int argc, char **argv){ // Be nice to other processes. Helps reduce mouse lag setpriority(PRIO_PROCESS, 0, 20); // Make sure we're running in the exe's directory char path[PATH_MAX]; if (realpath("/proc/self/exe", path)){ char *slash = strrchr(path, '/'); if (slash) *slash = '\0'; chdir(path); } initGlobals(); float runTime = 1e30f; float staticTime = 0; bool isStatic = false, lastStatic = false; for (int i = 1; i < argc; i++){ if (strcmp(argv[i], "-r") == 0 || strcmp(argv[i], "--run-for") == 0){ if (++i < argc){ runTime = atof(argv[i]); } } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--static") == 0){ isStatic = true; lastStatic = true; continue; } else if (lastStatic){ staticTime = atof(argv[i]); } else { printf("Unknown argument: %s\n", argv[i]); } lastStatic = false; } Display *display; int screen; initCPU(); cpuHz = getHz(); if (!app->init()) return 0; app->resetCamera(); display = XOpenDisplay(0); screen = DefaultScreen(display); app->setDisplay(display, screen); app->initDisplayModes(); app->initMenu(); //toggleFullscreen = false; time = 0; // uint64 prev, curr = getCycleNumber(); timeval prev, curr; gettimeofday(&curr, NULL); float rTime = 0; do { //if (toggleFullscreen) fullscreen = !fullscreen; toggleFullscreen = false; captureMouse = fullscreen; if (fullscreen) app->setDisplayMode(width = fullscreenWidth, height = fullscreenHeight, refreshRate); if (app->initAPI()){ app->showCursor(!captureMouse); if (captureMouse) XWarpPointer(display, None, window, 0,0,0,0, middleX, middleY); if (app->load()){ XEvent event; unsigned int key; done = false; do { ///* while (XPending(display) > 0){ XNextEvent(display, &event); switch (event.type){ case Expose: if (event.xexpose.count != 0) break; break; case MotionNotify: if (captureMouse){ static bool changeMouse; float mouseSensibility = 0.0005f * mouseSpeed; //app->rotateView(mouseSensibility * (middleY - event.xmotion.y) * (invertMouse? 1 : -1), // mouseSensibility * (middleX - event.xmotion.x)); //float a = mouseSensibility * (middleY - event.xmotion.y) * (invertMouse? 1 : -1); //float b = mouseSensibility * (middleX - event.xmotion.x); mousexxxxxx = mouseSensibility * (middleY - event.xmotion.y) * (invertMouse? 1 : -1); mouseyyyyyy = mouseSensibility * (middleX - event.xmotion.x); printf("%f %f\n", mouseSensibility, middleY); if (changeMouse = !changeMouse) XWarpPointer(display, None, window, 0,0,0,0, middleX, middleY); } app->setMousePos(event.xmotion.x, event.xmotion.y, 0); break; case ConfigureNotify: app->setViewport(width = event.xconfigure.width, height = event.xconfigure.height); if (!fullscreen){ windowedLeft = event.xconfigure.x; windowedRight = event.xconfigure.width + windowedLeft; windowedTop = event.xconfigure.y; windowedBottom = event.xconfigure.height + windowedTop; } middleX = event.xconfigure.width / 2; middleY = event.xconfigure.height / 2; break; case ButtonPress: if (!captureMouse && event.xbutton.button == 1){ //XGrabPointer(display, window, True, ButtonPressMask, GrabModeAsync, GrabModeAsync, window, blankCursor, CurrentTime); app->showCursor(false); XWarpPointer(display, None, window, 0, 0, 0, 0, middleX, middleY); captureMouse = true; } app->setButton((event.xbutton.button == 1)? MOUSE_LEFT : MOUSE_RIGHT, true); break; case ButtonRelease: app->setButton((event.xbutton.button == 1)? MOUSE_LEFT : MOUSE_RIGHT, false); break; case KeyPress: key = XLookupKeysym(&event.xkey, 0); if (key == XK_Return && app->getKey(XK_Alt_L)){ app->toggleScreenMode(); app->closeWindow(); } else { app->processKey(key); char str[8]; int nChar = XLookupString(&event.xkey, str, sizeof(str), NULL, NULL); for (int i = 0; i < nChar; i++) app->processChar(str[i]); } break; case KeyRelease: key = XLookupKeysym(&event.xkey, 0); app->setKey(key, false); break; case ClientMessage: if (*XGetAtomName(display, event.xclient.message_type) == *"WM_PROTOCOLS"){ app->closeWindow(); } break; default: break; } } //*/ prev = curr; // curr = getCycleNumber(); // frameTime = (float) (double(curr - prev) / cpuHz); gettimeofday(&curr, NULL); frameTime = (float(curr.tv_sec - prev.tv_sec) + 0.000001f * float(curr.tv_usec - prev.tv_usec)); if (isStatic){ time = staticTime; } else { time += frameTime; } rTime += frameTime; if (rTime > runTime) done = true; app->controls(); /*int a = 0; for (unsigned long int i = 0; i < 10000000000; i++){ a++; } printf("%d ",a);*/ app->beginFrame(); app->drawFrame(); app->drawGUI(); app->endFrame(); } while (!done); app->unload(); } else { printf(getLogString()); } app->closeAPI(); } else { printf(getLogString()); } //if (fullscreen) app->resetDisplayMode(); XDestroyWindow(display, window); } while (toggleFullscreen); if (fullscreen) app->resetDisplayMode(); app->exit(); delete app; XCloseDisplay(display); flushGlobals(); clearLog(); return 0; }